Is It Secure To Store Passwords In Web Application Source Code? - security

So I have a web application that integrates with several other APIs and services which require authentication. My question is, is it safe to store my authentication credentials in plain text in my source code?
What can I do to store these credentials securely?
I think this is a common problem, so I'd like to see a solution which secures credentials in the answers.
In response to comment: I frequently use PHP, Java, and RoR
I'd like to see some more votes for an answer on this question.

Here's what we do with our passwords.
$db['hostname'] = 'somehost.com'
$db['port'] = 1234;
$config = array();
include '/etc/webapp/db/config.php';
$db['username'] = $config['db']['username'];
$db['password'] = $config['db']['password'];
No one but webserver user has access to /etc/webapp/db/config.php, this way you are protecting the username and password from developers.

The only reason to NOT store the PW in the code is simply because of the configuration issue (i.e. need to change the password and don't want to rebuild/compile the application).
But is the source a "safe" place for "security sensitive" content (like passwords, keys, algorithms). Of course it is.
Obviously security sensitive information needs to be properly secured, but that's a basic truth regardless of the file used. Whether it's a config file, a registry setting, or a .java file or .class file.
From an architecture point of view, it's a bad idea for the reason mentioned above, just like you shouldn't "hard code" any "external" dependencies in your code if you can avoid it.
But sensitive data is sensitive data. Embedding a PW in to a source code file makes that file more sensitive than other source code files, and if that's your practice, I'd consider all source code as sensitive as the password.

It is not to be recommended.
An encrypted web.config would be a more suitable place (but note can't be used with a web farm)

It appears the answer is the following:
Don't put credentials in source code but...
Put credentials in a configuration file
Sanitize log files
Set proper permissions/ownership on configs
Probably more depending on platform...

No, it is not.
Plus, you might want to change your password one day, and probably having yo change the source code may not be the best option.

No. Sometimes it is unavoidable. Better approach is to have an architecture set up where the service will implicitly trust your running code based on another trust. (Such as trusting the machine the code is running on, or trusting the application server that is running the software)
If neither of these are available, it would be perfectly acceptable to write your own trust mechanism, though I would keep it completely separate from the application code. Also, would recommend researching ways to keep passwords out of the hands of predators, even when stored on local machine - remembering that you can't protect anything if someone has control of the physical machine it is on.

If you control the Web server, and maintain it for security updates, then in the source (preferably in a configuration module) or in a configuration file that the source uses is probably best.
If you do not control the Web server (say, you are on a shared or even dedicated server provided by a hosting company), then encryption won't help you very much; if the application can decrypt the credentials on a given host, than the host can be used to decrypt the credentials without your intervention (think root or Administrator looking at the source code, and adapting the decryption routine so that it can be used to read the configuration). This is even more of a possibility if you are using unobfuscated managed code (e.g., JVM or .NET) or a Web scripting language that resides in plaintext on the server (like PHP).
As is usually the case, there is a tradeoff between security and accessibility. I'd think about what threats are the ones you are trying to guard against and come up with a means to protect against the situations that you need. If you're working with data that needs to be secure, you should probably be redacting the database fairly regularly and moving data offline to a firewalled and well-protected database server as soon as it becomes stale on the site. This would include data like social security numbers, billing information, etc., which can be referenced. This would also mean that you'd ideally want to control the servers on your own network which provide billing services or secure data storage.

I prefer to keep them in a separate config file, located somewhere outside the web server's document root.
While this doesn't protect against an attacker subverting my code in such a way that it can be coerced into telling them the password, it does still have an advantage over putting the passwords directly into the code (or any other web-accessible file) in that it eliminates concern over a web server misconfiguration (or bug/exploit) allowing an attacker to download the password-containing file directly.

One approach is to encrypt The passwords before placing the password in config.web

I'm writing this for web service app that receives password, not client:
If you save hashed passsword in source code someone who views the source code won't be able to help himself with that hash.
Your program would receive plain password and hash it and compare both hashes.
That's why we save hashed passwords into databases, not plain text. Because they can't be reversed if someone for example steals db or views it for malicious purposes he won't get all users passwords, only the hashes which are pretty useless to him.
Hashing is 1 way process: it produces same value from same source but you can't compute source value out of hash.
Storing on client: when user enters pass u save it to db/file in plaintext, maybe obfuscate a little but not much u can do to prevent someone who gets a hold of that computer to get that password.

Nobody seems to have mentioned hashing yet - with a strong hash algorithm (ie SHA-2 and not MD5), it should be much safer.

Related

How to securely store a password used for 3rd party service on my website

I have a website I created with a nodeJS back-end and I'm currently stuck with a security issue.
For my website to function, I need to login using a 3rd party service that requires a username, password, and security code. I have to be able to sign in to multiple accounts multiple times automatically throughout the day for my website to function. I'm not storing any user information, this is my own account info.
So obviously storing everything in plain text in one of my classes is a bad idea, so what would be the best way to store my login information? Would having a database that can only be accessed locally with the data inside be a good option? As I said before, it has to be able to automatically login so I'm not sure if hashing it would work since the code will have to decrypt it anyways so if my code is ever exposed, will it really matter?
Thanks in advance for any help.
You’re basically asking “how do I store secrets on my backend?”.
Locally you would use a .env file, which isn’t committed to version control, that stores your secrets (i.e. “USERNAME=JBallin”).
You would then use something like dotenv to extract those values into environment variables and use them on your backend.
In production, you would store these environment variables on the server (instructions depend on the deployment environment).
It is probably not a good idea to store a password, because even if you encrypt it,
the encryption key is still somewhere in the server.
Have you checked if the 3rd party service offer auth flow as oauth or equivalent?
There is a new technology - Password-Hardened Encryption (PHE) protocol – a powerful and revolutionary cryptographic technology that provides stronger and more modern security, that secures users' data and lessens the security risks associated with weak passwords.
Virgil PureKit allows developers to interact with Virgil PHE Service to protect users' passwords and sensitive personal identifiable information (PII data) in a database from offline/online attacks and makes stolen passwords/data useless if your database has been compromised. Neither Virgil nor attackers know anything about users' passwords/data.
I provided you with the link where you can find out code-snippets for such langs as: Go, PHP, C#, Java

How does PasswordVault protect passwords? [duplicate]

I'd like to use Windows.Security.Credentials.PasswordVault in my desktop app (WPF-based) to securely store a user's password. I managed to access this Windows 10 API using this MSDN article.
I did some experiments and it appears that any data written to PasswordVault from one desktop app (not a native UWP app) can be read from any other desktop app. Even packaging my desktop app with Desktop Bridge technology and thus having a Package Identity does not fix this vulnerability.
Any ideas how to fix that and be able storing the app's data secure from other apps?
UPDATE: It appeared that PasswordVault adds no extra security over DPAPI. The case is closed with a negative result.
(this is from what I can understand of your post)
There is no real way of preventing data access between desktop apps when using these kind of API's http://www.hanselman.com/blog/SavingAndRetrievingBrowserAndOtherPasswords.aspx tells more about it. You'd probably just want to decrypt your information.
memory access restriction is difficult, code executed by the user is always retrievable by the user so it would be difficult to restrict this.
have you considered using the Windows Data Protection API :
https://msdn.microsoft.com/en-us/library/ms995355.aspx
grabbed straight from the source
DPAPI is an easy-to-use service that will benefit developers who must provide protection for sensitive application data, such as passwords and private keys
WDPAPI uses keys generated by the operating system and Triple DES to encrypt/decrypt your data. Which means your application doesn't have to generate these keys, which is always nice.
You could also use the Rfc2898DeriveBytes class, this uses a pseudo-random number generator to decrypt your password. It's safer than most decrypters since there is no practical way to go back from the result back to the password. This is only really useful for verifying the input password and not retrieving it back again. I have never actually used this myself so I would not be able to help you.
https://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes(v=vs.110).aspx
see also this post which gives a way better explanation than I can.
How to securely save username/password (local)?
If I misunderstood the question in some way, tell me, I will try to update the answer.
NOTE that modern/metro apps do not have this problem, although they still are accessible in other ways.
The hard truth is that storing a password in a desktop application, 100% securely is simply not possible. However, you can get close to 100%.
Regarding your original approach, PasswordVault uses the Credential Locker service which is built into windows to securely store data. Credential Locker is bound to the user's profile. Therefore, storing your data via PasswordVault is essentially equivalent to the master password approach to protecting data, which I talk about in detail further down. Only difference is that the master password in that case is the user's credentials. This allows applications running during the user's session to access the data.
Note: To be clear, I'm strictly talking about storing it in a way that allows you access to the plain text. That is to say, storing it in an encrypted database of any sort, or encrypting it yourself and storing the ciphertext somewhere. This kind of functionality is necessary in programs like password managers, but not in programs that just require some sort of authentication. If this is not a necessity then I strongly recommend hashing the password, ideally per the instructions laid out in this answer by zaph. (Some more information in this excellent post by Thomas Pornin).
If it is a necessity, things get a bit more complicated: If you want to prevent other programs (or users I suppose) from being able to view the plaintext password, then your only real option is to encrypt it. Storing the ciphertext within PasswordVault is optional since, if you use good encryption, your only weak point is someone discovering your key. Therefore the ciphertext itself can be stored anywhere. That brings us to the key itself.
Depending on how many passwords you're actually trying to store for each program instance, you might not have to worry about generating and securely storing a key at all. If you want to store multiple passwords, then you can simply ask the user to input one master password, perform some salting and hashing on that, and use the result as the encryption key for all other passwords. When it is time for decryption, then ask the user to input it again. If you are storing multiple passwords then I strongly urge you to go with this approach. It is the most secure approach possible. For the rest of my post however, I will roll with the assumption that this is not a viable option.
First off I urge you not to have the same key for every installation. Create a new one for every instance of your program, based on securely generated random data. Resist the temptation to "avoid having to store the key" by having it be generated on the fly every time it is needed, based on information about the system. That is just as secure as hardcoding string superSecretKey = "12345"; into your program. It won't take attackers long to figure out the process.
Now, storing it is the real tricky part. A general rule of infosec is the following:
Nothing is secure once you have physical access
So, ideally, nobody would. Storing the encryption keys on a properly secured remote server minimizes the chances of it being recovered by attackers. Entire books have been written regarding server-side security, so I will not discuss this here.
Another good option is to use an HSM (Hardware Security Module). These nifty little devices are built for the job. Accessing the keys stored in an HSM is pretty much impossible. However, this option is only viable if you know for sure that every user's computer has one of these, such as in an enterprise environment.
.Net provides a solution of sorts, via the configuration system. You can store your key in an encrypted section of your app.config. This is often used for protecting connection strings. There are plenty of resources out there on how to do this. I recommend this fantastic blog post, which will tell you most of what you need to know.
The reason I said earlier not to go with simply generating the key on the fly is because, like storing it as a variable in your code, you rely exclusively on obfuscation to keep it secure. The thing about this approach is that it usually doesn't. However, sometimes you have no other option. Enter White Box cryptography.
White box cryptography is essentially obfuscation taken to the extreme. It is meant to be effective even in a white-box scenario, where the attacker both has access to and can modify the bytecode. It is the epitome of security through obscurity. As opposed to mere constant hiding (infosec speak for the string superSecretKey approach) or generating the key when it is needed, white box cryptography essentially relies on generating the cipher itself on the fly.
Entire papers have been written on it, It is difficult to pull off writing a proper implementation, and your mileage may vary. You should only consider this if you really really really want to do this as securely as possible.
Obfuscation however is still obfuscation. All it can really do is slow the attackers down. The final solution I have to offer might seem backwards, but it works: Do not hide the encryption key digitally. Hide it physically. Have the user insert a usb drive when it is time for encryption, (securely) generate a random key, then write it to the usb drive. Then, whenever it is time for decryption, the user only has to put the drive back in, and your program reads the key off that.
This is a bit similar to the master password approach, in that it leaves it up to the user to keep the key safe. However, it has some notable advantages. For instance, this approach allows for a massive encryption key. A key that can fit in a mere 1 megabyte file can take literally billions of years to break via a brute force attack. Plus, if the key ever gets discovered, the user has only themselves to blame.
In summary, see if you can avoid having to store an encryption key. If you can't, avoid storing it locally at all costs. Otherwise, your only option is to make it as hard for hackers to figure it out as possible. No matter how you choose to do that, make sure that every key is different, so even if attackers do find one, the other users' keys are safe.
Only alternative is to encrypt password with your own private key stored somewhere in your code. (Someone can easily disassemble your code and get the key) and then store encrypted password inside PasswordVault, however the only security you have is any app will not have access to password.
This is dual security, in case of compromised machines, attacker can get access to PasswordVault but not your password as they will need one more private key to decrypt the password and that will be hidden somewhere in your code.
To make it more secure, if you leave your private key on your server and expose an API to encrypt and decrypt password before storing in Vault, will make it most secure. I think this is the reason people have moved on to OAuth (storing OAuth token in PasswordVault) etc rather then storing password in vault.
Ideally, I would recommend not storing password, instead get some token from server and save it and use that token for authentication. And store that token in PasswordVault.
It is always possible to push the security, with miscellaneous encryption and storage strategies. Making something harder is only making the data retrieval longer, never impossible. Hence you need to consider the most appropriate level of protection considering execution cost x time (human and machine) and development cost x time aspects.
If I consider strictly your request, I would simply add a layer (class, interface) to cipher your passwords. Best with asymmetrical encryption (and not RSA). Supposing the other softs are not accessing your program data (program, files OR process), this is sufficient. You can use SSH.NET (https://github.com/sshnet/SSH.NET) to achieve this quickly.
If you would like to push the security and give a certain level of protection against binary reverse-engineering (including the private key retrieval), I recommend a small (process limited) encrypted VM (like Docker, https://blogs.msdn.microsoft.com/mvpawardprogram/2015/12/15/getting-started-with-net-and-docker/) based solution such as Denuvo (https://www.denuvo.com/). The encryption is unique per customer and machine based. You'll have to encapsulated you c# program into a c/c++ program (which acts like a container) that will do all the in-memory ciphering-deciphering.
You can implement your own strategy, depending on the kind of investment and warranty you require.
In case your program is a backend program, you can pick the best strategy (the only I really recommend) of all which is to store the private key at the client side, public key at backend side and have local deciphering, all transmitted password would be hence encrypted. I would like to remark that password and keys are actually different strategies to achieve the same goal: checking if the program talks to the right person without knowing the person's identity; I mean this: instead of storing passwords, better store directly public keys.
Revisiting this rather helpful issue and adding a bit of additional information which might be helpful.
My task was to extend a Win32 application that uses passwords to authenticate with an online service with a "save password" functionality. The idea was to protect the password using Windows Hello (UserConsentVerifier). I was under the impression that Windows surely has something comparable to the macOS keychain.
If you use the Windows Credential Manager APIs (CredReadA, CredWriteA), another application can simply enumerate the credentials and if it knows what to look for (the target name), it will be able to read the credential.
I also explored using DPAPI where you are in charge of storing the encrypted blob yourself, typically in a file. Again, there seems to be no way (except obfuscation) to prevent another application from finding and reading that file. Supplying additional entropy to CryptProtectData and CryptUnprotectData again poses the question of where to store the entropy (typically I assume it would be hard-coded and perhaps obfuscated in the application: this is security by obscurity).
As it turns out, neither DPAPI (CryptProtectData, CryptUnprotectData) nor Windows Credential Manager APIs (CredRead, CredWrite) can prevent another application running under the same user from reading a secret.
What I was actually looking for was something like the macOS keychain, which allows applications to store secrets, define ACLs on those secrets, enforce biometric authentication on accessing the secret, and critically, prevents other applications from reading the secrets.
As it turns out, Windows has a PasswordVault which claims to isolate apps from each other, but its only available to UWP apps:
Represents a Credential Locker of credentials. The contents of the locker are specific to the app or service. Apps and services don't have access to credentials associated with other apps or services.
Is there a way for a Win32 Desktop application to access this functionality? I realize that if a user can be brought to install and run a random app, that app could probably mimic the original application and just prompt the user to enter the secret, but still, it's a little disappointing that there is no app-level separation by default.

What is the risk of hardcoded credentials in creating database connection?

Hi security aware people,
I have recently scanned my application with a tool for static code analysis and one of the high severity findings is a hardcoded username and password for creating a connection:
dm.getConnection(databaseUrl,"server","revres");
Why does the scanner think this is a risk for the application? I can see some downsides such as not being able to change the password easily if it's compromised. Theoretically someone could reverse-engineer the binaries to learn the credentials. But I don't see the advantage of storing the credentials in a config file, where they are easy to locate and read, unless they are encrypted. And if I encrypt them, I will be solving the same problem with the encryption key...
Are there any more risks that I cannot see? Or should I use a completely different approach?
Thank you very much.
A fixed password embedded in the code will be the same for every installation, and accessible by anyone with access to the source code or binary (including the installation media).
A password read from a file can be different for each installation, and known only to those who can read the password file.
Typically, your installer will generate a unique password per site, and write that securely to the file to be read by your application. (By "securely", I mean using O_CREAT|O_EXCL to prevent symlink attacks, and with a correct selection of file location and permissions before anyone else can open it).
This is an interesting one, I can give you examples for a .Net application (as you haven't specified running environment / technologies used). Although my guess is Java? I hope this is still relevant and helps you.
My main advice would be to read this article and go from there: Protecting Connection information - MSDN
Here is a page that describes working with encrypted configuration files here
I've seen this solved both using encrypted configuration files and windows authentication. I think that running your application as a user that will be granted access to the relevant stored procedures etc (as little as possible, e.g. Principle of Least Privilege) and furthermore folder access etc is a good route.
I would recommend using both techniques because then you can give relevant local folder access to the pool for IIS and split out your user access in SQL etc. This also makes for better auditing!
This depends on your application needs though. The main reason to make this configurable via a config file or environmental user account I would say is so that when you come to publish your application to production, your developers do not need access to the production user account information and instead can just work with Local / System test / UAT credentials instead.
And of course they are not stored in plain text in your source control checkin then either, which if you host in a private distributed network like GIT could mean that this could be compromised and a hacker would gain access to the credentials.
I think it depends on how accessible / secure your source code or compiled code is. Developers usually have copies of the code on their dev boxes, which are usually not nearly as secure as production servers, and so are much more easily hacked. Generally, a test user / pw is configured on the dev box, and in production, the "real" pw is stored in much more secure config files. Yes, if someone hacked into the server they could easily get the credentials, but that is much more difficult than getting into a dev box in most cases. But like I said it depends. If there is only one dev, and they have a super secure machine they work with, and the repo for their code is also super secure, then there is no effective difference.
What I do is to ask the credentials to end user initially and then encrypt and store them in a file. This way, I don't know their connection details and passwords as a dev. The key is a hashed binary and I store it by poking ekstra bytes in between. One who wants to crack it should find out the algorithm used, key and vector lengths, their location and the start-end positions of the byte sequence keeping the values. A genius, who would also reverse engineer my code to get all this information would break into it (but it might be easier to directly crack the end user's credentials).

Securing SQL queries, insuring that no one person knows that password

What are some effective and secure methods of securing SQL queries?
In short I would like to insure that programmers do not see the passwords used by the application to perform queries. Something like RSA or PGP comes to mind, but don't know how one can implement a changing password without being encoded in the application somewhere.
Our environment is a typical Linux/MySQL.
This might be more of a process issue and less of a coding issue.
You need to strictly separate the implementation process and the roll-out process during software development. The configuration files containing the passwords must be filled with the real passwords during roll-out, not before. The programmers can work with the password for the developing environment and the roll-out team changes those passwords once the application is complete. That way the real passwords are never disclosed to the people coding the application.
If you cannot ensure that programmers do not get access to the live system, you need to encrypt the configuration files. The best way to do this depends on the programming language. I am currently working on a Java application that encrypts the .properties files with the appropriate functions from the ESAPI project and I can recommend that. If you are using other languages, you have to find equivalent mechanisms.
Any time you want to change passwords, an administrator generates a new file and encrypts it, before copying the file to the server.
In case you want maximum security and do not want to store the key to decrypt the configuration on your system, an administrator can supply it whenever the system reboots. But this might take things too far, depending on your needs.
If programmers don't have access to the configuration files that contain the login credentials and can't get to them through the debug or JMX interfaces then that should work. Of course that introduces other problems but that would potentially satisfy your requirement. (I am not a Qualified Security Assessor - so check with yours to be sure for PCI compliance.)

Options for Securing Connection Strings

Just a general architecture question.
I know that for web sites, one can use the features built in to IIS to encrypt the connection string section. However, what I am not certain of is this... If I do this and then copy the web.config to another project, will the new project still be able to decrypt the connection strings section in the config file?
Where this becomes an issue is production database access. We don't want anyone to be able to copy the config file from production into their project and have carte blanche access to the production database.
Currently the way my company does it is to store the encrypted connection string in the registry of the server, then use a home-grown tool to read the registry and decrypt the value on the fly. This prevents someone from just looking into the registry or web config to see the connection string.
Further, for thick client (WinForms, WPF, etc.) applications, this could be a little more problematic because once again, I am unsure if the IIS encryption trick will work since the applications would not be running on IIS. We currently have a kludgy solution for this which involved the same home-grown application, but reading the encrypted string from a binary file and decrypting on the fly.
It just seems very patched together, and we are looking for a better way to do it (i.e., industry standard, current technology, etc.)
So, a more general question is this...
What approaches have you used for securing your connection strings? Especially when it comes to multiple application types accessing it, encryption, etc.
A quick Google search will show you other people's attempts at encrypting some or all of an application configuration file (i.e. Google "ecnrypting application configuration files").
But more often than not, I find that the better answer is properly securing the resource that you are concerned about (usually a database). Windows authentication is always preferred of SQL authentication, that way passwords do not need to be stored in the config file, though this may not always be an option. If you want to prevent access to a resource (especially if it's usually accessed through any sort of web layer, like a web service or a website itself), then host the resource on a different server (which is preferred anyways) and don't allow access to it from outside your internal network. If the attacker has access to your internal network, then there's usually bigger concerns than this one resource you are trying to protect.
If you are concerned about a malicious person performing an action that even your application can't perform (like dropping a database), then ensure that the credentials the application is using doesn't have that type of permission either. This obviously doesn't prevent an attack, but it can reduce the amount of damage that is done from it.
Securing information stored in a configuration file that is located on the user's machine is generally not worth the time, IMHO. At the end of the day, the machine itself will need to be able to decrypt the information, and if the machine has the means to do it, then so does the user. You can make it hard for the user to do it, but it's usually still doable.
This isn't really a direct answer to your question, but I hope it gets you thinking down a different path that may lead to an acceptable solution.
From my understanding the protection of encrypted connection strings as for example presented in the article Importing and Exporting Protected Configuration RSA Key Containers protected the connection string on a user-level.
This means that only the account running IIS (NT AUTHORITY\NETWORK SERVICE) can access the cryptographic keys for decrypting the connection string. Therefore this protected only against users who are able to log-on onto the server holding the web.config file. But it can be extended to limit access to certain application.
Regarding the fat client there may be a way to narrow down the interface a bit:
Define all SQL commands as stored procedures on the server and change the settings for the used user account to only allow executing those stored procedures. This would limit access to the database to operations that can be performed using the SQL login credentials.
I would use the SQL DB account management features, with specific permissions only (e.g. at it's most abstract - allow the execution of read only SQL commands) and only from allowed hosts and/or realms.

Resources