Encrypting using user's password - c++

I want to encrypt a given data using the log-in user's password on a windows machine using WINAPI. I've been looking for a function that uses a token (or something like that) but I couldn't find one.
Does anyone know how to do that?
Thanks! :-)

The Windows Data Protection API sounds like what you need. The CryptProtectData and CryptUnprotectData functions perform encryption using the logon credentials of the current user.

I had written this answer earlier but then reconsidered, since I hadn't heard of the DPAPI before. However, upon some further consideration, I'd like to offer the following opinion. The important preface here is that it all depends on your needs, though. Two conflicting possibilities come to mind:
You want to offer your user complete protection and encryption that the user can trust only she will be able to decrypt, no matter the circumstances.
You're an enterprise IT manager and have all employees on a tight leash. You want them to encrypt business data as part of their workflow so that they cannot see each other's data, but the admins can happily read everyone's data.
If you're in situation (2), then stop reading now and go with DPAPI, which is well suited to that case. If you prefer scenario (1), then read my original answer below.
That's probably not a good idea. Here's why:
The actual password will not be stored on the system (unless you have Windows 3.11 or something like that). Instead, only a hash of the password will be stored, and at login time the password that the user enters is hashed and compared to the stored hash.
So at best you could retrieve the stored hash from the system (if you have admin rights, say). However, if that's the only datum you can go on, then any encryption key you make will be derived from that hash, rather than from the actual password. Thus anyone with access to the system could get to the stored hash, and from there derive the encryption key with relative ease.
In short, don't. Ask the user for a dedicated, fresh password for your data and use it for only that.

use Kerberos (Linux-based authentication server, or other servers using Kerberos) / LDAP framework (Windows server) instead of designing your own login algorithm.
Windows Platform SDK & 3rd-party libraries have connectors with these frameworks.
More information in MSDN about Kerberos: http://msdn.microsoft.com/en-us/library/ff649429.aspx

How to safely store a password
Win32 bcrypt: http://msdn.microsoft.com/en-us/library/aa375421%28v=vs.85%29.aspx

Related

Django: Securing / encrypting stored files

In a Django project, I want to keep user uploaded files secure on the server. Should this be done at the OS level (we are using ubuntu) or at the application level?
Encrypting at the application level will be easier to maintain. But, aside from some drawbacks like possible negative effect on performance, I am not even sure if this will have any point. If a hacker compromises the server, he will also have access to the encryption keys and how it is encrypted / decrypted.
Any suggestions are greatly appreciated. Thanks.
How you protect your data depends on what kinds of attacks you want to protect against. Of course, you probably don't know how an attacker is most likely to compromise your system, unless there are certain threat models you're particularly trying to protect against, like say a rogue sysadmin.
The attacker might gain access to the OS that the web server is running on. In this case, filesystem level encryption probably does you no good. In fact file-system level encryption is probably only useful protection against somebody walking off with the physical server (which is a totally valid threat model). However, if the files are encrypted with keys stored in the database, then an attacker who has access to the webserver OS but not the database is thwarted.
In contrast, an attacker might gain access to the database but not the OS, through a hole in your application. I would expect this to be less likely since modern operating systems present huge and well-studied attack surfaces.
To protect your user's data against an attacker with full access to your servers is very difficult. You need to encrypt the data with a key that your servers don't have. This could be something like a password or a key stored in a user cookie. The problem with all these schemes is that users can't be trusted to hold on to critical data like this -- they always want a way to reset their password if they forget. In most cases, it's not realistic to protect data against an attacker with full access to your OS and your database.
So I'd choose what you're trying to protect against. Personally, I'd expect an OS penetration to be most likely, and thus encrypt the files with keys that are stashed in a part of the database that is extra protected somehow. The challenge here is that the OS has to store database login credentials (in settings.py) in order for the web app to function. So try to keep those files as restricted as possible within the OS i.e. chmod 600 on a user account that does as little else as possible.
You're right that if the key used to encrypt the files is stored on the server you don't get a whole lot of added security by encrypting the files.
However, if you use a key provided by the user, then you do get some security. For example, if you store the encryption key in a cookie, then it will only be available for the duration of each request. I don't believe this will create any new security issues (if an attacker can steal the cookie, they can also steal the user's session), and it will make it much harder for an attacker to access files belonging to users who aren't currently online.
If you're really paranoid, you could do what 1Password does, and send encrypted data back to the browser, which can decrypt it with JavaScript encryption routines…

