How to safely store strings (i.e. password) in a C++ application? - c++

I'm working on a wxWidgets GUI application that allows the user to upload files to an FTP server and a pair of username/password is required to access the FTP server.
As far as I know, STL strings or even char* strings are visible to end user even the program is compiled already, using hex editors or maybe string extractors like Sysinternals String Utility.
So, is there a safe/secure way to store sensitive informations inside a C++ application?
PS. I cannot use .NET for this application.

This is actually independent of the programming language used.
FTP is a protocol that transfers its password in plain text. No amount of obfuscation will change that, and an attacker can easily intercept the password as it is transmitted.
And no amount of obfuscation, no matter the protocol used, will change the fact that your application has to be able to decode that password. Any attacker with access to the application binary can reverse-engineer that decoding, yielding the password.
Once you start looking at secure protocols (like SFTP), you also get the infrastructure for secure authentication (e.g. public/private key) when looking at automated access.
Even then you are placing the responsibility of not making that key file accessable to anyone else on the file system, which - depending on the operating system and overall setup - might not be enough.
But since we're talking about an interactive application, the simplest way is to not make the authentication automatic at all, but to query the user for username and password. After all, he should know, shouldn't he?
Edit: Extending on the excellent comment by Kate Gregory, in case that users share a common "technical" (or anonymous) account accessing your server, files uploaded by your app should not be visible on the server before some kind of filtering was done by you. The common way to do this is having an "upload" directory where files can be uploaded to, but not be downloaded from. If you do not take these precautions, people will use your FTP server as turntable for all kind of illegal file sharing, and you will be the one held legally responsible for that.

I'm not sure if that is possible at all, and if, than not easy. If the password is embedded and your program can read it, everybody with enough knowledge should be able to do.
You can improve security against lowlevel attempts (like hexeditor etc.) by encrypting or obfuscating (eg two passwords which generate the real password by XOR at runtime and only at the moment you need it).
But this is no protection against serious attacks by experienced people, which might decompile you program or debug it (well, there are ways to detect that, but it's like cold-war - mutual arms race of debugging-techniques against runtime-detection of these).
edit: If one knows an good way with an acceptable amount of work to protect the data (in c++ and without gigantic and/or expensive frameworks), please correct me. I would be interested in that information.

While it's true that you cannot defend against someone who decompiles your code and figures out what you're doing, you can obscure the password a little bit so that it isn't in plain text inside the code. You don't need to do a true encryption, just anything where you know the secret. For example, reverse it, rot13 it, or interleave two literal strings such as "pswr" and "asod". Or use individual character variables (that are not initialized all together in the same place) and use numbers to set them (ascii) rather than having 'a' in your code.
In your place, I would feel that snooping the traffic to the FTP server is less work than decompiling your app and reading what the code does with the literal strings. You only need to defeat the person who opens the hex and sees the strings that are easily recognized as an ID and password. A littel obscuring will go a long way in that case.

As the others said, storing a password is never really save but if you insist you can use cryptlib for encryption and decryption.

Just a raw idea for you to consider.
Calculate the md5 or SHA-2 of your password and store it in the executable.
Then do the same for input username/password and compare with stored value.
Simple and straightforward.
http://en.wikipedia.org/wiki/MD5
http://en.wikipedia.org/wiki/SHA-2

Related

Creating c++ application where secret information can be stored

I want to create portable c++ application for myself [CLI] which will store my secret project information.
But i am not sure, how can i store information in my program, as whatever i will update in program when i am using it will be stored in buffer and when i will close it, it will get deleted and same informations will not be available at any place.
I want to store information persistently, what is the best way to do it. [Considering my application will be portable, i.e, i can carry it in my pen drive in any place and i can fetch my information from program].
Option i found was Datbase , but i have certain problem with database :-
1). sqlite => If any one gets my sqlite.db file, he will know all my secret project.
2). mysql/sql or any other database => They are not portable, it needs to be installed in system too and i need to import , export everytime in system wherever i will have to use it.
How such application stores information in crypted format, so that no one can read it easily.
Any help will be great.
Thanks
If you want your data to remain secret then you must encrypt it.
How you persist the data (sqlite, text file, etc.) makes no difference whatsoever.
See also:
encrypt- decrypt with AES using C/C++
This is not REALLY an answer, but it's far too long "discussion about your subject" to fit as a comment, and I'd rather break the rules by writing one "non-answer answer" (especially now that you have already accepted another answer) than write 6 comments.
First of all, if it's written in C++, it won't be truly portable in the sense that you can carry it around and plug it in anywhere you like and just access the ifnormation, because different systems will have different OS and processor architecture. Fine if you restrict being able to "plug in" on Windows and Linux with x86 - you only need to build two copies of your code. But covering more architectures - e.g. being able to plug into a iPad or a MacBook will require two more builds of the software. Soon you'll be looking at quite a lot of code to carry around (never mind that you need the relevant C++ compiler and development environment to built the original copy). Yes, C++ is a portable language, but it doesn't mean that the executable file will "work on anything" directly - it will need to be compiled for that architecture.
One solution here may of course be to use something other than C++ - for example Java, that only needs a Java VM on the target system - it's often available on a customer system already, so less of an issue. But that won't work on for example an ipad.
Another solution is to have your own webserver at home, and just connect to your server from your customer's site. That way, none of the information (except the parts you actually show the customer) ever leaves your house. Make it secure by studying internet/web-site security, and using good passwords [and of course, you could even set it up so that it's only available at certain times when you need it, and not available 24/7]. Of course, if the information is really top-secret (nuclear weapons, criminal activities, etc), you may not want to do that for fear of someone accessing it when you don't want it to be accessed. But it's also less likely to "drop out of your pocket" if it's well protected with logins and passwords.
Encrypting data is not very hard - just download the relevant library, and go from there - crypt++ is one of those libraries.
If you store it in a database, you will need either a database that encrypts on itself, or a very good way to avoid "leaking" the clear-text information (e.g. storing files on /tmp on a linux machine), or worse, you need to decrypt the whole database before you can access it - which means that something could, at least in theory, "slurp" your entire database.
Depending on how secret your projects are, you may also need to consider that entering for example a password will be readable by the computer you are using - unless you bring your own computer as well [and in that case, there are some really good "encrypt my entire disk" software out there that is pretty much ready to use].
Also, if someone says "Can I plug in my memory stick on your computer and run some of my from it", I'm not sure I'd let that person do that.
In other words, your TECHNICAL challenges to write the code itself may not be the hardest nut to crack in your project - although interesting and challenging.

