Security of $_SESSION array - php

When a low-privilege non-administrator user logs into my web app successfully, I am storing the following data in the $_SESSION array:
$_SESSION = array(
'user_id' => 2343, // whatever their user_id number is from the DB
'allow_admin' => false, // don't give them access to admin tools
'allow_edit' => false, // don't let them edit stuff
);
Is there any way that they could manipulate the $_SESSION array to give them Admin or Edit access, apart from somehow editing the session files in /tmp? (The above code is the only place where those items are added to $_SESSION)

The contents of the session are only visible and modifiable on the server side.
They could only be modified in an "unauthorized" way if your application or server contains some vulnerability.
You should also be aware of such things as session fixation attacks, where an attacker forces a particular session id onto an unsuspecting user, who when logs in and elevates that session's privileges, allowing an attacker to share that session.
One approach to mitigating these is to regenerate the session id whenever you change privilege levels of the session.
See also this question:
PHP Session Security

If you want to avoid javascript reading your cookies and man in the middle attacks, you need to use a server with https and set the session cookie to only be transported over https.
session.cookie_secure specifies whether cookies should only be sent over secure connections. Defaults to off. This setting was added in PHP 4.0.4. See also session_get_cookie_params() and session_set_cookie_params().
session.cookie_httponly Marks the cookie as accessible only through the HTTP protocol. This means that the cookie won't be accessible by scripting languages, such as JavaScript. This setting can effectively help to reduce identity theft through XSS attacks (although it is not supported by all browsers).
To secure admin privileges better for someone leaving his computer unguarded for a few mins, you should have a timer on last (admin) login. If that time is more then x timeunits away, the user has to login again to use admin rights.
Shorter sessions are also more secure then longer ones.

Server
Sessions are stored on the server. A user could change session data if they have direct access to the directory where sessions are stored. A solution to this is to secure the directory. And make sure you don't have a hole in your php code where you allow the user_id to be set by a $_POST or $_GET.
Client
But on the client side manipulating sessions is possible by hijacking someones session_id. This will let the hijacker pose as that user. And send request on their behalf.
There is also Cross-Site Request Forgery. This is when a hacker tricks a user into sending requests for him. By making him click on a link for example. You could combat this with tokens. A token is a generated string that is put in the $_SESSION array and in every HTML form as a hidden field. When the user submits a form the values are checked against each other. And every time the user requests a new page the token changes. This way an attacker must try to predict the token, which is pretty hard depending on how you make the token.
The links will also show examples on these attacks.

If you don't provide such access in your script there isn't much users can do about that. So your session data should be pretty secure. The only thing user can do is to manipulate session cookie or session id passed in the URL but it's unlikely that he will find an existing session id of another user.

Not unless you've left a security hole somewhere (such as allowing users to add/change $_SESSION data somehow).

As far as i know, no, unless user guess your session id and replaces it in his cookies. You should add additional IP-check at least server-side to prevent this.

Related

Laravel Session Hijacking issue [duplicate]

