PHP Session Security - security

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place!

There are a couple of things to do in order to keep your session secure:
Use SSL when authenticating users or performing sensitive operations.
Regenerate the session id whenever the security level changes (such as logging in). You can even regenerate the session id every request if you wish.
Have sessions time out
Don't use register globals
Store authentication details on the server. That is, don't send details such as username in the cookie.
Check the $_SERVER['HTTP_USER_AGENT']. This adds a small barrier to session hijacking. You can also check the IP address. But this causes problems for users that have changing IP address due to load balancing on multiple internet connections etc (which is the case in our environment here).
Lock down access to the sessions on the file system or use custom session handling
For sensitive operations consider requiring logged in users to provide their authenication details again

One guideline is to call session_regenerate_id every time a session's security level changes. This helps prevent session hijacking.

My two (or more) cents:
Trust no one
Filter input, escape output (cookie, session data are your input too)
Avoid XSS (keep your HTML well formed, take a look at PHPTAL or HTMLPurifier)
Defense in depth
Do not expose data
There is a tiny but good book on this topic: Essential PHP Security by Chris Shiflett.
Essential PHP Security http://shiflett.org/images/essential-php-security-small.png
On the home page of the book you will find some interesting code examples and sample chapters.
You may use technique mentioned above (IP & UserAgent), described here: How to avoid identity theft

I think one of the major problems (which is being addressed in PHP 6) is register_globals. Right now one of the standard methods used to avoid register_globals is to use the $_REQUEST, $_GET or $_POST arrays.
The "correct" way to do it (as of 5.2, although it's a little buggy there, but stable as of 6, which is coming soon) is through filters.
So instead of:
$username = $_POST["username"];
you would do:
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
or even just:
$username = filter_input(INPUT_POST, 'username');

This session fixation paper has very good pointers where attack may come. See also session fixation page at Wikipedia.

Using IP address isn't really the best idea in my experience. For example; my office has two IP addresses that get used depending on load and we constantly run into issues using IP addresses.
Instead, I've opted for storing the sessions in a separate database for the domains on my servers. This way no one on the file system has access to that session info. This was really helpful with phpBB before 3.0 (they've since fixed this) but it's still a good idea I think.

This is pretty trivial and obvious, but be sure to session_destroy after every use. This can be difficult to implement if the user does not log out explicitly, so a timer can be set to do this.
Here is a good tutorial on setTimer() and clearTimer().

The main problem with PHP sessions and security (besides session hijacking) comes with what environment you are in. By default PHP stores the session data in a file in the OS's temp directory. Without any special thought or planning this is a world readable directory so all of your session information is public to anyone with access to the server.
As for maintaining sessions over multiple servers. At that point it would be better to switch PHP to user handled sessions where it calls your provided functions to CRUD (create, read, update, delete) the session data. At that point you could store the session information in a database or memcache like solution so that all application servers have access to the data.
Storing your own sessions may also be advantageous if you are on a shared server because it will let you store it in the database which you often times have more control over then the filesystem.

I set my sessions up like this-
on the log in page:
$_SESSION['fingerprint'] = md5($_SERVER['HTTP_USER_AGENT'] . PHRASE . $_SERVER['REMOTE_ADDR']);
(phrase defined on a config page)
then on the header that is throughout the rest of the site:
session_start();
if ($_SESSION['fingerprint'] != md5($_SERVER['HTTP_USER_AGENT'] . PHRASE . $_SERVER['REMOTE_ADDR'])) {
session_destroy();
header('Location: http://website login page/');
exit();
}

php.ini
session.cookie_httponly = 1
change session name from default PHPSESSID
eq Apache add header:
X-XSS-Protection 1

I would check both IP and User Agent to see if they change
if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']
|| $_SESSION['user_ip'] != $_SERVER['REMOTE_ADDR'])
{
//Something fishy is going on here?
}

If you you use session_set_save_handler() you can set your own session handler. For example you could store your sessions in the database. Refer to the php.net comments for examples of a database session handler.
DB sessions are also good if you have multiple servers otherwise if you are using file based sessions you would need to make sure that each webserver had access to the same filesystem to read/write the sessions.

You need to be sure the session data are safe. By looking at your php.ini or using phpinfo() you can find you session settings. _session.save_path_ tells you where they are saved.
Check the permission of the folder and of its parents. It shouldn't be public (/tmp) or be accessible by other websites on your shared server.
Assuming you still want to use php session, You can set php to use an other folder by changing _session.save_path_ or save the data in the database by changing _session.save_handler_ .
You might be able to set _session.save_path_ in your php.ini (some providers allow it) or for apache + mod_php, in a .htaccess file in your site root folder:
php_value session.save_path "/home/example.com/html/session". You can also set it at run time with _session_save_path()_ .
Check Chris Shiflett's tutorial or Zend_Session_SaveHandler_DbTable to set and alternative session handler.

