Authentication system - is my one secure? - security

I want to authenticate my users based entirely on cookies and sql db.
What I do is:
1. Once they login, I generate a random string, create a hash from it, save it in the database along with the user id and his IP.
2. I send the hash to the user as cookie
3. Whenever he wants to access something, I verify if his cookie hash matches the one on the server and also if his IP matches. Of yes, he is valid or else, log him out.
4. (As pointed by Akhil) If he clears his browser cookies or anything does not match the information on the database, I clear all the rows with his username and log him out.
Note: I use a session cookie for storing the random hash, which again is generated using the timestamp, and as long as time doesn't repeat itself(I believe), its random in the corect way.
Is this fine? How can I make it better?

Once they login, I generate a random string
Make sure you use a cryptographically secure method to generate the random string. Do not use mt_rand use something such as openssl_random_pseudo_bytes.
create a hash from it,
Make sure to use a secure hashing algorithm (not MD5, and at least SHA-2).
save it in the database along with the user id and his IP.
One thing to bear in mind is that some internet connections share IP addresses or will sometimes change the client IP address (e.g. AOL or mobile).
I send the hash to the user as cookie 3. Whenever he wants to access something, I verify if his cookie hash matches the one on the server and also if his IP matches. Of yes, he is valid or else, log him out.
It sounds like a good way of doing it and there are no flaws in itself. I would implement a session timeout mechanism. For example, store the date last used in the DB for a sliding expiration and the query will only query records that have not expired. You could have a background process that runs to clear out old, expired records.
Also, use HTTPS and set the Secure and HttpOnly flags on the cookie. This will prevent them being leaked over HTTP, but I would not go as far as disabling HTTP on your system as there are workarounds for an attacker if it is anyway.
I would not be concerned with the cookie being stolen by another user on the same machine. If the cookie can be stolen in this way then the user's machine is probably compromised anyway and you cannot make your system protect data that is outside of your control. You could however renew the token (random string) on a periodic basis giving the user a rolling cookie. You would have to ensure only one user can be logged in at once under the same account though for this to be effective.