How insecure is this?

Looking for feedback. I am building a django app where users are given randomly generated passwords.
Currently, the password is being generated using the make_random_password() function in django auth.
However, early feedback is that the emails are too hard to remember (even though the users can change them).
This is a closed (invite only) app, but it lives on the internet. with about 600 users total. I had a solution that I feel is is somewhat insecure, but I wanted to run it by SO users, as it solves the feedback issue
In my settings.py file, I have created two lists, one contains about 20 car names, the other about 40 verbs (which are capitalized).
I was going randomly select one from each list, join them together and then append a few random chars to the end.
All passwords would be at least 9 chars long and when saved are hashed using django's set_password() function
The biggest issue I see is that if someone were to gain access to the SFTP server they would then have access to my code AND hence a template for cracking the pwords.
BUT they would also have db access etc, so is it really a concern?
You should always assume that the attacker has access to your password generation scheme. Basing your security on the assumption that he doesn't is trusting security through obscurity. Obscurity can give a nice security bonus but you should never rely on it.
You must assume the attacker knows the content of both lists. For example he can simply register about 40 times, and then knows a significant part of them.
Your car-names combined with the verbs have about 9.6(=log2(20)+log2(40)) bits of entropy. Corresponds to about 2 random characters. That's very low.
Can you force a password change the first time a user logs in? Or, if all your users have already been logged in, force a password change the next log in? That way, you can keep the more secure passwords and users can't complain about the randomly generated password being hard to remember because they have to change them to something they do remember.
How about using an OpenID system, so they don't have to remember yet another password. There's some Django integration on the interwebs. The downside is that you'll need to know their OpenID in order to add them to the auth DB before you send out the invites...
The Concept of doing a random password generation as far as you have a flag stating which random password generation pattern used for generating the password as you need to check the password in later sign ins.. are you doing that? If yes then add a salting pattern to make it secure and finally a hash of the overall salt generated will be more safe. Try this ..

Other ways of protecting cookies

I've been thinking a lot about this recently, and I wanted to know if anyone has thought of/implemented any intuitive ways of securing cookies from manipulation. I've always used the "sign it with a hash and check against the hash later" approach, but it doesn't strike me as a particularly brilliant way of going about it, and just like all good programmers I want to find a better way of doing it.
As for why cookies specifically, well, I don't use native sessions - I hate to touch the filesystem. Cookies are a really quick way of storing data for later, and even with things such as user authentication I'll chuck the user ID in the cookie, perhaps along with the username/email and a signature, as well as a random hash for good measure.
What clever ways have you used to secure your cookie data?
Uh, you're storing the UserID in the cookie and giving the user access based on that value? You're asking for trouble. Server session based data implementations exist for a good security reason: Store a session identifier in the cookie and access the UserID from the record on the server where the client can't tamper with it.
Cookie security to protect against client tampering is pretty much a lost cause. Given enough time, someone will figure out how to crack it. Don't give clients that opportunity. Cookie security's only purpose is to make sure client's cookies aren't stolen.
Signing the cookie with a HMAC is a perfectly reasonable way to do this. HMAC essentially rolls a secret key known only by your server into the hash, so even someone who knows the algorithm can't generate a HMAC that will be recognized as valid without knowing the key. Just using a plain old hash is trivially bypassable because the attacker can generate valid hashes of their own data, and all the "salt" in the ocean won't fix that.
Even if you used a session ID instead of storing meaningful values, you still would have to be careful that an attacker couldn't predict another valid session ID, and send that to you instead, thus hijacking the other user's session. I believe there was an actual exploit against Hotmail that worked this way.
Encrypting the cookie only helps you if there's something in there you don't want the user to see. Even worse, encryption without an HMAC gives a false sense of security because a cookie that is merely encrypted is still vulnerable to manipulation of the ciphertext to change parts of the plaintext.
So in summary, don't just hash it, use an HMAC!
With hashing you need to be very careful that you have included a salt, otherwise it can be trivial to determine a matching hash.
Thus, to protect against accidents, it's often appropriate to also encrypt the cookie.
-- edit
You may also like to learn about 'HTTPOnly' cookies: http://www.owasp.org/index.php/HTTPOnly
On the Security Now podcast (i forgot which episode), Steve Gibson talks about doing something like this and i think the system he recommended was to make the contents of the cookie a good hash, then make that hash a key in your local database where the value(s) is(are) all of the info that it needs to store.

