Just how safe is protecting a page with session_start()? - php

After my login page all my other pages are inaccessible unless you are logged in. And basically to check if you are logged in I have a simple if else statement:
session_start();
if (isset($_SESSION['id'])) {
// Show the page
} else {
// Ask the user to log in
}
And for the admin pages I have an extra check:
session_start();
if (isset($_SESSION['id']) && $_SESSION['isAdmin'] == TRUE){
// Show the page
} else {
// Unauthorised access
}
Is this a safe way of protecting PHP pages?

Yes it is the safe way. and try to add <?php if(!session_id()) session_start(); ?> at the top of the page because if you have included this page in another page and session is already started in that page, the session will be canceled and this page will be prone to unauthorized users.

It depends.
All PHP session variables are stored on the server side. The moment a session is started by session_start();. PHP sets a temporary cookie on your computer named PHPSESSID set to expire at the end of the browsing session. Using this cookie PHP server assigns values to the session variables. Whenever you log out (i.e, session_destroy();), this PHPSESSID cookie value is made useless
The insecure bit about this is if someone actually stole your PHPSESSID cookie value, the person can simply set this PHPSESSID cookie on their computer and have access to your session without even entering any username or password. However this can be mitigated if you use SSL/HTTPS on your web server. It must be enforced wherever session_start(); is used. You must force SSL/HTTPS where sessions are used. If you just use SSL/HTTPS for login, and HTTP for the rest of the session, this doesn't make you safe as the PHPSESSID cookie is sent in plaintext via HTTP.
As far as I know the only way to compromise PHP's Session mechanism is to steal the PHPSESSID cookie using man-in-the-middle attacks, which can be totally made useless if you have a valid SSL certificate and use of strong cipher suite for your webserver. This cookie can also be retrieved using properly crafted XSS attacks, which can be mitigated if you filter javascript or equivalent from the PHP input to your PHP code using preg_replace with the proper regex.

create one function then call this function when you load your page.. this function return true and false if you login or not and then you can manage your URL redirection..
oR
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
this lucks good..

Related

Is php session unchangeable from user end? [duplicate]

