Check if regenerate_session_id() function actually works / Other security questions - php

I am building a website and i would like to secure it against Session Hijacking. Reading for this i came across someone saying that:
A general rule of thumb is to generate the session ID each time a user changes his access level.
1.When a user log in
2.When a user log out
3.When a user get administrative access
For what is worth, my website will be seperating the access levels into users logged-in and users logged-out. All forms are submitted using the POST method.
index.php
<?php
session_start();
//Setting the variable initialy to false
$_SESSION['LOGGED_IN'] = FALSE;
//to use SSL
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(isset($_POST['SUBMIT']))
{
if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])
{
//Open database connection
require_once('connect_db.php');
//Calling functions.php that includes all custom functions
//ErrorHandler()
require_once('functions.php');
$email = $_POST['EMAIL'];
$password = $_POST['PASSWORD'];
$statement = $DBH->prepare("SELECT * FROM user_details WHERE email=:email AND pwd=:password ");
$statement->bindParam(':email',$email);
$statement->bindParam(':password',$password);
$statement->setFetchMode(PDO::FETCH_ASSOC);
try{
$result = $statement->execute();
$rows = $statement->rowCount(); // shows how many times the user is available in the user_details table
$data = $statement->fetch(); //fetches the data related to that user from user_details table
}
catch(PDOException $e)
{
//this is custom function
echo ErrorHandler($e);
}
if($rows == 1)
{
//this means that the user has inserted the correct credentials
//regenerate session_id each time there is a change in the level of privilege to mitigate SESSION FIXATION
session_regenerate_id(true);
//turning logged in variable to true as soon as it finds a match
$_SESSION['LOGGED_IN'] = TRUE;
//saves the email into a session so it can be used in mainpage.php
$_SESSION['EMAIL'] = $email;
//redirect to main page
header('Location:https://www.example.com/mainpage.php');
}
else
{
echo "<br />Wrong username or password!<br />";
}
}//closing *if(isset($_POST['TOKEN']) && $_POST['TOKEN'] == $_SESSION['TOKEN'])*
}//closing *if($_POST['SUBMIT'])*
//creating a random token to inject in our HTML form
$token = base64_encode(openssl_random_pseudo_bytes(32));
//store the random token in the session variable so we can later compare it to the one in the HTML form
$_SESSION['TOKEN'] = $token;
?>
<form action="index.php" method="POST" accept-charset="UTF-8">
<p>Email: <input type="email" name="EMAIL" /> </p>
<p><input type="hidden" name="TOKEN" value="<?php echo $token; ?>" /></p>
<p>Password <input type="password" name="PASSWORD" /> </p>
<p><input type="submit" name="SUBMIT" value="Submit" /></p>
</form>
The script accepts input email and password from the user,checks the database and if it finds a match it redirects the user to the mainpage.php.
mainpage.php
<?php
ob_start();
//the code to set the header must be called before output begins
session_start();
$serverport = $_SERVER['SERVER_PORT'];
$server_http_host = $_SERVER['HTTP_HOST'];
$server_request_uri = $_SERVER['REQUEST_URI'];
if (headers_sent())
{
die("HTTP headers have already been sent ");
}
else
{
if($serverport != '443')
{
ob_start();
exit(header('Location: https://'.$server_http_host.$server_request_uri));
}
}
if(($_SESSION['LOGGED_IN'] == TRUE) && isset($_SESSION['LOGGED_IN']))
{
$email = $_SESSION['EMAIL'];
echo $email;
//Calling functions.php that includes all custom functions
//LogOut()
require_once('functions.php');
if(isset($_POST['LOGOUT']))
{
//its a custom function that is used for logging out
LogOut();
}
echo '
<form method="POST" action="mainpage.php">
<p><input type="submit" name="LOGOUT" value="Log Out" /></p>
</form>
';
}
else
{
echo "Please login in order to use example.com";
}
?>
Is there a way for me to check if the way i have built these 2 scripts really regenerate the Session ID? I am using Firefox's extension LIVE HTTP headers but i am not sure if i am reading it correctly.
Also, i cannot find a way to track down and read the content of COOKIES stored while using my browser (either Chrome or Firefox or even IE11). How can i do that?
Another question that is related with security:
Implementing an anti-CSRF token:
Do i need to implement an anti-CSRF token for each form in my website [i guess the answer is Yes but i want to confirm it]? Should each token be different than the token used in a previous form? For example the token in index.php to be different than the token used in mainpage.php if it had a form as well.
Does the token technique prevent against any other kind of attack?
I would be glad if you indicate wrong programming in the code above, so i can correct it and learn at the same time.
Thanks!