Related

php5 $_SESSION security

I read sessions and security questions on stackoverflow, and much beyond. I think I know the answer, but I want to confirm it with one concise simple question--security is too important.
Conjecture: My black hat web visitor does not have direct access to his $_SESSION contents.
that is, after my server executes
$_SESSION['myuserprivilege']='user' ;
I can assume that even the most clever blackhat cannot somehow find out even that my code did this, interrogate to what my php program set his server $_SESSION to (both keys and contents), or (much worse) engineer $_SESSION['myuserprivilege'] = 'admin'. only my own server php code can do so.
I still have to be concerned that a blackhat can steal the cookie of a different admin user ( => https and session rotation). but that's a different issue.
correct?
The values of the session are stored in your server, not in the user machine. So, no... No one can see or set that value without access to your server or any security problem in your code. It's like money in a safe, only who have access can get it or if the safe isn't secure enough.
And about cookie stealing, this is called session hijacking. It's common tecnique used to steal a session from another user. You can get more information here.
Basically if a person get the id of the session of a logged admin and the application doesn't have any approach to avoid this kind of situation, this person can have access to that user privileges.
Anyone can set a cookie in your website, but sessions has one thing called "PHP Session ID", so to get some value from a session, this person need to know a valid session id that have privileges to some part of application.
Session routation is not a problem, the chances to get some session from anyone that have this privileges is really, really hard. You also can use more characters in your session to make it more harder, but o don't think it's necessary.
Final answer: No one cannot set a session in our website, just who has access do the code and your server can do it.

Harm of passing session id as url parameter

So I just noticed that one of the internet banks websites is passing session id as url parameter. ( See image below )
I didn't previously see anywhere that ';' in url, in this case it is after 'private;'.
1) What is the use of this ';'?
2) And why internet bank, which needs to be securest place in the internet is passing session id as url parameter?
At first, I thought they are doing it because some of the users disallow use of cookies, but then again, if they allow it, use cookies, if not - url, but I do allow use of cookies, so obviously thats not the case.
3) I guess then they should have some other security measures? What they could be?
4) And what one can possibly do if he knows others valid session id?
As I know, you can quite easily log into others peoples session if you know that id, because its not hard to edit cookies and its much easier to pass that session id as url parameter, especially if you have something like:
session_id($_GET[sessionid]);
Thanks!
1) You should ask whoever designed the application your red box is covering. URL can be anything you want; the convention of key=value&key2=value2 is just that - a convention. In this case, it's Java, and it commonly uses the convention of ;jsessionid=.... for its SID.
2) It's not that big of a deal. Normal users can't copy-paste cookies like they can copy-paste a GET parameter, but power users can do whatever they want (using Mechanize, wget, curl and other non-browser means, or even browser extensions). And if you allow it for some users and disallow for some, it's not really much of a security precaution, is it? Basically, cookie SID will make the attack a bit harder, but it's like putting your front door key under the mat - definitely doesn't keep your door secure. Additionally, cookies are shared between tabs: if a site wants you to be logged in with two accounts at once, you can't do it with cookies.
3) Serverside security, yes. One effective countermeasure is one-time SIDs (each time you visit a page, the server reads the session from the current SID, then starts a new session with a new SID for the next request). A less effective but still good method is to validate other information for consistency (e.g. - still same IP? Still same browser?)
4) Yes, if you know someone's valid SID, and the server does not adequately protect against session fixation, you can "become" that person. This might enable the attacker to, say, pay his bills with your money, for instance.
So, #Amadan correctly covered #1 and #4. But there's a bit more that needs expansion.
Using Session identifiers in a URL can be a major problem. There are a few cases where it's critically bad:
Session Hijacking:
If a user copy-pastes a URL into an email.
In this case, the attacker can simply read the email, and steal the session identifier (thereby resuming the session).
You could partially defend against this by making session lifetimes short, and validating things like IP addresses or User Agents in the session. Note that none of these are foolproof, they just make it "slightly" harder to attack.
If the connection is ever downgraded to HTTP.
If they are not using Http-Strict-Transport-Security (HSTS), then an attacker may be able to successfully downgrade the session to HTTP only (via MITM style attack). If the server isn't setup perfectly, this can cause the URL to leak to the attacker, and hence the session identifier.
Session Fixation Attacks
An attacker can craft a session identifier, and send the user a forged link with that session identifier. The user then logs in to the site, and the session is now tied to their account.
You can mitigate this by strictly rotating session identifiers every time the session changes (log in, log out, privilege upgrade or downgrade, etc). But many servers don't do this, and hence are susceptible to fixation style attacks.
The reason that cookie sessions are seen as more secure is not because they are harder to edit. It's because they are more resistant to fixation attacks (you can't create a URL or link or form or js or anything that sends a fraudulent cookie on behalf of the user).
Why the bank uses a URL parameter? I have two guesses:
Because they want to support those who don't allow cookies.
Which is sigh worthy.
They don't know any better.
Seriously. If it's not in a compliance doc or NIST recommendation, then they likely don't do it. Hell, there are implemented NIST recommendations that are known to be insecure, yet are still followed because it's in writing.
What is the use of this ;?
This is just a query string separator. & isn't the only sub-delim specified in the URL specification (RFC 3986).
And why internet bank, which needs to be securest place in the internet is passing session id as url parameter?
It could be that this session ID is never used, and the actual session identifier user is passed in cookies or in POST data between each navigated page. The only way to verify this is to try copying the URL into another browser to see if your session is resumed, however then again they may be checking things like User Agent - not real security but would dissuade casual attacks. Do not try this on a live system you do not have permission to do so on as it would be illegal. If you want to learn about security download something like Hacme Bank and try on there.
I guess then they should have some other security measures? What they could be?
No doubt they will, otherwise this would be a huge security threat. The URL could be leaked in the referer header if there are any external links on the page. The types of security a bank uses for their website is too large to list here, however they should be meeting certain industry standards such as ISO/IEC 27001 that will cover the types of threat that their site would need to be secure against.
And what one can possibly do if he knows others valid session id? As I know, you can quite easily log into others peoples session if you know that id, because its not hard to edit cookies and its much easier to pass that session id as url parameter, especially if you have something like:
As the ID is displayed on the screen it might be possible to read it (although IDs are generally long). A more realistic attack is Session Fixation. This is where an attacker can set the Session ID of their victim. For example, sending them a link that includes the attacker's Session ID. When the victim follows it and then logs in, as the attacker has the same session, they are logged in too.
Storing the Session information in a cookie or in a URL are both viable methods. A combination may used as
Security session management and (Server) Session management are separate aspects:
The fundamental difference is that cookies are shared between browser windows/tabs, the url not.
If you want your user to be logged on when navigating to the same site in different tab, sharing the security session (=without a new logon procedure) then cookies are a good way.
To differentiate "sessions" per tab and associate distinct server sessions with distinct tabs (Think of the user running two "stateful" transactions in two different tabs in parallel), managing a sessionId on the client which can be different per tab is required. Cookies won't work here.
Putting it in the URL is one way to assure this information is routinely added to requests fired from the page (referrer header). Alternative methods would require specific code to add this information explicitly to each request which is more work.
See How to differ sessions in browser-tabs?

