will this work as an alternative to http cookie? - php

I'm using php for my site and was wondeirng if it would be a good idea to use the $_SERVER
md5($_SERVER['remote_addr'] + $_SERVER['http_user_agent'])) into a cookie_auth field in the user table.
When the user logs in, php will use the above key to re-check the current user and compare it to the stored key and if matched get credintials for the user.
The problems are, the user agent can change and IP can change. I guess my main concern is the user user agent. IP addresses typically stay around for a month or two and my primary user base has static ip addresses (companies) so this shouldn't be issue.
Are there any other php $_SERVER variablies that I could concatinate that would be less volitile... but still dynamic?
I have the php manual infront of me but I don't see any usefull... Maybe I'm missing something.
Do other developers implement anything similar to this?
Thoughts?
Is there a better way to go about this?

It won't work, also because of proxies. If two people with the same user agent visit, then it's disaster.
Some projects can do "cookieless sessions" by passing the session id in a GET variable in all URLs that they use.
PHP can actually do this by itself. And you can even force PHP to not use cookies at all, just pass it in GET variables.
But there are some drawbacks. If you invoke URLs of your application in your javascript code, you have to insert the session id there. Also, if there are external links, the session id can be made available via the referer (sic) HTTP parameter to third parties, which could result in potential session stealing. You have to be extra careful with XSS holes. You probably have to be careful with session fixation happening during the login procedure of your application. And so on.

my primary user base has static ip addresses (companies)
So, if one persone in MegaCorp (with all the same browsers, and the same external IP address) logs in, everybody there is logged in? Don't do it.
And another reason: all iPhones in the same area (same proxy, same browser) are logged in. All I have to do to break in is just to be within several hundred meters (to some kilometers in some places) to someone with access, and it's automagically granted to me.
There are in general 2 ways to have a 'passwordless login' (which is where most of these questions originate):
Cookies with a sufficient 'unguessable hash' from a previous login
Convince the user to install a certificate you can validate over HTTPS.

Most of the $_SERVER variables are attacker controlled (remote_addr is pulled directly from the tcp socket and there for cannot be spoofed or otherwise tampered with). However an attacker can change the user-agent to anything.
Don't re-invent the wheal. session_start() and the $_SESSION super-global is secure, easy to implement and robust. To use this you should always call session_start() in a header file for all pages.
if(!$_SESSION[logged_in]){
header("location: login.php");
die();//Yes php keeps executing so you need this!
}
then in login.php:
if(login($_REQUEST[user],$_REQUEST[password])){
$_SESSION[logged_in]=true;
}

Related

Safe Way to "Stay Loggedin" with Sessions [Still Need Answers]

I use the $_SESSION variable to log users in. Are they safe from Injections?
If you wish to have a look at my scripts to check for vulnerability's Here you go: http://pastebin.com/raw/7iiSSjKP
So thanks to a user below they linked me to: http://resources.infosecinstitute.com/session-hijacking-cheat-sheet/
It looks like my sessions are being stored exactly the same as the InfoSec website's vulnerabilities. And yes, It is vulnerable.
I tested and the PHPSESSID cookie stored on the browser is exploitable, If I inject a different users cookie I will be logged into there account and vice-versa. If I stay on there cookie, logout and login to my own account, they will be logged into my account.
(Bottom msg and top 2 msgs are me other ones are my friend bean)
How can I fix this?
I have read around a lot and apparently a SSL certificate just solves this, I do have a SSL certificate but it doesn't seem to change anything. What do I do to solve this?!
Methods I have tried:
http://pastebin.com/raw/5skKhPSw (Seems to work at first and it would make sense to work but if you log into other accounts and vice-versa it just messes up here and there so its not a great solution.
Dont know any other way. Open to Suggestions.
$_SESSION are usually used for logins, thus they are reasonably safe by default, as a user won't be able to somehow set the $_SESSION['username'] value themselves; the value can only be set by your server.
However, there are still vulnerabilities about $_SESSION, more specifically session hijacking, this is the only real vulnerability to the whole scheme.
Also, after header("Location: http://gameshare.io");, you should use exit;.
Setting a header will not terminate the current script. Thus, if you're outputting sensitive information after this line, it will be sent to the client! You need to explicitly exit after setting the header.

Can a user manipulate cookies?