Your method only makes sure that the user possess the random string you generated and is using the same external IP address. There exists several way of abusing this system:
if your website doesn't enforce HTTPS then a user connecting using an unsecured public WiFi network could be at risk: if another user of the WiFi network is listening to all the packets being sent on the network, he could intercept your cookie and use it to access the website as your legitimate user. Your server would be unable to differentiate them because they'll both use the same IP address... (There is a Firefox extension available which enable anyone to intercept such login cookie easily: http://en.wikipedia.org/wiki/Firesheep)
This system is also more generally vulnerable to man in the middle attacks (without HTTPS)
If your cookie is stored on the user computer's hard drive it could be reused by another user.
So to answer your question, your system can be deemed as secured provided a few conditions:
you enforce the use of HTTPS on your website (unencrypted HTTP connections should be refused)
your random string is truly random (there exist right and wrong ways of generating random strings in PHP)
your cookie has a short expiry and preferably is set as a session cookie.
You should take a look at the following related question providing details about the proper way of doing what you want to do: How to secure an authentication cookie without SSL

One cannot say this is "bad". But in Web Development, and specifically in its security domain relativity talks. I recommend you to download a CodeIgniter (google it for more info) Session Class (standalone version) and use it. The basic idea is the same as yours, but it is properly more mature since it is developed in such a famous php framework. You can do your DB operations within that class too, since it allows session saving to DB.

Related

Hashing and using time as salt to prevent access from un-authorized system and replay attacks

I am currently writing a user authentication API for a mobile game. I'd want to make sure that the user can only access the system from the mobile app. (That is, the server has to deny access if the Server API is accessed from browser or CURL (un-authorized system) even though the exact POST parameters are valid). Ideally, the system should not allow replay attacks as well.
Does anybody have idea or example of how this can be done?
I am thinking of adding a unique-per-user salt with current timestamp and SHA256-ing the parameters with a private key on the client app, which will then be validated on the server. This way will prevent the access from browser or CURL as attackers will need to get the private key in order to compute the SHA256 hash. The salt (which includes timestamp) will also be sent as one of the params, and the server will get the timestamp and deny access if it is past a certain time. But I am not very sure about the security and whether it is the common or correct practice, as I've never design secured app, or seen the source code of one before.
Thanks for your input!
This will stop users from intercepting requests on network and using them with CURL. But both private key and signature algorithm can be extracted for your app and reimplemented, so this solution will not be totally secure.
Alas, you can't have complete security here without some custom tamper-resistant hardware issued to users.

Node.js TCP socket sessions

I have multiple clients connecting to a Node.js TCP socket server from an app. I would like to know a secure way of managing their session.
Username + password is passed over the socket to the server. The server confirms this is correct.
I believe that I now need to generate a unique token to send back to the client.
Now if the user closes the app, then opens it again, this token can be passed to the server and thus the server will confirm the user is authenticated again.
Potentially though, this token could be used by somebody else to gain access to this persons account. Is there a way to prevent this?
Is there a more secure way (whilst still maintaining the ability for the user to authenticate without logging in again)?
How would you handle connections from other devices using the same login. Do they get a different token or the same token?
Many thanks.
It comes down to your definition of secure enough. What you're doing now, which is essentially session tracking, and it is generally secure enough for a lot of general purpose usages - however there is typically an extra component added in which is a session should only be considered valid for a particular ip. If the users' IP changes, you should make them login again and issue them a new token. That way if some bad guy hijacks their session id it won't do them any good.
Now of course this is only valid if your bad guy can't appear to come from the same IP address as your client. If you are concerned about bad guys who are behind the same NAT as your client, and thus can appear to come from the same IP, then you'll have to bump up your security a bit more and maybe consider a system similar to what SSH uses, but that's a bit more complex.
As for connections from multiple devices, it's up to you - you can either keep track of some single token and just hand back that token when the user logs in from a different IP (while at the same time now allowing both IPs to access the site using that same token), or you can just issue a fresh token every time someone authenticates. Personally I tend to find issuing fresh tokens easier, much less tracking and hassle... but it comes down to your application and how you want to organize things, I could dream up good use cases for both methods.
Also, as for doing the password exchange.. You should at least do some hashing there, ie, server sends client some random_string, client then uses some hash function (such as md5 or sha) to compute hash(random_string + hash(username + password)) and sends it back. The server then verifies that this matches by checking hash(random_string + password_hash) is equal to whatever the user sent it. This makes it so the user's plain text password never has to be stored anywhere - on the server you just store password_hash = hash(username+password) when the password changes.
Maybe something like this:
FIRST LOGIN:
username + pwd (hashed) ---> check user/hashed pwd
receive token <--- send token
NEXT LOGIN:
request login ---> receive request
receive random string <--- send random string
hash string with token as salt ---> compare hashed string
You should allow only one attempt with that random string and if possible check the IP from the original login.
This is not perfect because you could still intercept the token at login, but then you would also have the username and pwd.
This question basically comes down to session hijacking using stolen cookies. So the question is how you can secure the cookie as good as possible.
Use https instead of http and force your users to use https. This way, the cookie is not transmitted as clear text and can not be stolen using eavesdropping.
Set the secure attribute on cookies (see Wikipedia) to bind the cookie to https and avoid it from being transferred via http.
Use some kind of message authentication digest, such as HMAC, to make sure that the cookie has not been tampered.
Optionally you can embed the client's IP address into the cookie and only accept it if it is being sent from the specific IP. Unfortunately this may cause problems with proxy servers or dial-up connections where IP addresses are newly assigned from time to time.
Last but not least allow one token only to be used once at a given point in time. If the user logs on using the same token on a second machine, either disallow the connection or end the first machine's session.
Hope this helps ...
PS: I am very sorry, I skipped the TCP part. Of course most of what I wrote only applies to http, not TCP. Anyway, some things might help anyway, such as #3, #4 and #5.

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.

Exists a way to prevent cookies from getting stolen?

in Web 2.0 applications many users usually want to stay logged in ('remember me' flag) and on the other hand their cookie can give access to very private data. Is there a way to prevent that somebody who steals the cookie - directly from the computer or via sniffing - can use the cookie to get access to the user's data? Always HTTPS is not an option.
Thanks, Bernd
[Edit] Connect the IP address to the cookie is not an option either.
KISS -- just use sessions so that you're using an ID that is already automatically created by the server-side scripting language of your choice. That's hard enough to guess. Then, if it's stolen, store the IP address and user-agent of the visitor in the session (making sure never to output that) and only consider the session valid only if the already stored IP address and user agent match that which is found for the remote client.
In this scenario, the attacker would have to do the following three things:
Steal the victim's cookies
Spoof the correct IP address
Spoof the correct User Agent
It also helps to make sure that the attacker doesn't already know all of the things he/she would have to do in order to correctly take over a victim's session. IE: They may assume just the cookie is needed and then fail... and have to figure out everything else through a very long trial and error. In this way, you gain security through obscurity and through difficulty, depending on the skill of the attacker and his/her existing knowledge of the system.
Bernd -- the trouble with anything done over standard HTTP is that it's plaintext; anyone can fake anything. IP Spoofing is a bit more challenging to do than just plain cookie stealing, so tying to the IP tends to be what people do. Like you said, that does not work very well with highly dynamic environments.
The only mostly secure way I can think of is to use HTTPS to place and verify a "permanent" cookie, and then place (in the same HTTPS session) a short-lived session cookie. The rest of the communication can be done over regular HTTP, using the session cookie to authenticate.
That way, fewer resources are used in supporting encryption (just the handshake), the permanent cookie is not exposed -- it's only transmitted under encryption -- and stealing the session cookie opens up to only limited risk, since that cookie will quickly expire.
All that being said -- don't let users click "remember me" on a site that contains truly sensitive data! That's why Banks don't do it..
Hope this helps.
About storing complex cookie ids and associated IPs in a database -- you don't really have to do that. If you have a secret key K, it is enough to encrypt the user's ip with your K, and place the result {IP}K as a cookie. As long as your key is secure (and the crypto hasn't been broken -- but if that happens, we have bigger problems), this is safe.
Perhaps using a Session ID and token (a hash based on the IP, a salt, and the Session ID), that is regenerated every request (use a fast hashing algorithm) would be a good approach? I store session data in a database (currently), and this means I have a two query overhead every request. It works like this:
Select where SID and TOK match.
Verify a token generated based on current client matches that in the database.
deserialise the data into a property.
Scripts etc happening.
Serialise the updated data, regenerate the SID/TOK, and update DB where SID/TOK = old sid and tok, updated data and new sid and tok. Set the cookie to the new SID and TOK.
In this way, firstly cookies are bound to whatever I base the token on (in this case, remote address), and if that is stolen and client data spoofed, the cookie is only useful for one request anyway - by the time the cookie is intercepted, it is useless.
The only perceivable weakness I can see is if the attacker managed to grab a cookie, spoof, and use it, before the real person could do another request. There are a few ways to solve this that I need to think about. The overhead is two queries and generating a token hash twice (once for verification, once for replacement).
Put a lid on the cookie jar.
Jokes aside, the best option has already been stated - make the cookie an obscure ID and tie it to an IP address lookup on the server side. Since you edited to say you cannot tie it to an IP address, that leaves the obscure ID part. Your options are limited with cookies - the minute you place something on the client, it becomes a risk.
Store a cookie that is an obscure ID into your local server database. Do a server-side DB lookup based on the ID provided in the cookie. Be sure to make the ID sufficiently complex that it cannot be easily guessed. Map the ID to the IP Address of the user. If their IP changes, then force them to log in again, and create a new ID.
On second read, it sounds like you want a high level of security with your hands tied. The user must have the choice to remain logged in and thus increase his/her risk. You can implement all the security in the world from the application's and server's point of view, but if the user forgets their laptop on a table in Tim Horton's (Canadian Starbucks), then none of it will do you any good.
Leave the choice up to the user as to whether or not they remain logged in, and give them a warning about their information being at risk.
Bernd - you say connecting the IP address to the cookie is not an option, I'm assuming that's b/c the user could be connected via DHCP, and thus could come in under a different IP each time. Have you considered tying the cookie to the DNS host name? You could encrypt the cookie using a private key, and store it on the user's box. Then whenever they come in, check the cookie, un-encrypt it, and then check the user's current DNS Host name against the one in the cookie. If it matches, you allow them in. If not, you don't allow the auto-login.
FYI - in ASP.Net, to get the DNS host name of the user's box, just look at
Page.Request.UserHostName

SSL session persistence and secure cookies

I currently have a roll-your-own application security service that runs in my enterprise and is - for the most part - meeting business needs.
The issue that I currently face is that the service has traditionally (naively) relied on the user's source IP remaining constant as a hedge against session hijacking - the web applications in the enterprise are not directly available to the public and it was in the past perfectly acceptable for me to require that a users' address remain constant throughout a given session.
Unfortunately this is no longer the case and I am therefore forced to switch to a solution that does not rely on the source IP. I would much prefer to implement a solution that actually accomplishes the original designer's intent (i.e. preventing session hijacking).
My research so far has turned up this, which essentially says "salt your authentication token hash with the SSL session key."
On the face of it, this seems like a perfect solution, however I am left with a nagging suspicion that real-world implementation of this scheme is impractical due to the possibility that the client and server can at any time - effectively arbitrarily - opt to re-negotiate the SSL session and therefore change the key.
this is the scenario I am envisioning:
SSL session established and key agreed upon.
Client authenticates to server at the application level (i.e. via username and password).
Server writes a secure cookie that includes SSL session key.
Something occurs that causes a session re-negotiation. For example, I think IE does this on a timer with or without a reason.
Client submits a request to the server containing the old session key (since there was no application level knowledge of the re-negotiation there was no opportunity for a new, updated hash to be written to the client).
Server rejects client's credential due to hash match failure, etc.
Is this a real issue or is this a misapprehension on my part due to a (to say the least) less-than-perfect understanding of how SSL works?
See all topics related to SSL persistence. This is a well-researched issue in the load-balancer world.
The short answer is: you cannot rely on the SSLID -- most browsers renegotiate, and you still have to use the source IP. If the IP address is likely to change mid-session then you can force a soft-reauthentication, or use the SSLID as a bridge between the two IP changes (and vice-versa, i.e. only assume hijacking if both IP address and SSLID change at the same time, as seen by the server.)
2014 UPDATE
Just force the use of https and make sure that that you are not vulnerable to session fixation or to CRIME. Do not bother to salt your auth token with any client-side information because if an attacker was able to obtain the token (provided that said token was not just trivial to guess) then whatever means were used to obtain it (e.g. cross-site scripting, or the full compromising of the client system) will also allow the attacker to easily obtain any client-side information that might have gone into the token (and replicate those on a secondary system if needed).
If the client is likely to be connecting from only a few systems, then you could generate an RSA keypair in the browser for possibly every new client system the client connects from (where the public part is submitted to your server and the private part remains in what is hopefully secure client storage) and redirect to a virtual host that uses two-way (peer/client certificate) verification in lieu of password-based authentication.
I am wondering why it would not be just enough to simply
require ssl in your transport
encode inputs (html/url/attribute) to prevent cross-site scripting
require only POSTs for all requests that change information and
prevent CSRF as best you can (depending on what your platform supports).
Set your cookies to HTTPOnly
Yes, but there are several things you can do about it. The easiest it to simply cache the session key(s) you use as salt (per user), and accept any of them. Even if the session is renegotiated you'll still have it in your cache. There are details--expiration policy, etc.--but nothing insurmountable unless you are running something that needs to be milspec hardened, in which case you shouldn't be doing it this way in the first place.
-- MarkusQ

Resources