Storing a password in an encrypted cookie? - c#

I know it is not best practice to store a password in a cookie, even if the data is encrypted.
However, I have a web application that needs to be able to search against Active Directory and, as far as I can tell, it requires that the user first binds using their credentials. This means that for each search request, I need to pass the user name and password to the DirectoryEntry constructor.
Given these constraints, is there an alternaive to storing the password in a (secure) cookie?
In absence of something better (e.g. getting a service account), the solution that I'm contemplating is either to store the credentials in an encrypted cookie or cache the DirectorySearcher object.
Thanks

You could store the credentials server-side, generate a unique identifier for them, and store this identifier in a cookie. You can make the identifier expire if needed.

Store the password in a Session Variable, this variable will expires if alive beyond the SessionTimeOut period.

Related

Session protection protect copying and pasting user identity cookie

I logged in as user 1. and user2 in another browser. I have a user identity session value in cookie. when i copy user1 cookie value and paste it in user2 cookie value user 2 got changed to user1 . How to prevent this?
You cannot prevent exactly this behaviour. That means if someone gets a token to represent a user (a cookie in your case) then he can represent that user. This is called session-hijacking. Think of it as someone finding a key to another house, it's not much preventing that person from entering the house even though it's not his.
It is possible to do some workarounds that big sites like google do: check if it's a new location or a new computer and ask for additional validation for example, but it's probably not a simple feature.
Otherwise you need to protect your tokens as best as you can to prevent them being accessible in an easy way, like suggested in comments by using TLS, having HTTP-olny cookie that cannot be read by javascript, etc, ensuring proper logout that will delete the cookie and so on.

How to store Encrypted Password in cookies in C#?

I want to store username and password in cookies.
I encrypted password by using MD5 Hashing technique.
so how can i store that encrypted password in cookies??
Thats not the way. You put some parameters such as timestamp, user agent, current ip, username, etc. But not the Password. Now compute hash for your token and send it as a cookie. Thats how an authentication token is made.
For authenticating the user on Log in, compute the hash on your server and compare it with the one in DB. Don't ever send your hashed password on line. For better criteria you should use salted hash for passwords. See this to get to know about salts.
Moreover MD5 is hashing not an encryption. There is a lot of difference between both of them. Also, use SHA instead of MD5. See this for details.
You shouldn't store username and password in the cookies because that's sent to the client. Even if it's hashed, specially if you are going to compare the hashed password received in the cookie with the one in the database directly. That breaks the purpose of hashing.
If you want to mantain the session of the user between requests, you should use the session ID. I'm not a C# expert, but with a quick google I've found this:
HttpContext.Current.Session.SessionID
That's what I would store in the cookie.
I would not recommend this to anyone...
Rather save get the passwords from the user. save them in a session to use through out the users connection period and if you want the user to use that same password and login later you will have to have a database that you store the data in.
So to store the information as follow
Session["username"] = txtusername.Text;
then to use it again on a different page or somewhere else
string username = Session["username"].toString();

Should I populate a session variable from a cookie?