I'm going to focus on your questions and not necessarily a thorough code review, since I think your questions are the main reason you're posting.
A simple way to check your current session id or PHPSESSID is to check under Chrome's Developer Tools > Resources > Cookies. You'll see the (initially-generated) session ID. You can check this value before and after a user logs in. If the value changes, your session id has actually been regenerated.
You can also view cookies in Firefox by right-clicking the current page, going to View Page Info and using the Cookies tab.
On CSRF (prevention) tokens, the answer varies. People use different methods to go about them. I would say a majority of websites set a token in $_SESSION upon any regenerate of the session id. So for the duration of the current session, the CSRF token will remain the same and check against hidden inputs for that CSRF token.
On the other hand, I've also heard of regenerating a CSRF token for every single form that is client-facing. Your way of doing it is up to you. Nothing is 100% bulletproof, but getting as close to 100% as you can is the idea.
Take a few minutes to read up on CSRF tokens and the Synchronizer Token Pattern.
Best of luck!

Related

PHP: Setting the session information in a cookie won't be kept after page reloads?

I have a very simple php single page, that requires the user to insert a specific username and pass in order to access its contents.
It generates a cookie that allows the user to access that page for one day.
If the user is logged in, the list of contents appear. If it's not, it shows the form.
It is all inside a single index.php page.
This single "protected" page contains a form where the user can put some information and save it. After the user logs in, all the content is shown as intended. But when the user tries to submit that form and reloads the page (the new content should be added to that page), it gets kicked out and the information contained in the form gets lost, and it's not saved.
This are the specific parts of the index.php page:
<?php session_start(); ?>
<!DOCTYPE html>
[...]
<?php
if(isset($_POST['loguearse'])) {
$_SESSION['user']=strip_tags($_POST['user']);
$_SESSION['pass']=strip_tags($_POST['pass']);
if($_SESSION['user'] == 'myuser' && $_SESSION['pass'] == 'mypass') {
if (isset($_SESSION['user'])) {
session_start();
setcookie ("usuario",$_POST['user'], time()+24*60*60);
setcookie ("clave",$_POST['pass'], time()+24*60*60);
}
[HERE IT GOES THE CONTENT THAT WORKS OK IF I STRIP THE LOGIN CONTROL]
}
} else {
setcookie("usuario","");
setcookie("clave","");
echo '
<form method="post">
<div class="form-group">
<input type="text" class="form-control" name="user" id="user" placeholder="Usuario">
</div>
<div class="form-group">
<input type="password" class="form-control" name="pass" id="pass" placeholder="clave">
</div>
</div>
<div class="modal-footer">
<input type="submit" name="loguearse" class="btn btn-primary">
</div>
</div>
</form>
';
echo 'No puedes entrar sin poner la clave correcta!';
}
?>
My question is: How do I keep that user logged in and with an active session for 24 hours?
Your testing order is the problem here. You are originally testing for the POST variable, not the SESSION variable. Try this:
Test for logout to see if the user tried to logout. If so, delete the session.
Test for the session variables to indicate they're already logged in.
IF 1 and 2 are false, test for login. If so, initialize session.
It's the way you construct your if-conditions. Every time the user doesn't submit a post form you overwrite the cookie. The condition isset($_SESSION['user']) has to be on the highest level (at first) and then the post form check.
Also you run twice session_start(), one time is enough.
I use this for this exact thing and just include this in the header of any page.
<?php
#session_start();
// DB DEFINITIONS
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/db.php');
$db = db_connect();
if(isset($_GET['logout'])){
session_unset();
session_destroy();
if (isset($_COOKIE['cookuhash']) && isset($_COOKIE['cookfhash'])){
setcookie("cookuhash", "", time()-2592000,"/");
setcookie("cookfhash", "", time()-2592000,"/");
$uhash=$db->real_escape_string($_COOKIE['cookuhash']);
$fhash=$db->real_escape_string($_COOKIE['cookfhash']);
$db->query("DELETE FROM tblsessions WHERE USER_HASH='$uhash' AND FORM_TOKEN='$fhash'");
}
header("Location: /index.php");
exit();
}
if(!isset($_SESSION['loggedIn'])){
$_SESSION['loggedIn']=false;
$_SESSION['username'] = 'Anonymous';
$_SESSION['userid'] = 0;
$_SESSION['userlevel'] = 0;
$_SESSION['formToken'] = sha1(microtime());
}
if (!$_SESSION['loggedIn'] && isset($_COOKIE['cookuhash']) && isset($_COOKIE['cookfhash'])){
$uhash=$db->real_escape_string($_COOKIE['cookuhash']);
$fhash=$db->real_escape_string($_COOKIE['cookfhash']);
$result = $db->prepare("SELECT u.id,uname, lvl, user_lvl_expires FROM tblusers u LEFT JOIN tblsessions s ON s.USER_ID=u.ID WHERE USER_HASH='$uhash' AND FORM_TOKEN='$fhash'");
$result->execute();
$result->bind_result($id,$uname,$ads,$lvl,$expires);
$result->store_result();
if($result->num_rows > 0){
while ($result->fetch()) {
$_SESSION['loggedIn']=true;
$_SESSION['username'] = $uname;
$_SESSION['userid'] = $id;
$_SESSION['userlevel'] = $lvl;
$_SESSION['expires'] = $expires;
$_SESSION['formToken'] = sha1(microtime());
}
}
}
?>
Then in any page, just check:
#session_start();
if((!isset($_SESSION['loggedIn']) || $_SESSION['loggedIn']==0) && !isset($_COOKIE['cookuhash'])){
header("Location: /login.php");
exit();
}

