How safe are PHP session variables?
I have a login script that verifies a username/password against data in a 'user' table. Furthermore, I have a 'roles' table that specifies the access level of a given user. Assuming I am using safe login scripts, are there any security holes in simply performing an additional query, upon successful login, against the 'roles' table to discover the user's authorization level and storing this into a session variable? The idea would then be that on any page with mixed authority, I could simply query the session variable to discover the logged in user's authorization level.
Verified Answer (74 Votes) ✓
Sessions are significantly safer than, say, cookies. But it is still possible to steal a session and thus the hacker will have total access to whatever is in that session. Some ways to avoid this are IP Checking (which works pretty well, but is very low fi and thus not reliable on its own), and using a nonce. Typically with a nonce, you have a per-page "token" so that each page checks that the last page's nonce matches what it has stored.
In either security check, there is a loss of usability. If you do IP checking and the user is behind a intranet firewall (or any other situation that causes this) which doesn't hold a steady IP for that user, they will have to re-authenticate every time they lose their IP. With a nonce, you get the always fun "Clicking back will cause this page to break" situation.
Answer #2 (15 Votes)
Only scripts executing on your server have access to the _SESSION array. If you define the scope of the session cookie, you can even restrict it to a specific directory. The only way someone besides you could get that session data is to inject some PHP code into one of your pages.
As for the system you're using, that is acceptable and is a good way to save database calls, but keep in mind that it will require the user to log out and log in again for any authorization changes to apply. So if you wanted to lock out an account and that user is already logged in, you can't.
Answer #3 (12 Votes)
It should be noted that in Apache the PHP $_SESSION superglobal is accessible across virtualhosts. Consider this scenario:
- Your server hosts two domains, example.com and instance.org. PHP sessions are stored in cookies that are restricted to the domain.
- A user logs in to example.com and receives a session ID. Example.com sets some session variables (which are stored on the server, not in the cookie).
- A third party intercepts the cookie during transmission and passes it to instance.org. Instance.org now has access to the example.com session variables.
This is not such a big deal when you control all the virtualhosts on your server, but if you are on a shared machine, it's problematic.