I have a question regarding usage of cookies for standard login purposes. Say my php script saves a cookie into a users computer each time he logs in. The cookie value is say "Mike" after his username at the website. Can that user somehow manipulate that cookie in his browser to change the value to say "Admin" so suddenly he has access to administration of the website?
If this could happen how to solve such security risk?
--
Additionally... What if someone was to copy cookies from my browser, either he would stare at my computer screen and copy cookies and values into his computer or such intruder could steal cookies from my browser via JavaScript.
How is that taken care of?
Yes, that is a security problem, which extends to any information provided by the client.
Cookies are stored on the user's machine. They can be modified in any way. In fact, the cookies can just be created on the fly and sent via several utilities for making HTTP requests. It isn't even a browser problem.
Never trust any data that comes from the client.
Yes, a user can manipulate cookies if they're stored on their computer.
Use a session.
A 'session' is the server-side storage of connection-relative information that is linked to the user through a variable which is passed back and forth, most often a cookie, however logically, anywhere will do if both your client and server can handle it.
This 'session' is often represented by an integer which the client and server both know.
The problem is, if another client has a session open on the server, we (as a client) could 'hi-jack' this session by replacing our given id with a random id until one is found. The server would now believe we are in fact the other use and could give us access to their private informatin.
For this reason, we have 'keys'. A key is a unique, often alphanumeric, code which is changed on each request-response pair with the server, ensuring that only those who have the latest key are able to gain access.
YES
They can manipulate, edit, modify, create and delete cookies.
You should only store a hash key that you use on the server to look up in a database anything that should be secure.
Yes, users can manipulate cookies. The best way to handle it is to not store user credentials in such a manner that they can gain admin access by changing their user name.
The specifics on how to do this are pretty deep, but a good start would be to just store the users's session identifier instead. That has its own issues, but won't let people break things quite so easily.
Cookies are clientside which means that they can be read, write and delete by the client. A cookie manager plugin makes it easier to change the cookie value.
http://www.ehow.com/how_7149468_edit-cookies-computer.html
Yes a user can easily manipulate the cookies by just going to cooking option which all popular browser provide

How exactly does session hijacking work in PHP?