how to deal with passwords securely within your application

I have found a similar question here Saving passwords inside an application but it didn't really answer my concerns.
I am dealing with an application that will receive a password (securely) from the user. Once I receive the password I would need store it in some variable and send it through transactions to other systems (this logic is safe and secure and already implemented).
My worry is that I don't want to be able to see the password in a core dump so I would like to encrypt any password before saving it to any variable.
Questions:
Is encrypting it before saving it to a variable enough? Or am I missing some security loopholes?
Is there a simple header only libraries that can do encryption? Can you guide me to where I can start looking?
Note to answer commenters:
The password will not be stored long term; Only for the lifespan of the transactions.
Unfortunately, the participants of the transactions cannot decrypt the password, therefore I would need to decrypt it before I send it to them.
My main concern right now is to find a way to encrypt and decrypt the password locally - in an easy manner...
I found OpenSSL library and crypto++ but it seams that I would need to link with them, I can't just include and call them (i.e. not header only libraries)...
Thanks,
(Note: I'm sure there are rigorous checklists and official guidelines about how to treat passwords in secure software out there, from people and authorities that actually know something about security. This is not one of those!)
I don't think there is a cryptographically-secure way to have passwords in your process memory, be able to use them, but not give access to it to a user that can run your application under a debugger or inspect your core dumps.
What you can do is obscure the password. Here are some techniques you can use:
Not keep the password as a simple string anywhere in your memory (scatter the characters around, etc.)
Scrub all the variables that the password is stored in after they are used (e.g. if you pass the password to a function, you should set all the characters of that variable to NUL inside the function after you are done with it.
Encrypt the password.
Vary the encryption key at each run of the application (or periodically if it's a long-running app.)
Generate the encryption key procedurally based on some aspect of the system/hardware and not store the encryption key for the password anywhere in your process memory.
Use hardware like the Trusted Platform Module (TPM) if available.
Implementing the above consistently and effectively is quite hard and impacts all of your code that deals with the password. And sometimes you even have to intentionally make your code more obscure and go against all your instincts as a programmer (e.g. not passing the password into functions as a parameter, but using hard-coded addresses inside the function.)
I, once again, have to emphasize that it's probably provably impossible to secure your passwords in software only, when the adversary has complete access to the physical machine.
As for the second part of your question, I don't know of any header-only encryption libraries, but encrypting a password will probably only need a cipher and probably a hash. And all of the best algorithms have public-domain or otherwise free implementations in the wild. You can get one of those and copy/paste into your own application. Don't forget to seriously test it though!

How can I obfuscate a string into a C++ binary?

If I have a C++ code containing strings, that can be password or anything, what's the best way to obfuscate them to make very difficult the reverse engineering?
I've found some tools online, but all are not opensource.
Let's say your application uses a web service "www.example.com" and authenticates with the password, "letmein". Compile the program and examine it with strings, objdump, or whatever:
$ make
$ objdump -j .rodota -s program
a.out: file format elf64-x86-64
Contents of section .rodata:
4005f8 01000200 7777772e 6578616d 706c652e ....www.example.
400608 636f6d00 6c65746d 65696e00 com.letmein.
$ strings program
/lib64/ld-linux-x86-64.so.2
__gmon_start__
...
www.example.com
letmein
This is pretty easy. If you obfuscate it, you still need to put the plain text somewhere in memory before you can use it, so instead the attacker does one of the following:
Intercepts network packets (easy, takes 5 minutes with basic knowledge Wireshark)
Uses a debugger (easy, takes 10 minutes with basic knowledge of GDB)
Reverse engineers your source code (hard, takes hours or days)
Note that the obfuscation tools make it harder only for attackers that are already doing it the hard way. What's the sense in that? All you've done is make it take 15 minutes instead of say, 5 minutes for an attacker to get the password from your executable. Since that's pretty much the best you can do, don't work too hard on it. Just XOR the password with some easy pattern and hope that the attackers are very lazy or stupid.
C-3PO: Master Luke, sir. Pardon me for asking, but what should R2 and I do if we're discovered here?
Luke: Lock the door.
Han Solo: And hope they don't have blasters.
C-3PO: That isn't very reassuring.
(You will probably end up spending more time on this than your attacker will.)
On the other hand: If you are trying to prevent non-root users from accessing the password on a trusted system, you can do that with permissions & setuid binaries.
Footnote: The purpose of obfuscators in general is to hide program code, not data. For example, if your application uses an algorithm that is a trade secret, that is when you would want to use an obfuscator.
You should avoid put passwords as constants inside a binary. It should be configurable (e.g. by a configuration file passed in argument).
If you really need to put some password in a binary, encrypt that password and put the encrypted form as a constant in your executable.But that is not always safe (e.g. won't work against the NSA).
Don't trust any obfuscation techniques, so don't use them.
On Linux and POSIX systems, a common practice is to have built-in default for path of configuration files (and a way to set that configuration file thru program arguments). Then the configuration files use the system permissions to hide sensitive passwords. Since the configuration file has a builtin default (usually under /etc or $HOME) you can start the program without any arguments for the common case.
Notice that many programs are secure, even when their source code is freely available (a good example is ssh).
Read about trusted computing base
How secure does it need to be?
If you just want to hide a password (little sister's diary security) then you could just XOR it with some random data. A determined attacker could reverse engineer the code and discover this, but they could do that however complex your solution

Methods for encrypting an archive in C++

I'm writing a game that will have a lot of information (configuration, some content, etc) inside of some xml documents, as well as resource files. This will make it easier for myself and others to edit the program without having to edit the actual C++ files, and without having to recompile.
However, as the program is starting to grow there is an increase of files in the same directory as the program. So I thought of putting them inside a file archive (since they are mostly text, it goes great with compression).
My question is this: Will it be easier to compress all the files and:
Set a password to it (like a password-protected ZIP), then provide the password when the program needs it
Encrypt the archive with Crypto++ or similar
Modify the file header slightly as a "makeshift" encryption, and fix the file's headers while the file is loaded
I think numbers 1 and 2 are similar, but I couldn't find any information on whether zlib could handle password-protected archives.
Also note that I don't want the files inside the archive to be "extracted" into the folder while the program is using it. It should only be in the system's memory.
I think you misunderstands the possibilities brought up by encryption.
As long as the program is executed on an untrusted host, it's impossible to guarantee anything.
At most, you can make it difficult (encryption, code obfuscation), or extremely difficult (self-modifying code, debug/hooks detection), for someone to reverse engineer the code, but you cannot prevent cracking. And with Internet, it'll be available for all as soon as it's cracked by a single individual.
The same goes, truly, for preventing an individual to tamper with the configuration. Whatever the method (CRC, Hash --> by the way encryption is not meant to prevent tampering) it is still possible to reverse engineer it given sufficient time and means (and motivation).
The only way to guarantee an untampered with configuration would be to store it somewhere YOU control (a server), sign it (Asymmetric) and have the program checks the signature. But it would not, even then, prevent someone from coming with a patch that let's your program run with a user-supplied (unsigned) configuration file...
And you know the worst of it ? People will probably prefer the cracked version because freed from the burden of all those "security" measures it'll run faster...
Note: yes it is illegal, but let's be pragmatic...
Note: regarding motivation, the more clever you are with protecting the program, the more attractive it is to hackers --> it's like a brain teaser to them!
So how do you provide a secured service ?
You need to trust the person who executes the program
You need to trust the person who stores the configuration
It can only be done if you offer a thin client and executes everything on a server you trust... and even then you'll have trouble making sure that no-one finds doors in your server that you didn't thought about.
In your shoes, I'd simply make sure to detect light tampering with the configuration (treat it as hostile and make sure to validate the data before running anything). After all file corruption is equally likely, and if a corrupted configuration file meant a ruined client's machine, there would be hell to pay :)
If I had to choose among your three options, I'd go for Crypto++, as it fits in nicely with C++ iostreams.
But: you are
serializing your data to XML
compressing it
encrypting it
all in memory, and back again. I'd really reconsider this choice. Why not use eg. SQLite to store all your data in a file-based database (SQLite doesn't require any external database process)?
Encryption can be added through various extensions (SEE or SQLCipher). It's safe, quick, and completely transparent.
You don't get compression, but then again, by using SQLite instead of XML, this won't be an issue anyway (or so I think).
Set a password to it (like a password-protected ZIP), then provide the password when the program needs it
Firstly, you can't do this unless you are going to ask a user for the password. If that encryption key is stored in the code, don't bet on a determined reverse engineer from finding it and decrypting the archive.
The one big rule is: you cannot store encryption keys in your software, because if you do, what is the point of using encryption? I can find your key.
Now, onto other points. zlib does not support encryption and as they point out, PKZip is rather broken anyway. I suspect if you were so inclined to find one, you'd probably find a zip/compression library capable of handling encryption. (ZipArchive I believe handles Zip+AES but you need to pay for that).
But I second Daniel's answer that's just displayed on my screen. Why? Encryption/compression isn't going to give you any benefit unless the user presents some form of token (password, smartcard etc) not present in your compiled binary or related files. Similarly, if you're not using up masses of disk space, why compress?

Prevent strings stored in memory from being read by other programs

Some programs like ProcessExplorer are able to read strings in memory (for example, my error message written in the code could be displayed easily, even though it is compiled already).
Imagine if I have a password string "123456" allocated sequentially in memory. What if hackers are able to get hold of the password typed by the user? Is there anyway to prevent strings from being seen so clearly?
Oh yes, also, if I hash the password and sent it from client to server to compare the stored database hash value, won't the hacker be able to store the same hash and replay it to gain access to the user account? Is there anyway to prevent replaying?
Thank You!
I believe you are confusing two things. The strings ProcessExplorer is finding are also able to be found by the "strings" command in Unix. It just dumps all the stored strings in an executable not the current memory.
Unless you compiled a User password into your program, the memory allocated to store the data shouldn't be read by ProcessExplorer.
There are numerous issues that can occur. Your best bet is to ensure that no other code can run within your process space. Since the days of virtual memory, each process gets its own virtual memory space, ideally preventing any other program from accessing and messing with the memory of other programs. There are ways to detect if your program is being debugged.
You also need to ensure that the memory you are using to store the password is never written to disk or paged out. This web site can point you in the right direction. https://www.securecoding.cert.org/confluence/display/seccode/MEM06-C.+Ensure+that+sensitive+data+is+not+written+out+to+disk
[edit]
I wanted to expand upon my previous post by talking about replay prevention.
If you are truly serious about a complete solution you will need to implement two-way authentication using a PKI system. Your client will have a certificate and so will your server. The client's private key will only be able to unlocked with a password the user will enter. This will allow the server to verify the the client is who he says he is. The client will then verify the server is who he says he is the same way as the client.
By using this system you prevent someone from possing as a server and attempting to get you to send it your password.
This is a topic I can't cover too well on this web site. You will need to research Certificate Authorities and PKI.
Your vulnerabilities are then:
1. Peaking into current memory to extract the password
2. Social engineering
Reference: http://en.wikipedia.org/wiki/Public_key_infrastructure
Andrew's answer gives you good hints for protection of in-memory strings. Regarding replaying - you're certainly right that if someone else intercepts the hashed password, they can replay it and compromise security. The way to defeat that is challenge-response authentication: http://en.wikipedia.org/wiki/Challenge-response_authentication
Do not store plain passwords in the memory (you can XOR them at least). And read Introduction Into Windows Anti-Debugging
I don't know how is it usually done, but if it's critical for you, you may extend whatever string class you use to store your string at least primitively encrypted and to overwrite it with zeroes or with random data upon destruction/reassignment.