This question already has answers here:
Can a user modify a PHP session?
(3 answers)
Closed 7 years ago.
I am developing my own application which requires user login. All users and passwords (encrypted) are stored in a database. When a user tries to login, then it search in the database the username and password. If all is ok, then I store username in $_SESSION["username"], user role (admin, author etc) in $_SESSION["role"] and user website in $_SESSION["website"] (I need website to be stored because the application is like "multisite" - my applicaton is hosted on client hosting but the administration is on my server).
I read this Can a user alter the value of $_SESSION in PHP? and I don't understand. Is this method secure (of storing data and if user is logged in) in a $_SESSION?
Can the user change the session content? (for example, if user is logged in and $_SESSION["website"] is "example.com", can the user change the session $_SESSION["website"] to "example.org" to ruin another website? If yes, how to avoid or what's the secure alternative of session?).
And please tell me what is session hijacking and how can this affect my site and also, how to make session_id dinamically to change?
Thank you so much!
$_SESSION is saved in the server, so the user cannot modify it ( Except the case of session hijacking)
Session() is server side as #kd0807 noted. For more info on Session Hijacking && Fixation:
http://phpsec.org/projects/guide/4.html
http://php.net/manual/en/session.security.php
Side note...
With the amount of variables I recommend an array for session['user'].
example....
$_SESSION['user'] => Array(
'userid'=> '123',
'username'=> 'some_joe',
'role' => 'customer', // user, customer, admin, moderator etc.
'website' => 'http://www.example.com'
);
// reading variables from array
$userid = $_SESSION['user']['userid'];
$username = $_SESSION['user']['username'];
// etc. etc.
Here are 3 very simplified functions I use.
// determine if session has started
Function HasSessionStarted() {
$result = false; // default to false
// Check if session has started
IF ((session_status() == PHP_SESSION_NONE) || (session_id() == '')) {
$result = true;
}
return $result;
}
// Set a session value
Function Set_Session($name, $value) {
/* #params value: can be a string or an array */
$new_session = HasSessionStarted(); // Check Session Status
IF ((isset($name)) && (isset($value))) {
IF ($new_session) { session_start(); }
$_SESSION[$name] = $value;
IF ($new_session) { session_write_close(); }
}
}
Function Unset_Session($name) {
$new_session = HasSessionStarted(); // Check Session Status
IF (isset($_SESSION[$name])) {
IF ($new_session) { session_start(); }
unset($_SESSION[$name]);
IF ($new_session) { session_write_close(); }
}
}
There is a cookie stored in the browser usually PHPSESSID which identifies which server session the user is using. If a user were able to steal it (this usually happens through XSS vulnerabilities) the user could potentially take control of another users session.
The session data itself is stored on the server and could only be modified if a user were somehow able to upload and execute a malicious script in the server
No, Until and unless the php code itself reveals the PHP session, which can be used to session stealing, and the session could not be changed from the user end until and unless the there is some functionality given by you yourself to change the session from the front end.
`$_SESSION` variables are stored in the server and hence cannot be modified by the user.
One of the best practices is that we must keep changing the session id from our end.
Thats why we use a function called session_regenerate_id().
This function that will replace the current session ID with a new one, and keep the current session information, so the use will not be logged out.
To answer your question in comment:
Whenever you start a session, server will send back a cookie which will contain the session id, the cookie name will be PHPSESSID which is the default name. You can also choose to change it. So this id is what that keeps changing when you use the session_regenerate_id function.
REASON WHY TO USE IT:
This mainly helps in preventing session fixation attacks.In this attack a malicious user will try to fix the session ID (SID) of another user. If he gets successful,the user will get all the access of the original user and will be able to do anything that the legitimate user can do.
So if you regenerate the session id the previous old session id will be no longer valid
You can get more info about session fixation IN OWASP WEBSITE
Can the user change the session content? (for example, if user is logged in and $_SESSION["username"] is "example.com", can the user change the session $_SESSION["username"] to "example.org" to ruin another website?
No. Sessions are stored on your server thus it would be impossible to directly change the session. On the other side, it all depends on the developer and how the interprets the client requests. For example, making
$_SESSION['last_website'] = isset($_SERVER['HTTP_REFERER'])
? $_SERVER['HTTP_REFERER']
: $_SERVER['REQUEST_URI'];
would eventually override the $_SESSION['last_website'].
Yes user cannot change session Variables...
if it hacked it can changed...
you need to get user id to change the $_SESSION["website"] in your current domain and use strict validation...
Otherwise they can hack it....

PHP detect if session cookies are disabled

I know that with sessions in php, a cookie that stores the session ID is set on the client's side. The client can turn off these cookies, which I presumes makes sessions not work. How can I detect if the client has disabled the session cookies?
You can use javascript navigator.cookieEnabled. This returns true or false.
So
if(navigator.cookieEnabled)
//do something
else
//do something else
assuming you started a session on a previous page...
<?php
if(session_status() == PHP_SESSION_ACTIVE)
{
echo 'cookies & sessions enabled';
}
else
{
echo 'no cookies or sessions';
}
?>
or you're looking for a non-session cookies as well.
<?php
if(!empty($_COOKIE))
{
echo 'cookies are tasty';
}
else
{
echo 'no cookies to eat';
}
?>
with a pure php solution you can't check if sessions/cookies are enabled without setting a cookie on a previous page
If you know you MUST use a session, the usual approach is to redirect the user instantly at the start while trying to set a cookie, and then complain about the cookie not being set on the second page.
User goes to http://www.example.com
System sets a cookie (maybe only starts the session, maybe a dedicated test cookie).
System redirects to http://www.example.com/?cookietest=true
On that page, if the cookie is not sent back, complain to the user.
On the other hand, most of the time a session really is not needed if you do not have to log someone in. And IF you do, most users will understand they need to allow cookies, because otherwise the login will fail.

PHP session managment, is this ok to do?

I have the following structure:
Index.php
Account.php
Login.php
CheckLogin.php
When someone logs in via login.php it checks the username and password and sets the following session variables
$_SESSION['username'] = $username;
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
When they access Account.php
that includes the file CheckLogin.php which checks the HTTP_USER_AGENT and also if the username variable is set.
Now here's where I have the problem. If a user went back to index.php (home page) and is logged in I would like to display the account link.
However if the user is not logged in i.e. just visited the site I would like to show the sign up link.
I was thinking I could do the following:
<?php session_start()
if (!isset($_SESSION['username'])) {
// If username is not set destroy the session
session_destroy();
echo ("Sign up");
}
else {
// If username is set
echo ("Sign up");
}
?>
I know this is not fully secure however if someone managed to hijack the session and went to account.php it would do the check which should destroy the session and log them out if they are not legit.
Is this best practice or is there a better way to achieve this desired result. I can't help thinking everyone just visiting the site and creating and destroying sessions is a bad idea. Is it the right thing to do or is there anything else I need to take into consideration?
This is enough for checking. No need to destroy the session on every attempt.
<?php session_start()
if (isset($_SESSION['username'])) {
echo ("Sign up");
}
else {
// If username is not set
echo ("Sign up");
}
?>
If someone is able to hijack the session, he will also be able to access your account.php. As stated above, read a good tutorial on auth systems or use a plugin. Building an authentication without proper knowledge is a bit dangerous.
if your checking is only based on session sure your website will not be secured. and I have a couple of suggestions:
1- use CSRF for more security on every post you have.
2- session should be always encrypted and you should use a salt key with them.
this way you can secure more. and just for information sessions is not always the best way to secure your website.

The correct procedure for preventing access to web pages if login details haven't been entered PHP

I am in the process of making a secure Web application on a remote server. Is there a industry standard of preventing users from accessing web pages that are only available to users who have posted their login details.
So far authenticated user pages are protected using simple header redirects if the user do sent hold a session variable.
Is this industry standard? Are there better ways to implement such a method.
pysedo code
Session code dosent equal value or session is null {
header redirect to index
}
Like I said in my comment, redirect headers are not a security feature in their own. After you have sent a redirect header, you should make sure that normal execution can't happen.
For example:
if($username != "foo" && $password != "bar")
{
header('Location: http://domain.org/index.php');
}
echo "Authorized page";
Even if the username and password are not correct, the contents of this page can still be accessed by just ignoring the Location header.
A simple fix would be:
if($username != "foo" && $password != "bar")
{
header('Location: http://domain.org/index.php');
die("Redirecting to home page");
}
echo "Authorized page";
Furthermore, it's important that authentication doesn't rely on manual checks on each page, because these checks can easily be forgotten by developers. Try to automate these kind of things as much as possible.
Not really sure if I understand the question correct.
However maybe this helps:
Since the web server handles authentication in a pretty good manner (provided it is configured correct) there is only hotlinking left. You can try to catch that issue by additional redirect rules in the server configuration: if the HTTP_REFERER is not a previously authenticated page, then redirect to wherever.
There is nothing more I can think of.
The important thing is to get authentication right and safe at the beginning.
Not sure if it is a good solution, but I simply keep the login status in session variables:
if ($_SESSION[loggedIn] == "yes" && $_SESSION["LevelTwoPermissions"] == "yes")
{
// Grant access to allowed content...
}
else
{
// Redirect to login page or ask for login in a pop-up
}
It could theoretically be hacked by stealing session cookie from an other user, but it's a reasonable level of security for my purposes.

Are there any session security loopholes in my PHP script?

After I authenticate user login info, i create this session for them:
$_SESSION['username']= $userName;
Then, I redirect them like this:
header('Location:www.domain.com/profile/' . $_SESSION['username'];
I want my website to have a beauty URL, something like: www.domain.com/profile/userName
Thus, in all my redirect links (HTML <a> tag or PHP header() function), I will use:
"www.domain.com/album/" . $_SESSION['username'];
Are there any security loopholes?
Edit:
Do I need to create session id first using session_id()?
So, to check:
if(!isset($_SESSION['id']){
//redirect to login page
}
Normally while using Sessions we also need to be aware of -:
Session Hijacking , Session Fixation
I suggest in your code after user logged in store the username in session variable also store one more unique value such as USER AGENT in a session variable. so that every page the user visit we can check for whether the same USER AGENT and SESSION ID exist this would make it much secure. To make it much more secure do the encryption like MD% on User AGENT so that hackers cant reproduce it.
Quoted from PHP SECURITY GUIDE
<?php
session_start();
if (isset($_SESSION['HTTP_USER_AGENT']))
{
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT']))
{
/* Prompt for password */
exit;
}
}
else
{
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}
?>
Refer :
PHP Security Guide on Session
Another Thread on Session security
What are you protecting? What are you doing to verify that they have authorization? Are you protecting their profile and verifying that they have authorization because they have the session key? You don't ever mention checking that they have a session variable.
You won't even need to know the session ID. That is immaterial to storing whether the user has gotten authentication, that's just the mechanism which indicates what session information they should be using.
When the user logs in, you want to store something like
$_SESSION['authed_user'] = true;
And then, on subsequent attempts to edit information you do:
if ($_SESSION['authed_user']) {
// do something authed users can do
}
And naturally, you'll really probably want some sort of levels of authorization. I recommend you consider using something like SimpleAuth...
You need authorization on the page that allows user to edit their profile. If they'll be editing on the http://www.domain.com/profile/[username] page then you need to check if their $_SESSION['username'] is equal to the profile page they are on.
Otherwise anyone would be able to type in the URL (basically guess a profile number or name) and edit it.
But yes, you should first check if they've logged in AT ALL:
if (IsSet($_SESSION['username'])) {
// Logged in
} else {
// Not logged in
}

Categories