How can I uniquely identify a desktop application making a request to my API?

I'm fleshing out an idea for a web service that will only allow requests from desktop applications (and desktop applications only) that have been registered with it. I can't really use a "secret key" for authentication because it would be really easy to discover and the applications that use the API would be deployed to many different machines that aren't controlled by the account holder.
How can I uniquely identify an application in a cross-platform way that doesn't make it incredibly easy for anyone to impersonate it?
You can't. As long as you put information in an uncontrolled place, you have to assume that information will be disseminated. Encryption doesn't really apply, because the only encryption-based approaches involve keeping a key on the client side.
The only real solution is to put the value of the service in the service itself, and make the desktop client be a low-value way to access that service. MMORPGs do this: you can download the games for free, but you need to sign up to play. The value is in the service, and the ability to connect to the service is controlled by the service (it authenticates players when they first connect).
Or, you just make it too much of a pain to break the security. For example, by putting a credential check at the start and end of every single method. And, because eventually someone will create a binary that patches out all of those checks, loading pieces of the application from the server. With credentials and timestamp checks in place, and using a different memory layout for each download.
You comment proposes a much simpler scenario. Companies have a much stronger incentive to protect access to the service, and there will be legal agreements in effect regarding your liability if they fail to protect access.
The simplest approach is what Amazon does: provide a secret key, and require all clients to encrypt with that secret key. Yes, rogue employees within those companies can walk away with the secret. So you give the company the option (or maybe require them) to change the key on a regular basis. Perhaps daily.
You can enhance that with an IP check on all accesses: each customer will provide you with a set of valid IP addresses. If someone walks out with the desktop software, they still can't use it.
Or, you can require that your service be proxied by the company. This is particularly useful if the service is only accessed from inside the corporate firewall.
Encrypt it (the secret key), hard-code it, and then obfuscate the program. Use HTTPS for the web-service, so that it is not caught by network sniffers.
Generate the key using hardware speciffic IDs - processor ID, MAC Address, etc. Think of a deterministic GUID.
You can then encrypt it and send it over the wire.

comparison of ways to maintain state