I have a site with a login function, and a "Remember Me" option. In my users table I have a 128 digit random token which I put in the cookie, and then use to lookup the user.
I will be using a "LoggedInUser" which is an instance of my "User" class, which will be populated with a database lookup, so I can retrieve the users username, id, and other info. Now assuming the user has a cookie, should I simply perform a user lookup using the cookies value, or should I store the token in a session and perform the lookup with that? The main worries here are security and performance, IE which is more secure and which will have shorter load times?
Session Id normally stored in cookie - so there is almost no security differences whether you store ID in cookie yourself or use SessionState cookie.
Same for performance - the main cost will bin in DB lookup, obviously if you do couple extra steps (add/red from session state) it will be (probably not measurably) faster.
Notes:
"random" generated by session state went through plenty of security reviews, hopefully your one is as good too.
Session State cookie is not marked as "secure" by default so will be sent over HTTP too, clearly yours will not be - so custom cookie a bit better.
Session state can be configured cookieless, in your case your scheme is a bit safe (as you can't mistakenly share cookie, but urls are easy to share).

REST API token authentication

I just started a development of my first REST API in .NET. Since it will be stateless I will use tokens for authentication:
Basic idea (System.Security.Cryptography):
AES for encryption + HMACSHA256 for integrity
token data will consist object with properties: username, date of issuing and timeout
database will hold username, hashed password and HMAC hash
Login:
check if credentials are valid (username, compare hashed password to db value)
if true, encrypt data object
use HMAC on generated token and store it to database
return token (without HMAC) to user (cookie/string)
Request to method which requires authentication:
user sends token with each request
token is decrypted
if it is expired, error
if not expired use HMAC and compare username + generated hash with db values
if db check valid, user is authenticated
The way I see it, this approach has following pros:
even if db is comprosmised, it does not contain actual token (hash cannot be reversed...)
even if attacker has token, he cannot increase expiration by updating fields since expiration date is in the token itself
Now firstly, I wonder if this is good approach at all.
Besides that I still didn't figure out, where to store AES and SHA256 keys on server (should i just hardcode them? If I put them into web.config or use machine key than I have a problem in case of load balanced servers,...).
And lastly where do I store AES IV vectors, since Crypto.CreateEncryptor requires it for decryption? Does it mean that users have to send token + IV with each request?
I hope this makes any sense and I thank you for answers in advance.
UPDATE:
Ok, now I did some more research and came down with this solution:
token will contain originally specified data (username, date of issuing and timeout)
token is generated with encrypt-then-mac (it includes AES encrypted data, IV vector + tag of these 2 values for authentication, generated with HMACSHA265)
token tag will be written to db
user will be authenticated if:
tag is valid (token authentication)
data can be decrypted
token has not expired yet
tag matches the one written in database
user is not blocked in database (token invalidation on demand)
keys will be stored in web.config separate section. Same keys will have to be on every server (per application of course)
I didn't use FormsAuthenticationTicket because in .NET there are following issues:
same keys are used for different purposes (machinekey for view states, resources and formauthtickets)
mac-then-encrypt, used by .NET is not considered as safe as encrypt-then-mac
no built in way to invalidate token before it is expired
This is a follow up from the comment thread under the question.
You seem to be a bit confused as to what, exactly, OAuth is, so hopefully I can clarify it here.
OAuth is not a web service or something you consume. It is a protocol that describes the way that a site can authenticate a user against a service, without allowing the site to know what the user's credentials are. As a side benefit, most OAuth providers also have a web service to query the user's information, and permission to do so can be granted at the same time.
Typically, you are interested in implementing OAuth from the perspective of the site (eg, AcmeWidgets.com) so that a user can log in via Facebook or Google or something. However, you can also implement the service side (eg, where Facebook normally would be), and allow others to authenticate against YOU.
So, for example, let's say you have a web service to allow for third-party sites to provision Acme-brand Widgets for users. Your first third-party implementor is the popular MyBook.org. The flow would look something like this:
Someone invites the User to use the "Acme Widgets" app on their MyBook profile.
The user clicks on the button, which redirects to AcmeWidgets.com. The URL looks something like:
http://acmewidgets.com/oauth/user?r=http%3A%2F%2Fmybook.org%2Foauth%2Fclient&appid=12345
The user is asked if they want to allow MyBook to access their data and provision widgets.
The user clicks Yes, whereupon Acme Widgets notes that the user has allowed it.
The user is redirected back to MyBook, at a URL like this:
http://mybook.org/oauth/client?token=ABCDEFG
MyBook, on the server side, now takes that token, and places a web service call BACK to AcmeWidgets:
http://acmewidgets.com/oauth/validate?token=ABCDEFG&appid=12345&appsecret=67890
AcmeWidgets replies with the final authentication token identifying the user.
Alternately, it fails, which means the user is trying to fake a token, or they denied permission or some other failure condition.
MyBook, with the token, can now call AcmeWidgets APIs:
http://acmewidgets.com/api/provision?appid=12345&token=ABC123&type=etc
This is all known as the OAuth dance. Note that there are a number of implementation defined things here, like URLs, the means of encoding the various tokens, whether tokens can expire or be revoked, etc.
Hopefully that clears everything up for you!

Authenticaion, hash, salt, https process?

Hi I think I may have done this the wrong way round can anyone help explain how you hash/salt a password. Do you do it from the client or the webservice?
I have a datacontract which has a password datamember, in my service I do this to create a hash/salt of the password before it is saved:
So here is the process in which I was thinking.
Rest Service has https for secure connection
User creates account (along with password)
//to stop packet sniffing when user creates account https is used during POST so no one can see the password?
web service then creates a hash of the password to store it
//so if anyone did get access to the service/database they couldnt make much use of the data in terms of breaching accounts
Then some means to authenticate that user there after
Is this correct?
Sounds like you're on the right track. Hashing along with the salt value should never occur on client side, as attackers will have access to that code. And https would indeed secure the connection, disallowing others from reading the data.
During authentication you do the same thing: take the password the user entered via https, hash/salt that value, then compare the result hash with the value in the database. And of course if you ever return a Student object to the client, it should contain neither of the values.
It may be wise not to reuse the Password property of Student since now you can't tell whether it contains the plain password or the hashed value.

Categories