Why does Magento use 2 cookies per session?

For data security and privacy reasons I want to know why Magento uses two cookies for one frontend session.
All I know is that one of them is being set in Mage_Core_Model_Cookie::set(..) and the other one in Zend_Session::expireSessionCookie(), but still I can't seem to figure out what they are used for.
I just can't think of any reason why one would need a second cookie for the same domain.
I'm going to call this one vestigial code. Varien relies heavily on the Zend Framework as the underpinning for Magento, so many of the classes (Zend_Session for instance) are used as parent classes for Magento implementations.
The Varien-set cookie labeled "frontend" is namespaced for the section of the site you visit (e.g. you will have a separate "admin" cookie if you log in through the backend), whereas the Zend cookie appears to be global.
Also note that I was able to delete the Zend cookie without any apparent deleterious effects (my login session and cart remained accessible, and the cookie was not immediately replaced).
I was able to fix this by reversing the order of the session_start() call and the statement that sets the cookie in Mage_Core_Model_Session_Abstract_Varien::start(..). Those two lines now look like this:
$cookie->set(session_name(), $this->getSessionId());
session_start();
It now only creates one single cookie and it does not seem to have any side-effects.
BTW: The other cookie was not created in Zend_Session as I assumed, but instead both of them came from Mage_Core_Model_Session_Abstract_Varien::start(..).
That is interesting. I just checked on an install of enterprise edition and only "PHPSESSIONID" is set, "frontend" and "admin" are missing even when logged into both. Perhaps this is something still actively being developed.

How to Secure CouchDB