How do you prevent multiple clients from using the same session ID? I'm asking this because I want to add an extra layer of security to prevent session hijacking on my website. If a hacker somehow figures out another user's session ID and makes requests with that SID, how can I detect that there are different clients sharing a single SID on the server and then reject the hijack attempt?
EDIT
I have accepted Gumbo's answer after careful consideration because I've come to the realization that what I'm asking for is impossible due to the restrictions of a stateless HTTP protocol. I forgot about what is perhaps the most fundamental principle of HTTP, and now that I think about this question seems a bit trivial.
Let me elaborate what I mean:
After User A logs in on example.com, he is given some random session ID, for simplicity's sake, let it be 'abc123'. This session ID is stored as a cookie on the client side and is validated with a server-side session to ensure the user who logged in remains logged in as he moves from one webpage to another. This cookie of course would not need to exist if HTTP were not stateless. For that reason, if User B steals User A's SID, and creates a cookie on his computer with the value 'abc123', he would have successfully hijacked User A's session, but there is simply no way for the server to legitimately recognize that User B's request is any different from User A's requests, and therefore the server has no reason to reject any request. Even if we were to list the sessions that were already active on the server and try to see if someone is accessing a session that is already active, how can we determine that it is another user who is accessing the session illegitimately and not the same user who is already logged in with a session ID, but simply trying to make another request with it (ie navigate to a different webpage). We can't. Checking the user agent? Can be spoofed - but good as a Defense in Depth measure nevertheless. IP Address? Can change for legitimate reasons - but instead of not checking for the IP address at all, I suggest checking something like the first two octets of the IP, as even a user on a data plan network who constantly has a changing IP for perfectly legitimate reasons would only usually have the last two octets of their IP change.
In consclusion, it is the stateless HTTP that condemns us to never being able to fully protect our websites from session hijacking, but good practices (like the ones Gumbo has provided) will be good enough to prevent a good majority of session attacks. Trying to protect sessions from hijacking by denying multiple requests of the same SID is therefore simply ludicrous, and would defeat the whole purpose of sessions.
Unfortunately, there is no effective way to unmistakably identify a request that originates from an attacker in opposite to a genuine request. Because most properties that counter measures check like the IP address or user agent characteristics are either not reliable (IP address might change among multiple requests) or can be forged easily (e. g. User-Agent request header) and thus can yield unwanted false positives (i. e. genuine user switched IP address) or false negatives (i. e. attacker was able to successfully forge request with same User-Agent).
That’s why the best method to prevent session hijacking is to make sure an attacker cannot find out another user’s session ID. This means you should design your application and its session management that (1) an attacker cannot guess a valid session ID by using enough entropy, and (2) that there is no other way for an attacker to obtain a valid session ID by known attacks/vulerabilities like sniffing the network communication, Cross-Site Scripting, leakage through Referer, etc.
That said, you should:
use enough random input for generating the session ID (see session.entropy_file, session.entropy_length, and session.hash_function)
use HTTPS to protect the session ID during transmission
store the session ID in a cookie and not in the URL to avoid leakage though Referer (see session.use_only_cookies)
set the cookie with the HttpOnly and Secure attributes to forbid access via JavaScript (in case of XSS vulnerabilities) and to forbid transmission via insecure channel (see session.cookie_httponly and session.cookie_secure)
Besides that, you should also regenerate the session ID while invalidating the old one (see session_regenerate_id function) after certain session state changes (e. g. confirmation of authenticity after login or change of authorization/privileges) and you can additionally do this periodically to reduce the time span for a successful session hijacking attack.
Can we do something like this.
Store session id in database.
Also store the Ip address and the HTTP_USER_AGENT for that session id.
Now when a request comes to the server containing that matching session id, Check from which agent and ip it is coming from in your script.
Can make this funda work by make common function or class for session so that every request is verified before it is processed. It would hardly take some micro seconds. But, If many users are visiting your site and you have huge database of sessions, then this might be little performance issue. But, It would surely be very secure compared o other methods like
=> Using regenerating sessions.
In regenerating session ids, there is again little chance of session hijacking.
suppose, user's session id is copied and that user is not working or active for sometime and no request is made to server with old session id asking to regenerate new one. Then In case session id is hijacked, hacker will use that session id and make request to server with that id, then server will respond back with regenerated session id and so that hacker can go on using the services. Actual user will no longer be able to operate because he is unknown of what the regenerated id is and what request session id is to be passed in request. Completely Gone.
Please correct me if i m wrong somewhere.
There are lots of standard defenses against session hijacking. One of them is to match each session to a single IP address.
Other schemes may use an HMAC generated from:
the network address of the client's IP
the user-agent header sent by the client
the SID
a secret key stored on the server
The reason only the network address of the IP is used is in case the user is behind a public proxy, in which case their IP address can change with each request, but the network address remains the same.
Of course, to truly be secure, you really ought to force SSL for all requests so that the SID can't be intercepted by would-be attackers in the first place. But not all sites do this (::cough:: Stack Overflow ::cough::).
Session hijacking is a serious threat, it has to handle by using a secure socket layer for advanced application which involves transactions or by using simple techniques like using cookies, session timeouts and regenerates id etc as explained above.
When the internet was born, HTTP communications were designed to be stateless; that is, a connection between two entities exists only for the brief period of time required for a request to be sent to the server, and the resulting response passed back to the client.
Here are a few methods which hackers follow to hijack the session
Network Eavesdropping
Unwitting Exposure
Forwarding, Proxies, and Phishing
Reverse Proxies
Always recommend SSL Secure Sockets Layer
Use cookies also to following ini_set() directives at the start of your scripts, in order to override any global settings in php.ini:
ini_set( 'session.use_only_cookies', TRUE );
ini_set( 'session.use_trans_sid', FALSE );
Use Session Timeouts and Session Regenerate ID
<?php
// regenerate session on successful login
if ( !empty( $_POST['password'] ) && $_POST['password'] === $password )
{
// if authenticated, generate a new random session ID
session_regenerate_id();
// set session to authenticated
$_SESSION['auth'] = TRUE;
// redirect to make the new session ID live
header( 'Location: ' . $_SERVER['SCRIPT_NAME'] );
}
// take some action
?>
In my view you can store session id in database when users login and check everyone for the same before loggin in. delete the same session id which you have stored in database when users logout. You can easily findout session id of each and every user or else I can help you.
One of the easy implementations can be done by making a table in database , as logged users , then at login, update that table with user name and his SID , this will prevent other logins as same user , now at the time of log out , just run a simple query , which deletes the logged in data in database , this can also be used to trace logged in user on ur website at a time .
Obviously when you'll set session cookie in the browser, that cookie is sent in the request. Now when request comes, Server will check the session id in database and grant access. To prevent that only its important to store agent and ip so that before checking server makes sure that sessions access is granted to the unique client and not the unique session id which can be hijacked.
I don't know about the coding part well. So I can tell u an algorithm to do this. Setting stuffs like SSL, or setting the session cookie to secure and httpOnly wont work if a user sniffs the session id from a LAN network(Provided user and attacker are in the same LAN).
So what you can do is, once the user successfully logs into the application, set unique token to each and every pages of the web application and keep a track of this at the server side. So that if the valid user sends the request to access a particular page, the token of that page will also be sent to the server side. Since the tokens are unique for a user for a particular session, even if the attacker can get the session id, he cannot hijack the users session as he cannot provide the valid token to the server.
#Anandu M Das:
I believe what you may be referring to is the use of session tokens with each session ID. This site can explain the use of tokens with sessions:
https://blog.whitehatsec.com/tag/session-token/
Although session tokens are easily compromised by an XSS attack, this doesn't mean that they should never be used. I mean let's face it, if something was compromisable by a security vulnerability on the server, its not the fault of the method, its the fault of the programmer who introduced that vulnerability (to highlight points made by Hesson and Rook).
If you follow proper security conventions and practicies and secure your site from SQL injection, XSS, and require all sessions be managed over HTTPS, then you can easily manage the potential attack from CSRF by use of server-side tokens, stored within the session, and updated everytime the user would cause a manipulation to their session (like a $_POST being submitted). Also, NEVER store sessions or their contents in a url, no matter how well you think they are encoded.
When the security of your users is paramount (which it should be), the use of session tokens will allow better or more advanced functionality to be provided without compromising their session security.