Redirect loop issue in PHP website

I have been working on CS50's problem set 7, in which we have to make a financial website using MVC. I completed the website and it is working absolutely fine on my local machine.
But when I upload the files to hosting (free) service's server and try to access it I get a Redirect Loop error. Here is the link to it: http://ghazilajpal.byethost6.com/finance/public/
Here is code of login.php:
<?php
// configuration
require("../includes/config.php");
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET")
{
// render form
render("login_form.php", ["title" => "Log In"]);
}
// else if user reached page via POST (as by submitting a form via POST)
else if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// validate submission
if (empty($_POST["username"]))
{
apologize("You must provide your username.");
}
else if (empty($_POST["password"]))
{
apologize("You must provide your password.");
}
// query database for user
$rows = query("SELECT * FROM users WHERE username = ?", $_POST["username"]);
// if we found user, check password
if (count($rows) == 1)
{
// first (and only) row
$row = $rows[0];
// compare hash of user's input against hash that's in database
if (crypt($_POST["password"], $row["hash"]) == $row["hash"])
{
// remember that user's now logged in by storing user's ID in session
$_SESSION["id"] = $row["id"];
$_SESSION["cash"] = $row["cash"];
// redirect to index.php (portfolio)
redirect("/");
}
}
// else apologize
apologize("Invalid username and/or password.");
}
?>
Update
Here is login_form.php:
<form action="login.php" method="post">
<fieldset>
<div class="form-group">
<input autofocus class="form-control" name="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Log In</button>
</div>
</fieldset>
</form>
<div>
or register for an account
</div>
And this is config.php. This also has a redirect:
<?php
/**
* config.php
*
* Computer Science 50
* Problem Set 7
*
* Configures pages.
*/
// display errors, warnings, and notices
ini_set("display_errors", true);
error_reporting(E_ALL);
// requirements
require("constants.php");
require("functions.php");
// enable sessions
session_start();
// require authentication for all pages except /login.php, /logout.php, and /register.php
if (!in_array($_SERVER["PHP_SELF"], ["/login.php", "/logout.php", "/register.php"]))
{
if (empty($_SESSION["id"]))
{
redirect("login.php");
}
}
?>
I hope its easy to understand. I don't know where the problem lies and how to fix it.
I could have asked it on cs50.stackexchange.com but a similar question is already there with no answer.
Is it coming in this code block always?
if (crypt($_POST["password"], $row["hash"]) == $row["hash"])
{
// remember that user's now logged in by storing user's ID in session
$_SESSION["id"] = $row["id"];
$_SESSION["cash"] = $row["cash"];
// redirect to index.php (portfolio)
redirect("/");
}
if yes then here have a probelm.
change redirect with die(); to verify.
And Please provide some more inputs from you to clarify more.
I did some debugging using bhushanRJ's advice of using die (). And found out that the issue is with URLs. So using /finance/public/login.php instead of just login.php (same for other array items) solved the issue.
However CSS and JS files weren't loading. Similarly, fixing their URLs in templates fixed the issue.
When I got a loop it was because I hadn't started the session by putting "session_start()"

AngularJS ngRoute and PHP $_SESSION variables

