I have a web application that I want to improve in its security flaws, I read a lot of articles about it but some questions are still unanswered. I appreciate your help.
First of all I have a login screen. After the user enters his credentials, they are checked against the database ( they are properly hashed ;)), and if it succeeds the server creates a session variable
//Jhon id = 1
$_SESSION["userID"]= '1';
At the beginning of every php file (e.g. dashboard.php) I have the following code:
session_start();
if(isset($_SESSION['userID'])) {
if($_SESSION["userID"]==""){header("location:login.php");}
}else{
header("location:login.php");
}
?>
<html ...
For improve maintenance i want to include this code in an external php file like
include('inc/restricted.php');
?>
<html ...
My two main questions are:
1) If an intruder handles to corrupt or to deny access to restricted.php, would the remain of dashboard.php show up? Is it possible to do something like that? If it is, how could I fix it the way I can include the security code as an external file?
2) As you see the value of my session variables are simple (integers numbers), should I change them to hashed values? I thought the php session was stored on server side but i read about some php session variables stored on cookies and now im worried about the chance of create a cookie with a random number and granted access.
$_SESSION
is never stored on the client, only on the server. This is controlled in php by the session.handler
interface (by default it's stored as a plain-text file on your server in session.save_path
).The things that tend to make sessions insecure are almost always the result of poorly written code or a poorly configured server.
Some things you can do to improve the security of your sessions are outlined below:
Always use session_regenerate_id(true)
when logging the user in (this prevents session fixation attacks).
Always delete the session cookie on the client when you log the user out (see the first example in http://php.net/session-destroy). This prevents session take-over attacks when the user is logged in from a public computer, for example, as the session may not always be deleted instantly on the server side and the cookie allows the client to re-trigger the session TTL on the server.
Only transmit session cookies over a secure connection (See session.cookie_secure
To prevent some XSS and CSRF vectors consider using session.cookie_httponly
and session.cookie_samesite
to prevent malicious JS from opening up these kinds of attacks.
Always use CSRF tokens along with all modifying requests to protect the user from compromising their access strictly via sessions. This is an added layer of security.
Just remember that this is not an unabridged list. Security is built in layers and requires a lot of forethought in use cases and objectives.