Security for login by session in php

I'm using session variable for login purpose. If login is successful $_SESSION['userName'] is set. In some pages there are codes like if(isset($_SESSION['userName'])) echo $_SESSION['userName];
I wonder if $_SESSION['userName'] is already set by other website in someone's browser it will lead to a huge problem. How may I overcome this problem, please suggest.
The session value is communicated between a browser and a server by HTTP cookie.
The HTTP cookie is only shared on the same host name like (*.stackoverflow.com)
So, I think another website cannot be get a session value of others.
So this is how a PHP session works.
PHP generates a session id for a specific user. It then hashes that ID and passes the hash to the user as a cookie.
On each subsequent request the user send that cookie back, PHP and looks up the session data for that session hash. It is then able to start the session associated with that user. In that sense no other user is able to access the first user's session without knowing the session hash.
However the end user is vulnerable to session hijacking in case someone else steals their cookies and there's a number of ways this can happen.
Session fixation which someone tricks a user of your site to use a session ID that someone has provided them (there's not much you can do about this).
Man in the middle attacks where someone is between the user and your website and intercepts all data that get passed along. This usually can be protected against by serving the page under HTTPS (not always but it's a lot harder for someone to steal data that comes over HTTPS).
Cross-site scripting (XSS), when someone uses client-side code (which can access cookies) to impersonate that user. You can protect against this by implementing CORS restrictions and sending a "nonce" with each response which you expect the user to return when they send the next request.
Taking advantage of browser exploits that expose the user's cookies to another website. It's normally a requirement to browser manufacturers to prevent websites from accessing cookies they did not set, but sometimes bugs can be present that prevent this. This is usually taken care of if the user keeps their browser up to date (not because exploits are not there but because most people haven't found them yet).
Someone breaks into a user's house and uses the user's browser (can't do anything about this one either).
There's probably more ways

Preventing session hijacking

How do you prevent multiple clients from using the same session ID? I'm asking this because I want to add an extra layer of security to prevent session hijacking on my website. If a hacker somehow figures out another user's session ID and makes requests with that SID, how can I detect that there are different clients sharing a single SID on the server and then reject the hijack attempt?
EDIT
I have accepted Gumbo's answer after careful consideration because I've come to the realization that what I'm asking for is impossible due to the restrictions of a stateless HTTP protocol. I forgot about what is perhaps the most fundamental principle of HTTP, and now that I think about this question seems a bit trivial.
Let me elaborate what I mean:
After User A logs in on example.com, he is given some random session ID, for simplicity's sake, let it be 'abc123'. This session ID is stored as a cookie on the client side and is validated with a server-side session to ensure the user who logged in remains logged in as he moves from one webpage to another. This cookie of course would not need to exist if HTTP were not stateless. For that reason, if User B steals User A's SID, and creates a cookie on his computer with the value 'abc123', he would have successfully hijacked User A's session, but there is simply no way for the server to legitimately recognize that User B's request is any different from User A's requests, and therefore the server has no reason to reject any request. Even if we were to list the sessions that were already active on the server and try to see if someone is accessing a session that is already active, how can we determine that it is another user who is accessing the session illegitimately and not the same user who is already logged in with a session ID, but simply trying to make another request with it (ie navigate to a different webpage). We can't. Checking the user agent? Can be spoofed - but good as a Defense in Depth measure nevertheless. IP Address? Can change for legitimate reasons - but instead of not checking for the IP address at all, I suggest checking something like the first two octets of the IP, as even a user on a data plan network who constantly has a changing IP for perfectly legitimate reasons would only usually have the last two octets of their IP change.
In consclusion, it is the stateless HTTP that condemns us to never being able to fully protect our websites from session hijacking, but good practices (like the ones Gumbo has provided) will be good enough to prevent a good majority of session attacks. Trying to protect sessions from hijacking by denying multiple requests of the same SID is therefore simply ludicrous, and would defeat the whole purpose of sessions.
Unfortunately, there is no effective way to unmistakably identify a request that originates from an attacker in opposite to a genuine request. Because most properties that counter measures check like the IP address or user agent characteristics are either not reliable (IP address might change among multiple requests) or can be forged easily (e. g. User-Agent request header) and thus can yield unwanted false positives (i. e. genuine user switched IP address) or false negatives (i. e. attacker was able to successfully forge request with same User-Agent).
That’s why the best method to prevent session hijacking is to make sure an attacker cannot find out another user’s session ID. This means you should design your application and its session management that (1) an attacker cannot guess a valid session ID by using enough entropy, and (2) that there is no other way for an attacker to obtain a valid session ID by known attacks/vulerabilities like sniffing the network communication, Cross-Site Scripting, leakage through Referer, etc.
That said, you should:
use enough random input for generating the session ID (see session.entropy_file, session.entropy_length, and session.hash_function)
use HTTPS to protect the session ID during transmission
store the session ID in a cookie and not in the URL to avoid leakage though Referer (see session.use_only_cookies)
set the cookie with the HttpOnly and Secure attributes to forbid access via JavaScript (in case of XSS vulnerabilities) and to forbid transmission via insecure channel (see session.cookie_httponly and session.cookie_secure)
Besides that, you should also regenerate the session ID while invalidating the old one (see session_regenerate_id function) after certain session state changes (e. g. confirmation of authenticity after login or change of authorization/privileges) and you can additionally do this periodically to reduce the time span for a successful session hijacking attack.
Can we do something like this.
Store session id in database.
Also store the Ip address and the HTTP_USER_AGENT for that session id.
Now when a request comes to the server containing that matching session id, Check from which agent and ip it is coming from in your script.
Can make this funda work by make common function or class for session so that every request is verified before it is processed. It would hardly take some micro seconds. But, If many users are visiting your site and you have huge database of sessions, then this might be little performance issue. But, It would surely be very secure compared o other methods like
=> Using regenerating sessions.
In regenerating session ids, there is again little chance of session hijacking.
suppose, user's session id is copied and that user is not working or active for sometime and no request is made to server with old session id asking to regenerate new one. Then In case session id is hijacked, hacker will use that session id and make request to server with that id, then server will respond back with regenerated session id and so that hacker can go on using the services. Actual user will no longer be able to operate because he is unknown of what the regenerated id is and what request session id is to be passed in request. Completely Gone.
Please correct me if i m wrong somewhere.
There are lots of standard defenses against session hijacking. One of them is to match each session to a single IP address.
Other schemes may use an HMAC generated from:
the network address of the client's IP
the user-agent header sent by the client
the SID
a secret key stored on the server
The reason only the network address of the IP is used is in case the user is behind a public proxy, in which case their IP address can change with each request, but the network address remains the same.
Of course, to truly be secure, you really ought to force SSL for all requests so that the SID can't be intercepted by would-be attackers in the first place. But not all sites do this (::cough:: Stack Overflow ::cough::).
Session hijacking is a serious threat, it has to handle by using a secure socket layer for advanced application which involves transactions or by using simple techniques like using cookies, session timeouts and regenerates id etc as explained above.
When the internet was born, HTTP communications were designed to be stateless; that is, a connection between two entities exists only for the brief period of time required for a request to be sent to the server, and the resulting response passed back to the client.
Here are a few methods which hackers follow to hijack the session
Network Eavesdropping
Unwitting Exposure
Forwarding, Proxies, and Phishing
Reverse Proxies
Always recommend SSL Secure Sockets Layer
Use cookies also to following ini_set() directives at the start of your scripts, in order to override any global settings in php.ini:
ini_set( 'session.use_only_cookies', TRUE );
ini_set( 'session.use_trans_sid', FALSE );
Use Session Timeouts and Session Regenerate ID
<?php
// regenerate session on successful login
if ( !empty( $_POST['password'] ) && $_POST['password'] === $password )
{
// if authenticated, generate a new random session ID
session_regenerate_id();
// set session to authenticated
$_SESSION['auth'] = TRUE;
// redirect to make the new session ID live
header( 'Location: ' . $_SERVER['SCRIPT_NAME'] );
}
// take some action
?>
In my view you can store session id in database when users login and check everyone for the same before loggin in. delete the same session id which you have stored in database when users logout. You can easily findout session id of each and every user or else I can help you.
One of the easy implementations can be done by making a table in database , as logged users , then at login, update that table with user name and his SID , this will prevent other logins as same user , now at the time of log out , just run a simple query , which deletes the logged in data in database , this can also be used to trace logged in user on ur website at a time .
Obviously when you'll set session cookie in the browser, that cookie is sent in the request. Now when request comes, Server will check the session id in database and grant access. To prevent that only its important to store agent and ip so that before checking server makes sure that sessions access is granted to the unique client and not the unique session id which can be hijacked.
I don't know about the coding part well. So I can tell u an algorithm to do this. Setting stuffs like SSL, or setting the session cookie to secure and httpOnly wont work if a user sniffs the session id from a LAN network(Provided user and attacker are in the same LAN).
So what you can do is, once the user successfully logs into the application, set unique token to each and every pages of the web application and keep a track of this at the server side. So that if the valid user sends the request to access a particular page, the token of that page will also be sent to the server side. Since the tokens are unique for a user for a particular session, even if the attacker can get the session id, he cannot hijack the users session as he cannot provide the valid token to the server.
#Anandu M Das:
I believe what you may be referring to is the use of session tokens with each session ID. This site can explain the use of tokens with sessions:
https://blog.whitehatsec.com/tag/session-token/
Although session tokens are easily compromised by an XSS attack, this doesn't mean that they should never be used. I mean let's face it, if something was compromisable by a security vulnerability on the server, its not the fault of the method, its the fault of the programmer who introduced that vulnerability (to highlight points made by Hesson and Rook).
If you follow proper security conventions and practicies and secure your site from SQL injection, XSS, and require all sessions be managed over HTTPS, then you can easily manage the potential attack from CSRF by use of server-side tokens, stored within the session, and updated everytime the user would cause a manipulation to their session (like a $_POST being submitted). Also, NEVER store sessions or their contents in a url, no matter how well you think they are encoded.
When the security of your users is paramount (which it should be), the use of session tokens will allow better or more advanced functionality to be provided without compromising their session security.

Session hijack resulting in token exposure

I'm trying to wrap my head around session hijacking and the use of tokens for CSRF protecting.
I use this object method in each of my scripts to check whether a session variable is set or the token matches the session token.
public function admin_index(){
session_start();
if(!isset($_SESSION["user"]) || $_GET['token']!=$_SESSION['token']) {
header("location: login/login_form.php");
session_destroy();
exit();
}
I'm new at this and my question is:
If my session id is somehow hijacked will he be able to some how also read my variable $_SESSION['token'] in the short time span after session_start and the the session data is fetched and populate in $_SESSION or is it still safe on the server?
Are session variables generally safe even though a valid session has been obtained?
Never mind the $_GET['token'] instead of POST. I'm still working on it.
Thanks
EDIT:
What I'm asking is. If a token also helps me secure my sessions the way I'm using it. If every query, link or view in my script requires a valid token and an attacker only got a hold of my session_id the tokens would be another layer of protection cause he/she would need both the id AND the token to do anything in the script, right?
And the token is secure on the server even though an attacker has acquired my session_id?
Session Hijacking and CSRF attacks are two completely different things and once someone has your access to your session they are 'you' and can access everything on your account.
A CSRF attack is an attack which forces an end user to execute
unwanted actions on a web application in which he/she is currently
authenticated
This is a social engineering and validation issue which using a token can obviously solve as it can be proved that the data was sent legitimately from your form. Using POST instead of GET will make this attack very difficult.
A Session Hijack on the other hand is where someone can use your
session, become 'you' and use your account which will allow them to do
whatever they please.
Once a malicious user has access to this session a CSRF attack is pretty much useless as it is not needed.
If you are worried about your session ids being hijacked then you can take some precautionary measures such as regenerating a users session id once they are elevated to a higher level of access. This can be done using the session_regenerate_id() PHP function. You can also check the User Agent of the browser to check if there are changes and if there are then you can simply ask the user to login and regenerate the id so it is then unknown to the attacker. Obviously there is always a chance that they will be the same user agent but it does limit the risk significantly. Encryption such as SSL/HTTPS are also an option that you may want to look at
For more information you should check out this link for some examples: http://phpsec.org/projects/guide/4.html. Hopefully this has solved your problem :)
Correct me if I'm wrong, but I'm quite sure you simply can't hijack $_SESSION values because these, unlike $_COOKIE is saved on the server and not in the webbrowser.
Therefor they can't change it either. They can close their webbrowser to remove it, but not edit it.
Session variables are stored on the server. They can not be read. However, a session can be hijacked typically by an attacker getting access to the session id of another user, and can then use that session id to impersonate them (hijack) their session.
CSRF is an entirely different concern. CSRF exploits get users to inadvertantly perform operations in a manner similar to xss exploits: I might post a bogus img link where the src is actually a url that passes parameters to a script that your browser runs on your behalf. In that case the attacker is simply getting your browser to make a request you didn't intend it to. The CSRF protection should stop this, because the user does not know what the token is, so they can't embed it into the url.

Creating a secure login using sessions and cookies in PHP

I am making a login script that I would like to be as secure as possible. Problem is, security seems to be a never ending battle. So essentially, I am looking for suggestions and improvements to my ideas.
What I have is a login based solely on sessions. Anytime the session information changes, session_regenerate_id() is called to avoid obvious hijacking attempts.
When the session is not set, I check a cookie for valid login, and on success, I update the session.
I attempt to secure the cookie by adding a hash value along with a piece of unique user information (like username or id). This hash is comprised of various information, including the username/id, undecipherable password hash, part of the IP address, etc. By extracting the username/id from the cookie, I can make a new hash from the valid user information and compare that with the hash in the cookie. My hopes here are to prevent fake cookies and cookie hijacking (unless they also spoof the IP address).
EDIT Assume that the login itself will be done via HTTPS/SSL, so the transfer is (reasonably) secure.
Am I on the right track? What else can be done to secure my login?
Thanks for the help!
Stop what you are doing. Do not check the user-agent or the ip address. The user-agent is an attacker controlled variable and checking this value does not increase the security of this system. The ip address will change for legitimate reasons, such as if a user is behind a load balancer or TOR.
A session id must always be a cryptographic nonce. In php just call session_start() and then start using the $_SESSION super global. PHP takes care of all of this for you. If you want to improve php's session handler, use the configurations. Enable use_only_cookies, cookie_httponly and cookie_secure. Also setting the entropy_file to /dev/urandom is a good idea if you are on a *nix system but if your under windows then your in trouble.
For instance to authenticate a user:
//In a header file
session_start();
...
if(check_login($_POST['user_name'],$_POST['password'])){
//Primary key of this user
$_SESSION['user_id']=get_user_id($_POST['user_name']);
$_SESSION['logged_id']=True;
}
And to verify if a user is logged in:
//in a header file
session_start()
...
if(!$_SESSION['logged_id']){
header("location: login.php");
die();//The script will keep executing unless you die()
}
To improve this system read OWASP A9 and use HTTPS for the entire life of the session. Also read OWASP A5: CSRF aka "session riding" and OWASP A2: XSS because they can both be used to compromise a session.
There is no such thing as secure cookie UNLESS it's transmitted over SSL only. It can be mitigated some when using a persistent non-session cookie (like remember me), by doing exactly what you're doing, but not in the same way you're thinking of doing it.
You can indeed store server variables such as the user-agent, the ip address and so forth (and even JavaScript variables), but they are only good for validating that the persistent cookie data matches the client's new connection. The ip address isn't a good idea except when you know that the client (like you only) isn't going to change on every page load (a la AOL).
Modern web browsers and 3rd party services like LastPass can store login credentials that only require a key press (and sometimes not even that) to send the data to the login form. Persistent cookies are only good for those people who refuse to use what's available otherwise. In the end, persistent, non-session cookies are not really required anymore.
I use a cookie based method (using setcookie function) but ....
session_start();
...
if(check_login($_POST['user_name'],$_POST['password'])){
//Primary key of this user
$_SESSION['user_id']=get_user_id($_POST['user_name']);
$_SESSION['logged_id']=True;
}
...these methods are wrooooong !!!!
I crack my website with an attack based on the cookie.
I used cookie option of the WebCruiser vulnerability scanner, so I get my cookie after login.
Then I changed a simply value on cookie
Then I clicked save cookie.
At this point I clicked on webbrowser see on the left panel then I clicked right then I clicked on refresh page, so I got my admin page without using the login page with user and password.
So if someone push you a virus to read the cookie history of IE or Firefox, you'll be happy to find out your admin user and pass can be used by others.
So how to fix the problem? Simple: combine the cookie with session server or session's cookie with sessions server, or session with file session, or cookie with file session....
will be secure but slow :((((
I keep all login data in the users session, this way its all stored server side.
The only thing i would store in a client cookie is stuff like 'auto login', 'session id'
SESSION more secure than cookie
and my advise is to create a unique id for the current login attempted
like :
$id = uniqid();
$_SESSION['username'.$id] = "something ...";

Categories