I've made a website which has registration/login. I can see the PHPSESSID cookie in Chrome's Developer Tools, so I'm wondering how can I use this session id value to hijack into the account I'm logged, from let's say a different browser, for simplicity's sake?
Should a secure website be able to determine that this session is being hijacked and prevent it?
Also, how come other big sites that use PHP (e.g. Facebook) do not have PHPSESSID cookies? Do they give it a different name for obscurity, or do they just use a different mechanism altogether?
Lots of good questions, and good on you for asking them.
First.. a session is just a cookie. A 'session' is not something that's part of the HTTP stack. PHP just happens to provide some conveniences that make it easy to work with cookies, thus introducing sessions. PHP chooses PHPSESSID as a default name for the cookie, but you can choose any you want.. even in PHP you can change the session_name.
Everything an attacker has to do is grab that session cookie you're looking at, and use it in its own browser. The attacker can do this with automated scripts or for instance using firebug, you can just change the current cookie values.
So yes, if I have your id.. I can steal your session if you didn't do anything to prevent it.
However.. the hardest part for an attacker is to obtain the cookie in the first place. The attacker can't really do this, unless:
They have access to your computer
They somehow are able to snoop in on your network traffic.
The first part is hard to solve.. there are some tricks you can do to identify the computer that started the session (check if the user agent changed, check if the ip address changed), but non are waterproof or not so great solutions.
You can fix the second by ensuring that all your traffic is encrypted using HTTPS. There are very little reasons to not use HTTPS. If you have a 'logged in' area on your site, do use SSL!!
I hope this kind of answers your question.. A few other pointers I thought of right now:
Whenever a user logs in, give them a new session id
Whenever a user logs out, also give them a new session id!
Make sure that under no circumstances the browser can determine the value of the session cookie. If you don't recognize the cookie, regenerate a new one!
If you're on the same IP and using the same browser, all you have to do is duplicating the session ID (and maybe other cookie values: not really sure if browser specific things like its agent string is tracked/compared; this is implementation dependant).
In general, there are different ways to track users (in the end it's just user tracking). For example, you could use a cookie or some hidden value inside the web page. You could as well use a value in HTTP GET requests, a Flash cookie or some other method of authentication (or a combination of these).
In case of Facebook they use several cookie values, so I'd just assume they use one of these values (e.g. 'xs').
Overall, there's no real 100% secure way to do it (e.g. due to man-in-the-middle attacks), but overall, I'd do the following:
Upon logging in, store the user's IP address, his browser agent string and a unique token (edit due to comment above: you could as well skip he IP address; making the whole thing a bit less secure).
Client side store the user's unique id (e.g. user id) and that token (in a cookie or GET value).
As long as the data stored in first step matches, it's the same user. To log out, simply delete the token from the database.
Oh, and just to mention it: All these things aren't PHP specific. They can be done with any server side language (Perl, PHP, Ruby, C#, ...) or server in general.
Someone sniffs the session ID cookie and sets it for a subsequent request. If that's the only thing authenticated a user, they're logged in.
Most sites will use authentication based on cookies in some form. There are several ways to make this more secure such as storing info about the user's browser when they log in (e.g. user agent, IP address). If someone else naively tries to copy the cookie, it won't work. (Of course, there are ways around this too.) You'll also see session cookies being regenerated periodically to make sure they aren't valid for a particularly long time.
Check out Firesheep for a Firefox extension that performs session hijacking. I'm not suggesting you use it, but you may find the discussion on that page interesting.

Cookies/Sessions login system

When a user logins I get him/her's ID and save it in a session var. What I wonder is, is this the way to go? Or should I use cookies? so it automatically login and so on.
session_start();
ifcorrectlogin {
$_SESSION['id'] = mysql_result($loginQuery, 0, 'user_id');
}
how do you authenticate your users?
//Newbie
Yes, this is the way to go. The session itself is already backed by a cookie to remove you any programming efforts around that. The session (actually, the cookie) will live as long as the user has the browser instance open or until the session times out at the server side because the user didn't visit the site for a certain time (usually around 30 minutes).
On login, just put the obtained User in the $_SESSION. On every request on the restricted pages you just check if the logged-in User is available in the $_SESSION and handle the request accordingly, i.e. continue with it or redirect to a login or error page. On logout, just remove the User from the $_SESSION.
If you want to add a Remember me on this computer option, then you'll need to add another cookie yourself which lives longer than the session. You only need to ensure that you generate a long, unique and hard-to-guess value for the cookie, otherwise it's too easy to hack. Look how PHP did it by checking the cookie with the name phpsessionid in your webbrowser.
Cookies can be manipulated very easily. Manage login/logout with Sessions. If you want, you can store the users emailaddress/username in a cookie, and fill the username box for them the next time they visit after the present session has expired.
I would try to find a session engine so you don't have to deal with the misc. security issues that bite you in the ass if you do the slightest thing wrong. I use django which has a session engine built in. I'm not aware of the other offerings in the field although I would assume most frameworks would have one.
The way they did it in django was by placing a cryptographic hash in the user's cookies that gets updated every page view and saving all other session information in a database on your server to prevent user tampering and security issues.
As BalusC mentions, the session_-functions in php are the way to go, your basic idea is sound. But there are still many different realisations, some of them have their pitfalls.
For example, as Jonathan Samson explains, using cookies can result in security holes.
My PHP is a bit rusty, but I remember that the session_-functions can also use session IDs that are encoded in URLs. (There was also an option to have this automatically added to all local links (as GET) and form targets (as POST). But that was not without risks, either.) One way to prevent session hijacking by copying the SID is to remember the IP address and compare it for any request that comes with a valid session ID to to IP that sent this request.
As you can see, the underlying method is only the start, there are many more things to consider. The recommendation by SapphireSun is therefore something to be considered: By using a well tested library, you can gain a good level of security, without using valuable development time for developing your own session system. I would recommend this approach for any system that you want to deploy in the real world.
OTOH, if you want to learn about PHP sessions and security issues, you should definitely do it yourself, if only to understand how not to do it ;-)

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.
Thanks.
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.
But with a cookie, a hacker can steal the session simply by using fairly simple XSS techniques. If you store the user's session ID as a cookie, they are vulnerable to this as well. So even though the session is only penetrable to someone who can do a server-level hack (which requires much more sophisticated methods and usually some amount of privilege, if your server is secure), you are still going to need some extra level of verification upon each script request. You should not use cookies and AJAX together, as this makes it a tad easier to totally go to town if that cookie is stolen, as your ajax requests may not get the security checks on each request. For example, if the page uses a nonce, but the page is never reloaded, the script may only be checking for that match. And if the cookie is holding the authentication method, I can now go to town doing my evilness using the stolen cookie and the AJAX hole.
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.
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.
If you rely on a value stored inside of a session variable to determine roles then you lose the ability to change the value in the DB and have it reflected against the user's current session. If you look at Zend Framework, there's a clear distinction between authentication and authorization, and strongly-worded warnings in the manual to only store the minimal amount of data in the session (ie "Yup, he's user #37 & he logged in").
As far as 'safety' goes - unless you're on shared host, there's nothing to worry about. On a properly configured shared host, they should be relatively secure, too.

Categories