There are various ways to maintain user state using in web development.
These are the ones that I can think of right now:
Query String
Cookies
Form Methods (Get and Post)
Viewstate (ASP.NET only I guess)
Session (InProc Web server)
Session (Dedicated web server)
Session (Database)
Local Persistence (Google Gears) (thanks Steve Moyer)
etc.
I know that each method has its own advantages and disadvantages like cookies not being secure and QueryString having a length limit and being plain ugly to look at! ;)
But, when designing a web application I am always confused as to what methods to use for what application or what methods to avoid.
What I would like to know is what method(s) do you generally use and would recommend or more interestingly which of these methods would you like to avoid in certain scenarios and why?
While this is a very complicated question to answer, I have a few quick-bite things I think about when considering implementing state.
Query string state is only useful for the most basic tasks -- e.g., maintaining the position of a user within a wizard, perhaps, or providing a path to redirect the user to after they complete a given task (e.g., logging in). Otherwise, query string state is horribly insecure, difficult to implement, and in order to do it justice, it needs to be tied to some server-side state machine by containing a key to tie the client to the server's maintained state for that client.
Cookie state is more or less the same -- it's just fancier than query string state. But it's still totally maintained on the client side unless the data in the cookie is a key to tie the client to some server-side state machine.
Form method state is again similar -- it's useful for hiding fields that tie a given form to some bit of data on the back end (e.g., "this user is editing record #512, so the form will contain a hidden input with the value 512"). It's not useful for much else, and again, is just another implementation of the same idea behind query string and cookie state.
Session state (any of the ways you describe) are all great, since they're infinitely extensible and can handle anything your chosen programming language can handle. The first caveat is that there needs to be a key in the client's hand to tie that client to its state being stored on the server; this is where most web frameworks provide either a cookie-based or query string-based key back to the client. (Almost every modern one uses cookies, but falls back on query strings if cookies aren't enabled.) The second caveat is that you need to put some though into how you're storing your state... will you put it in a database? Does your web framework handle it entirely for you? Again, most modern web frameworks take the work out of this, and for me to go about implementing my own state machine, I need a very good reason... otherwise, I'm likely to create security holes and functionality breakage that's been hashed out over time in any of the mature frameworks.
So I guess I can't really imagine not wanting to use session-based state for anything but the most trivial reason.
Security is also an issue; values in the query string or form fields can be trivially changed by the user. User authentication should be saved either in an encrypted or tamper-evident cookie or in the server-side session. Keeping track of values passed in a form as a user completes a process, like a site sign-up, well, that can probably be kept in hidden form fields.
The nice (and sometimes dangerous) thing, though, about the query string is that the state can be picked up by anyone who clicks on a link. As mentioned above, this is dangerous if it gives the user some authorization they shouldn't have. It's nice, though, for showing your friends something you found on the site.
With the increasing use of Web 2.0, I think there are two important methods missing from your list:
8 AJAX applications - since the page doesn't reload and there is no page to page navigation, state isn't an issue (but persisting user data must use the asynchronous XML calls).
9 Local persistence - Browser-based applications can persist their user data and state to the local hard drive using libraries such as Google Gears.
As for which one is best, I think they all have their place, but the Query String method is problematic for search engines.
Personally, since almost all of my web development is in PHP, I use PHP's session handlers.
Sessions are the most flexible, in my experience: they're normally faster than db accesses, and the cookies they generate die when the browser closes (by default).
Avoid InProc if you plan to host your website on a cheap-n-cheerful host like webhost4life. I've learnt the hard way that because their systems are over subscribed, they recycle the applications very frequently which causes your session to get lost. Very annoying.
Their suggestion is to use StateServer which is fine except you have to serialise/deserialise the session eash post back. I love objects and my web app is full of them. I'm concerned about performance when switching to StateServer. I need to refactor to only put the stuff I really need in the session.
Wish I'd know that before I started...
Cheers, Rob.
Be careful what state you store client side (query strings, form fields, cookies). Anything security-related should not be stored client-side, except maybe a session identifier if it is reasonably obscured and hard to guess. There are too many websites that have settings like "authenticated=true" and store those in a cookie or query string or hidden form field. It is trivial for a user to bypass something like that. Remember that ANY input coming from a client could have been tampered with and should not be trusted.
Signed Cookies linked to some sort of database store when you need to grab data. There's no reason to be storing data on the client side if you have a connected back-end; you're just looking for trouble if this is a public facing website.
It's not some much a question of what to use & what to avoid, but when to use which. Each has a particular circumstances when it is the best, and a different circumstance when it's the worst.
The deciding factor is generally lifetime of the data. Session state lives longer than form fields, and so on.