Encrypting password in compiled C or C++ code - c++

I know how to compile C and C++ Source files using GCC and CC in the terminal, however i would like to know if its safe to include passwords in these files, once compiled.
For example.. i check user input for a certain password e.g 123, but it appears compiled C/C++ programs is possible to be decompiled.
Is there anyway to compile a C/C++ source file, while keeping the source completely hidden..
If not, could anyone provide a small example of encrypting the input, then checking against the password e.g: (SHA1, MD5)

No you can't securely include password in your source file. Strings in executable file are in plain text, anyone with a text editor can easily look at your password.
A not so secure, but would trample some people, is to store the encrypted string instead. So, basically:
enc = "03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4"
bool check() {
pass = getPassFromUser();
encpass = myHashingFunction(pass);
return pass == encpass;
}
this will deter some people, but isn't really much more secure, it is relatively trivial for assembly hacker to replace the 'enc' string in your executable with another sha256-encoded string with a known cleartext value.
Even if you use a separate authentication server, it is not difficult to setup a bogus authentication server and fool your program connect to this bogus authentication server.

Even if you use SHA1 to generate a hash it is not really all that safe if you do it in a normal way (write a function to check a password) any determined or knowledgable hacker given access to the executable will be able to get around it (replace your hash with a known hash or just replace the checkPassword() call with a call that returns true.
The question is who are you trying to protect against? Your little brother, a hacker, international spies, industrial espionage?
Using SHA1 with the hash just contained within in the code (or a config file) will only protect against you little brother? (read casual computer users that can't be bothered to try and hack your program instead of paying the share ware price). In this case using plain text password or a SHA1 hash makes little difference (maybe a couple of percent more people will not bother).
If you want to make your code safe against anything else then you will need to do a lot more. A book on security is a good starting point but the only real way to do this is to take a security class where protection techniques are taught. This is a very specialized field and rolling your own version is likely to be counter productive and give you no real protection (using a hash is only the first step).

It is not recommended to keep any sensitive static data inside code. You can use configuration files for that. There you can store whatever you like.
But if you really want to do that first remember that the code can be easily changed by investigating with a debugger and modifying it. Only programs that user doesn't have access to can be considered safer (web sites for example).
The majority of login passwords (of different sites) are not stored in clear in the database but encrypted with algorithms MD5, SHA1, Blowfish etc.
I'd suggest you use one of these algorithms from OpenSSL library.
What I would do is using some public-key cryptographic algorithm. This will probably take a little longer to be cracked because in my opinion there is nothing 100% sure when talking about software protection.

It's not safe if you store them as plain text, you can just dump the file or use a utility like strings to find text in the executable.
You will have to encode them in some manner.

Here is a code sample that might help you, using OpenSSL.
#include <openssl/evp.h>
bool SHA256Hash(const char* buf, size_t buflen, char* res, size_t reslen)
{
if (reslen >= 32)
{
EVP_MD_CTX mdctx;
EVP_MD_CTX_init(&mdctx);
EVP_DigestInit_ex(&mdctx, EVP_sha256(), NULL);
EVP_DigestUpdate(&mdctx, buf, buflen);
EVP_DigestFinal_ex(&mdctx, res, &len);
EVP_MD_CTX_cleanup(&mdctx);
return (len == 32);
}
return false;
}
I took this sample from the systools library and had to adapt it. So i'm not sure it compiles without modifications. However, it should help you.
Please note that, to determine if storing a hash value of some password in your binary is safe, we must know what you want it for.
If you expect it to forbid some functionalities of your program unless some special password is given, then it is useless: an attacker is likely to remove the whole password-check code instead of trying to guess or reverse the stored password.

Try finding out Hashing Functions and Ciphering Methods for securing your passwords and their storage.

Related

Safely embedding a string in C code (Secure string, Secure char*)

I have a dll (ansi c) that has some string litarals defined.
__declspec(dllexport) char* GetSomeString()
{
return "This is a test string from TestLib.dll";
}
When compiled this string is still visible in "notepad" for example. I'm fairly new to C, so I was wondering, is there a way to safely store string literals?
Should I do it with a resx file (for example), that has some encrypted values, or what would be the best way?
Thanks
EDIT 1:
The scenario is basically the following in pseudo code:
if(hostname)
return hostname
else
return "Literal String"';
It's this "literal string" that I would like to see "secured" in some way..
Don't put your secrets on anyone else's computer if you want them to stay secret.
See my related answer, The #1 Law of Software Licensing
And Eric Lippert's similar answer
First of all, since your executable1 needs to decode that literal in memory, any attacker determined enough will be able to do the same; often it's just as easy as freezing the process after startup (or after it needed to use the string we want), creating a memory dump and use utilities like string over it. There are methods to mitigate the issue (e.g. zeroing the memory used by a sensitive string immediately after using it), but since your code is on a machine where the potential attacker has all the privileges, you can only put roadblocks: in the end your executable is completely in the attacker's hands.
That being said, if your concern is just "not leaving important strings en plein air" you may just run an executable packer/encrypter over your whole dll. This is as easy as adding a post-build step in your solution, the packer will compress/encrypt the whole executable image and build an executable that when launched will decrypt and run it in memory.
This method has the great advantage of not requiring any change to your code: you just run upx over the compiled dll and you get your compressed dll, no XORs or weird literals spread across your code are needed.
Of course, this is quite weak security (basically it will just protect from snooping around in the executable with notepad or a hex editor), but again, storing critical "secrets" in an executable that is going to be distributed is a bad idea in first place.
In the whole answer I "executable" is to be intended in the wide meaning - i.e. also dlls are included.
You probably want to store hardcoded passwords in the library, right? You can XOR the string with some value, and store it, then read it and XOR again. It's the simplest way, but it doesn't protect your string from any kind of disassembling/reverse engineering.

Hide char array from reverse engineer

Looking for the easiest way to hide char* from reverse engineer. Doesn't have to be strong encryption, but something simple. It has to happen in header, and here is my code:
#pragma once
const char * pw = "test";
#define PASS pw;
where PASS is used in the source.
I already tried reverse string and hex to text and vice versa but didn't succeed. Someone please post some easy solution for this.
Edit: This is just an example. The user will not input anything, I only have to hide a char pointer from debugger. What is the best way to do that?
The standard way would be to store only the hash of your string (computed offline and outside the code) in the code and to hash any user input with which you want to compare it during runtime and then compare the hashes instead of the plain passwords
You could store the XOR value of the password, and then XOR the user input to compare. Refer to this answer for the code.
Then the problem becomes someone can run a debugger or dis-assembler to reveal what your program is doing when it checks the password.

Mask passwords in String

I have been wondering quite a bit on String functions such as replace().
My objective is simple. I have a logger, that logs strings into a text file, that contains passwords which needs to be masked before writing it to the log file.
For example:
str = "-field_value=userId=1,-field_value=password=pass123,-field_value=location=London,-field_value=day=Tuesday,-field_value=emailPassword=pass123,-field_value=fbPassword=pass1234";
Which approach would be the best in this case? The string may or may not end with any password "field_value".
I need to mask all the occurring "Passwords" with their exact length, in this string to get the following output:
str = "-field_value=userId=1,-field_value=password=*******,-field_value=location=London,-field_value=day=Tuesday,-field_value=emailPassword=*******,-field_value=fbPassword=********";
Which would be a more suitable option to use? Normal string handling (using substrings/replaceAll/indexOf) or StringBuilder functions?
Also, how effective is using Regular Expressions in this case? I've never used Regex extensively, so I have little idea on using it for this scenario.
I assume this is C#, but this answer is valid for many other languages.
You must not have passwords in clear text. Just now you do. So that is a huge security concern and it doesn't matter if you put "*" instead of the password. It is there in memory and little skill is needed to extract passwords from memory (given attacker has access to the machine).
A standard approach is that you only store password hash and salt. Now the problem would be how do you convert a password into the hash and how do you securely dispose original password. For this purpose you should use SecureString which encrypts the password string in memory and securely removes it from memory when it is no longer needed.
To give a direct answer to your question: you do not use any approach to replace a password character with a star. Any approach in this case is insecure.
I used String.replaceAll(regex, replace) method, to search for password or emailPassword etc and did the masking. Not sure, if that's the most ideal method to do the masking in this case.

Test environment for an Online Judge

I am planning to build an Online Judge on the lines of CodeChef, TechGig, etc. Initially, I will be accepting solutions only in C/C++.
Have thought through a security model for the same, but my concern as of now is how to model the execution and testing part.
Method 1
The method that seems to be more popular is to redirect standard input to the executable and redirect standard output to a file, for example:
./submission.exe < input.txt > output.txt
Then compare the output.txt file with some solution.txt file character by character and report the results.
Method 2
A second approach that I have seen is not to allow the users to write main(). Instead, write a function that accepts some arguments in the form of strings and set a global variable as the output. For example:
//This variable should be set before returning from submissionAlgorithm()
char * output;
void submissionAlgorithm(char * input1, char * input2)
{
//Write your code here.
}
At each step, and for a test case to be executed, the function submissionAlgorithm() is repeatedly called and the output variable is checked for results.
Form an initial analysis I found that Method 2 would not only be secure (I would prevent all read and write access to the filesystem from the submitted code), but also make the execution of test cases faster (maybe?) since the computations of test results would occur in memory.
I would like to know if there is any reason as to why Method 1 would be preferred over Method 2.
P.S: Of course, I would be hosting the online judge engine on a Linux Server.
Don't take this wrong, but you will need to look at security from a much higher perspective. The problem will not be the input and output being written to a file, and that should not affect performance too much either. But you will need to manage submisions that can actually take down your process (in the second case) or the whole system (with calls to the OS to write to disk, acquire too much memory....)
Disclaimer I am by no means a security expert.

C++ Win32 Replace Strings in an Executable

I'm looking for a good way to replace several strings inside a native win32 compiled exe. For example, I have the following in my code:
const char *updateSite = "http://www.place.com"
const char *updateURL = "/software/release/updater.php"
I need to modify these strings with other arbitrary length strings within the exe. I realize I could store this type of configuration elsewhere, but keeping it in the exe meets the portability requirements for my app. I would appreciate any help and/or advice on the best way to do this.
Thanks!
Update: I found some code in the Metasploit project that seems to do this:
MSF:Util:Exe
I would not mess around the the EXE itself, if you really need 1 file, then do the old zip append trick and put your configs in there.
Could look like this:
> BINARY DATA
> ZIP FILE DATA
> 32bit unsigned int which's value is the size of the appended zip file
Pros:
easy to extend / maintain
you don't mess with the exe itself
you can put lots of stuff in there
Contras:
You need to link some compression lib
If you don't want to zip it, then just write some simple uncompressed archive thing your own.
In a PE file is the global relocations table- it is a list of addresses (for example, global variables or constants that must be runtime-stored, like, say, strings) that must be altered by the PE loader. If you knew which entry this particular variable was, you could get it's address and then alter it manually. However, this would be a total bitch and you'd need an in-depth knowledge of your favourite compiler and the PE format. Easier just to use XML or Lua or something else that's totally portable - they were invented for exactly this kind of purpose.
Edit:
Why not just use a const char**? Is there something wrong with this being a normal runtime variable?
IMO the best place to store that strings in a string table resource. It's incorporated into your .EXE file, so the portability will not be compromised.
Use the visual studio editor to alter that values.
Use LoadString WinAPI, or better, CString::LoadString method, in your code, to load the values.
There's also 3-rd party software allowing you to modify the strings in the compiled .EXE, without recompilation.