I have 3 pages:
index.php
login.php
display.php
index.php
Sets up AngularJS using the ngRoute module to navigate my pages.
login.php
Loaded by default and sets PHP $_SESSION variables.
display.php
Echos the contents of $_SESSION.
I navigate to display.php from login.php using a link setup with ngRoute.
Problem
display.php does not show $_SESSION variables no matter how many times I navigate to and from it. It will only display them if I manually navigate to the page such as refreshing the page or entering the address in the browser.
I know the php code is executed because I can echo other things to the screen it just doesn't access the $_SESSION variables.
Why is this?
I think i might see where your problem is. You try to access php session in your single page angularJS HTML templates am i right? like:
<div ng-repeat="n in <?php $_SESSION['someSessionArray'] ?>">
That is not how it works. Your $_SESSION will never be available in your templates.
What you can do, is use an ajax request for your login authentication and have that request give you a session id.
Then use that session id when starting your session in further ajax requests (as already mentioned).
Then, when you want to store something to the php session, access the data via ajax request and php service.
a VERY, VERY, VERY, simple Example:
inside getFromSession.php
session_start($_GET['session_id']);
$key = $_GET['key']
echo json_encode($_SESSION[$key]);
inside storeToSession.php
session_start($_GET['session_id']);
$key = $_GET['key'];
$value = $_GET['value'];
$_SESSION[$key] = $value;
inside your login.php
$user = yourAuthMechanism($_GET['username'],$_GET['password']);
if($user) {
session_start();
echo json_decode(array('status' => 'success','sid' => session_id()));
}
else { ... error handling
inside anywhere in your angular where you need to access session data:
$promise = $http.get('pathtoyourphp/getFromSession.php?key=foo');
$http.set('pathtoyourphp/getFromSession.php?key=bar&value=4');
// now use promise to acces the data you got from your service
In general, no reason exists, why AngularJS apps, which request
PHP-based server-side stuff, won't be able to read $_SESSION.
That said, please provide at least the core concepts of of your AngularJS code, so we can provide further details.
Additionally, put just this in display.php:
<?
echo __FILE__
. '<br />' . date( DATE_RFC822 )
. '<br />' . var_dump( $_SESSION )
;
// intentionally skipped dangerous closing PHP-tag
Now run your AngularJS app and tell what comes out.
Make sure you start the session before reading the SESSION variables.
<?php
session_start();
echo $_SESSION["user9"];
?>
I don't think you're looking for angularJS.
I think you're looking for something more like this.
index.php:
<html>
<header>
<title>Login</title>
</header>
<body>
<form method="POST" action="login.php">
<input type="username" name="username" placeholder="username" />
<input type="password" name="password" placeholder="password" />
<input type="submit" value="Login" />
</form>
</body>
</html>
login.php
<?php
session_start();
if(empty($_POST)) {
die("You don't have permission to be here.");
} elseif(empty($_POST['username']) or empty($_POST['password'])) {
die("All fields are required.");
}
$username = "admin";
$password = "password";
if($_POST['password'] == $password && $_POST['username'] == $username) {
$_SESSION['loggedIn'] == "true";
header("Location: show.php");
} else {
die("Invalid login");
}
?>
show.php
<?php
if($_SESSION['loggedIn'] == "true") {
echo "You are logged in";
} else {
die("You don't have permission to be here.");
}
?>

php: setting cookies and retrieving them?

I'm making a login system with php, and when I submit the correct information, it set's a cookie. the form action sends to the same page, wich has an isset cookie verification on top, but since cookies need a refresh after they're set, you need to refresh page another time so it can notice that cookies are there.
what's a workaround for it? here's my code (where username and password are "admin" just as a placeholder. when I get the system working, I'll pull values from database.)
<?php
if(isset($_COOKIE['user']))
{
echo "Hello, administrator.<br />";
echo "<a href=?logout=yes>logout</a>";
if(isset($_GET['logout']))
{
setcookie("user", $_POST['username'], time() - 3600);
}
}
else
{
if (isset($_POST['submit']))
{
if (($_POST['username']=="admin")&&($_POST['password']=="admin"))
{
setcookie("user", $_POST['username'], time() + 3600);
}
else
{
echo "empty field or wrong user/pass.";
}
}
else
{
echo "nothing submitted. show form.";
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Login</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="40">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" maxlength="50">
</td></tr>
<tr><td colspan="2" align="right">
<input type="submit" name="submit" value="Login">
</td></tr>
</table>
</form>
Unless you absolutely need to use a custom cookie, I would suggest to use the $_SESSION global instead. $_SESSION data is available as soon as you set it. But its more important feature is that the data is not stored on the client. What that mean in plain is that the user can never access its data. So it is harder to hack your login system. With a cookie, as other have pointed out, anybody can read and edit the data!
session_start();
if (isset($_GET['logout']))
{
unset($_SESSION['username']);
}
if ($_SESSION['username'] == 'admin')
{
echo "hello admin!";
}
else if (($_POST['username']=="admin")&&($_POST['password']=="admin"))
{
$_SESSION['username'] = $_POST['username'];
}
To use the $_SESSION globals, you need to put session_start() at the beginning of your script (before sending any data). It should solve your problem of redirection at the same time. Note that behind the scene, $_SESSION use a small cookie, but you don't really have to think about it. It only contain a small id.
more information on session
http://www.php.net/manual/en/book.session.php
PS : to be honest, I would still use a redirect here. When you POST a form and press the back button, the browser ask you to send the data again and its annoying. Using a redirect with header("Location: " . $newUrl); remove that annoyance. But just my 2 cents.
$loggedin = false;
if(isset($_POST['submit'])) {
// Do login checking and set cookies
$loggedin = true; // if the case
}else if(isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
// Check if valid login
$loggedin = true; // if the case
}else{
// They are not logged in.
}
Then use the veriable $loggedin to see if they are logged in. I suggest making a user class though to handle this, so do you keep using the same code over and over again in your files.
You can make your own function to set cookies, ie:
function my_setcookie($name,$value,$expire){
$_COOKIE[$name] = $value;
return setcookie($name,$value,$expire);
}
But better idea is to redirect user after successful 'POST' request, so if the page is refreshed, browser won't complain about resending POST data.

Simple PHP login with cookie

I have begun developing this very simple PHP login that asks for a password to allow access to a website. It also creates a cookie to allow continued access until the user closes their browser window.
At the top of each page I check for the cookie:
<?php
if(!isset($_COOKIE['authorised']) || ($_COOKIE['authorised'] != 'true'))
{
include('login.php'); exit;
}
?>
If they don't then I exit and show a login form:
<?php
function pageURL()
{
$pageURL = 'http';
if ($_SERVER["HTTPS"] == "on")
{
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80")
{
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else
{
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
$pageRedirect = pageURL();
if(isset($_POST['password']) && ($_POST['password'] == 'qwe123'))
{
setcookie('authorised', 'true'); header("Location:$pageRedirect",303);
}
else
{
include('noaccess.php'); exit;
}
?>
<form action="<?php echo pageURL(); ?>" method="post">
<input type="password" name="password" />
<input type="submit" title="I agree" value="I agree" name="submit" />
</form>
The current PHP is from an old Warning page when you had to agree to access the site, I want to modify it to work with a simple form so that if the user types a password say for example 'qwe123' then they create the cookie and then are redirected back to the page but now have access because of the cookie. If they get it wrong then another page is included and exited.
Can someone help me with this? Thanks
Please don't try to store things like "authenticated" in a client side cookie; that's incredibly insecure. A user can modify anything in a cookie - so in this case, I could look up the cookie in my browser settings and then edit it to set "authenticated" to true. I would then be logged in, without a username or password.
Have a look at PHP's session management functions. You should create a session and store any secure information server side, not client side.
An example using sessions would be the following;
<?php
session_start();
$secretpassword = 'qwert1234';
$secretusername = 'foobar';
if ($_SESSION['authenticated'] == true) {
// Go somewhere secure
header('Location: secure.php');
} else {
$error = null;
if (!empty($_POST)) {
$username = empty($_POST['username']) ? null : $_POST['username'];
$password = empty($_POST['password']) ? null : $_POST['password'];
if ($username == $secretusername && $password == $secretpassword) {
$_SESSION['authenticated'] = true;
// Redirect to your secure location
header('Location: secure.php');
return;
} else {
$error = 'Incorrect username or password';
}
}
// Create a login form or something
echo $error;
?>
<form action="login.php"><input type="text" name="username" /><input type="text" name="password" /><input type="submit" value="login" /></form>
<?php
}
It's a pretty ugly example, but this covers the meat of it
if the user is logged in already, do the secure stuff (of course, the secure.php script should also verify that the user is logged in)
if the user is not logged in, but they have submitted a form, check their details
if username/password incorrect, set an error messagee
if username/password correct, send them to secure place
display the error message, if set
display a login form
You run session_start() before sending any other output; this stores a session cookie on the client side, which only stores an identification number on the client side. All other data is stored on the server side, so it cannot be modified by the user.
There are several parameters that you can set on this to improve security, including httponly (prevents the cookie from being accessed via javascript, helps against XSS attacks) and secure (only transfer the cookie over SSL). These should be enabled if possible.
Just have the form submit to the page where you check the password, and it should work just fine.
However, you might have to change the $_SERVER["REQUEST_URI"]; to a more specific page, as this will simply be the page you are currently at (the page the form submitted to).

Categories