CouchDB access as a rest service seems insecure. Anyone can hit the database and delete/add documents once it is exposed.
What strategies are there to secure the CouchDB?
A lot has changed since 2009, so I'm going to throw an answer in here. This answer is drawn from this page on the wiki.
CouchDB has a _users database that serves the purpose of defining users. Here's the gist straight from the wiki:
An anonymous user can only create a new document.
An authenticated user can only update their own document.
A server or database admin can access and update all documents.
Only server or database admins can create design documents and access views and _all_docs and _changes.
Then, for any given database you can define permissions by name or by role. The way authentication is implemented is through a _session Database. Sending a valid username and password to the _session DB returns an authentication cookie. This is one of several option for CouchDB Authentication. There're a few more options:
This option is a little old 1.0 was a few months back, we're on 1.2 as of today. But it's still very well outlined.
And this one from "The Definitive Guide"
Also, depending on which hosting service you might be using, you'll have the option to restrict access to couch over SSL.
Between Node, Couch, and a variety of other technologies that effectively scale horizontally (adding more servers) there's an interesting kind of pressure or incentive being put on developers to make applications that scale well in that manner. But that's a separate issue all together.
The only thing which really works currently security wise is something like this in your CouchDB configuration.
[couch_httpd_auth]
require_valid_user=true
[admins]
admin = sekrit
This puts basic HTTP auth on all of CouchDB. Even this is not well supportet in client libraries. For python e.g. you need a patched library.
The second approach is to put a proxy in front of CouchDB and let the proxy do the authentication and authorization work. Due to CouchDB's RESTful design this is quite easy.
All other approaches must be considered up to now highly experimental.
This may be a little different from your original question. If your couchdb is only a back-end store for a full server app, you can make a special account for the server app to use and require those credentials for access to couchdb.
On the other hand, a pure couch app that people hit directly through a javascript client needs a lot of care to be secure.
Using rewrites is not optional. You need a vhosts config that forces requests to your domain through your rewrites.
Rewrite routes */_all_docs and /*/_design/* to a 404 page. Otherwise users can list every document or get your whole app.
Rewrite generic object access, ie /dbname/:id to a show that can deny access if the user is not allowed to see the document. Unfortunately there is no equivalent workaround for doc-based access control of attachments.
We used haproxy to filter GET requests on _users. There is no legit reason for someone from outside to get a user record or list all your users. We want users to be able to register so we need write access. Currently couch cannot block read access to a db and simultaneously allow writes. It's a bug. Filtering with something like haproxy is our best workaround for now.
Use your own database to keep contact information that is in addition to what is provided by _users. This allows more control over access.
validate_doc_update should carefully reject any writes that should not be allowed.
In every case you need to imagine what someone who understood the system could do to subvert it and lock down those avenues of attack.
CouchDB does cookies, SSL, oauth, and multi-users just fine:
Here's some actual code in python:
from couchdb import Server
s = Server("https://user:password#example.com:6984")
Request the cookie: url encoded above and below, of course
You have to put the credentials twice to get started with the first cookie
Both in the Server() constructor as well as the _session POST body
code, message, obj = s.resource.post('_session',headers={'Content-Type' : 'application/x-www-form-urlencoded'}, body="name=user&password=password")
assert(code == 200)
Now you have received a cookie, extract it
cookie = message["Set-Cookie"].split(";", 1)[0].strip()
Now, exit python and restart
Next, Request a server object, but without the username and password this time
s = Server("https://example.com:6984")
s.resource.headers["Cookie"] = cookie
Yay, no password, try to access the database:
db = s["database"]
Optionally set the "persistent" cookie option on the server side to make the cookie last longer.
Have you read CouchDB documentation http://couchdb.apache.org/docs/overview.html? It has a "Security and Validation" section that addresses some of your concerns.

Securely implementing session state and 'keep me logged in' feature

I would like to improve security on a current application regarding session management and I want the users to be logged in until they explicitly logout.
How does one implement that securely?
Keep session information in database, like sessionid, ip, useragent?
Please provide the requirements, possibly a database layout, do's and don'ts, tips and tricks.
Note:
I know frameworks like asp.NET, rails, codeigniter, etc... already take care of that, but this is not an option. Actually it for a classic asp application. But I think this question does not relate to a specific language.
Read Improved Persistent Login Cookie Best Practice (both the article and comments).
You should know that such a system cannot be secure unless you use https.
It's quite simple:
User logs in.
The server sends the user a cookie with an expire date far in the future.
If you want, you can record the IP of the user.
User requests another page.
The server checks the cookie (possibly the IP stored with the cookie), sees that the user is logged in, and servers the page.
Some security considerations:
As stated above, there is no secure way unless you use https.
If you're using shared hosting, try to find out where your cookies are stored. Often they reside in the /tmp directory, where every user as access to and through that someone could possibly steal your cookies.
Track the IP, if you know that the computer isn't ever going to change it.
Don't store any information in the cookie. Just store a random number there and store the information belonging to it on the server in a database. (Not sensitive information like preferred colour can be stored in the cookie, of course.)
Create a cookie with a ridiculous expiry like 2030 or something. If you need session state, keep a session ID in the cookie (encrypted if security is priority) and map that to a table in a database. IP/UserAgent etc. tend to be meta-data, the cookie is the key to the session.

Resources