Implementing License Validation with RSA - c#

I am about to sell a program I have written in C# and I want to control licenses for it, strictly. That means I want to let the client connect to my server every single time it starts. This also gives me the ability to disable keys (in case of chargebacks on paypal or distribution of the code). Of course this might be a hassle for other users, but it is necessary in this case.
Since I was unable to find any good .NET Licensing systems that are uncracked, I wanted to take the approach of writing a little one myself.
My plan was to do the following:
Generate a key.dat containing 1024 characters that gets shipped with the software (individual to each user)
In the application entrypoint add a httprequest to my server that sends the key.dat + current timestamp, encrypted.
My HTTP server (running PHP) decrypts the request and checks if the key is valid (in my database) and replies with the "access level" (license type). If the key is invalid or disabled it replies with an errorcode. Just like with the request, the reply is being salted with a timestamp, so someone can't validate his program by sending a valid packet to himself. The timestamp is being checked in the client. The reply is encrypted with RSA and a previously generated public key.
Client receives response, decrypts with private key and reacts.
Is RSA the correct approach for this, so I can assure that the packets are sent by me and are not crafted (by noone else having the public key)?
Is there a better approach for solving this problem?

Someone who wants your software bad enough will just decompile it and remove the part of the code that phones home on startup.
If you were to add a checksum to the app that checks whether the code has been altered, someone can just change the checksum the program checks against (or remove the check entirely).
People who want your application enough will find ways around any type of protection you can conceive. You're better off sticking to something simple, having a product that is worth paying for (and easily) and make sure it's worth the price you're asking.
EDIT
Given that protection is important, the fact that the users will have code running on their machines is a risk you can avoid. If the users don't have the code, they can't crack it. They can't copy it and share it.
Now, it might not apply to the application you intend to write, but you should consider writing a web, Flash or Silverlight application instead of a regular client application. That way you don't have to distribute the code to customers. All you have to do is manage credentials into the application, which should be a lot easier than your round-about RSA system.
It's also easier to push out new versions of the software in a centralized model, and you won't have to worry about theft at all. Of course, load will become an issue when it wasn't before. And not all applications can be centralized easily (or at all). I'm just proposing this to make sure you consider it because it is a valid solution to your problem.
A web-based application will have the same issues as your application (i.e. it will be down whenever the user is offline, whenever the network is down, whenever your server is down, etc). So there's no added risk in that regard.

Is RSA the correct approach for this?
I do not think RSA is your best choice.
One of the capabilities of PKE (Public Key Encryption) is that it lets parties talk to each other who previously have never exchanged information before (eg. strangers).
I do not see this applying to your case. Your software knows your server well. They are not "strangers".
Consider instead Shared Secret Key encryption, where each copy of the software you distribute is given a unique secret key, and your server knows each user's secret key as well. The keys are never sent, and must be protected, but can still be used to encrypt, sign, and validate communications.
Edit After considering the comments and other answers.
Anyone who wants your software badly enough will be able to bypass the authentication completely. RSA does nothing to prevent that.
The real question is: Does breaking a single license make all licenses vulnerable/worthless. In both cases, (RSA and Secret Key), the answer is No. Just because one copy of the software got hacked and got its key exposed, or the licenses system bypassed, other copies are no more exposed. PKE and SSE seem equal in that respect to me.
Because Shared Secret Key is easier to implement, and computationally faster to execute, I think it is preferred in this case over RSA/PKE. That is not to say RSA is "wrong". It will accomplish what you are after, to the same degree that SSE will (no more, no less). But I think SSE is the smarter choice.

Related

PasswordVault security when used from Desktop app

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.

A way to make a file decryptable only by specific program?

My situation is as follows:
I have to deploy a series of .NET desktop applications consisting of a file with encrypted data and an executable that will access that data and decrypt some parts of it in runtime.
What I need to achieve is that each data container should only be decryptable by that specific .exe it is provided with.
The first idea was to encrypt the data using, say, the hash value of the .exe file as a symmetric key and during decryption calculate the hash value of the .exe file in runtime and decrypt the parts of the data container with it.
However, the problem with that approach is that the user can easily look into the .NET assembly with ILSpy or any other decompiler and discover the whole encryption algorithm which will enable the user to decrypt all the data containers in my series of applications.
Another solution that comes to my mind is to make a small C native library (that is less easy to decomplile) that will perform some manipulations with the .exe assembly information and generate a key for decryption based on it (let's consider the user lazy enough so that he will not try to intercept the key from the memory).
But ideally I wouldn't like to resort to any languages other than C# because porting the application to other platforms with Mono will require additional effort (P/Invokes and so).
So my question is: is there a way I can encrypt the data so that only a certain application would be able to decrypt it?
Of course I understand that in case of a local application it is impossible to keep the data absolutely secure but I need to make the 'hacking' at least not worth the effort. Are there any reasonable solutions or I will have to stick to one of my ideas I described above?
Thank you in advance!
The simple answer is no.
To encrypt and decrypt data, you need an algorithm and, optionally, a secret or key. If a computer can execute the algorithm, someone else can learn what it is. Ignoring decompilation and disassembly, a user could just look at the instructions executed by the CPU and piece together the algorithm.
This leaves the secret. Unfortunately, if the computer or program can access or derive a secret, so can someone with root or administrator rights on that computer for the same reasons above.
However, maybe you are just thinking about the problem the wrong way. If you want the program to access data that no one else can, consider making that data available from a server that users must authenticate to access. Use SSL so data is protected in transit and encrypt the data locally using a key that only the local user and local administrators can access. It is not perfect but it is about the best you are going to get in the general case.
If you need more protection than that, you may want to consider hardware dongles but this gets expensive and complex quite quickly.

C# application which requires access key to activate licence [duplicate]

I'm currently involved in developing a product (developed in C#) that'll be available for downloading and installing for free but in a very limited version. To get access to all the features the user has to pay a license fee and receive a key. That key will then be entered into the application to "unlock" the full version.
As using a license key like that is kind of usual I'm wondering :
How's that usually solved?
How can I generate the key and how can it be validated by the application?
How can I also avoid having a key getting published on the Internet and used by others that haven't paid the license (a key that basically isn't "theirs").
I guess I should also tie the key to the version of application somehow so it'll be possible to charge for new keys in feature versions.
Anything else I should think about in this scenario?
Caveat: you can't prevent users from pirating, but only make it easier for honest users to do the right thing.
Assuming you don't want to do a special build for each user, then:
Generate yourself a secret key for the product
Take the user's name
Concatentate the users name and the secret key and hash with (for example) SHA1
Unpack the SHA1 hash as an alphanumeric string. This is the individual user's "Product Key"
Within the program, do the same hash, and compare with the product key. If equal, OK.
But, I repeat: this won't prevent piracy
I have recently read that this approach is not cryptographically very sound. But this solution is already weak (as the software itself has to include the secret key somewhere), so I don't think this discovery invalidates the solution as far as it goes.
Just thought I really ought to mention this, though; if you're planning to derive something else from this, beware.
There are many ways to generate license keys, but very few of those ways are truly secure. And it's a pity, because for companies, license keys have almost the same value as real cash.
Ideally, you would want your license keys to have the following properties:
Only your company should be able to generate license keys for your products, even if someone completely reverse engineers your products (which WILL happen, I speak from experience). Obfuscating the algorithm or hiding an encryption key within your software is really out of the question if you are serious about controlling licensing. If your product is successful, someone will make a key generator in a matter of days from release.
A license key should be useable on only one computer (or at least you should be able to control this very tightly)
A license key should be short and easy to type or dictate over the phone. You don't want every customer calling the technical support because they don't understand if the key contains a "l" or a "1". Your support department would thank you for this, and you will have lower costs in this area.
So how do you solve these challenges ?
The answer is simple but technically challenging: digital signatures using public key cryptography. Your license keys should be in fact signed "documents", containing some useful data, signed with your company's private key. The signatures should be part of the license key. The product should validate the license keys with the corresponding public key. This way, even if someone has full access to your product's logic, they cannot generate license keys because they don't have the private key. A license key would look like this: BASE32(CONCAT(DATA, PRIVATE_KEY_ENCRYPTED(HASH(DATA))))
The biggest challenge here is that the classical public key algorithms have large signature sizes. RSA512 has an 1024-bit signature. You don't want your license keys to have hundreds of characters.
One of the most powerful approaches is to use elliptic curve cryptography (with careful implementations to avoid the existing patents). ECC keys are like 6 times shorter than RSA keys, for the same strength. You can further reduce the signature sizes using algorithms like the Schnorr digital signature algorithm (patent expired in 2008 - good :) )
This is achievable by product activation (Windows is a good example). Basically, for a customer with a valid license key, you need to generate some "activation data" which is a signed message embedding the computer's hardware id as the signed data. This is usually done over the internet, but only ONCE: the product sends the license key and the computer hardware id to an activation server, and the activation server sends back the signed message (which can also be made short and easy to dictate over the phone). From that moment on, the product does not check the license key at startup, but the activation data, which needs the computer to be the same in order to validate (otherwise, the DATA would be different and the digital signature would not validate). Note that the activation data checking do not require verification over the Internet: it is sufficient to verify the digital signature of the activation data with the public key already embedded in the product.
Well, just eliminate redundant characters like "1", "l", "0", "o" from your keys. Split the license key string into groups of characters.
Simple answer - No matter what scheme you use it can be cracked.
Don't punish honest customers with a system meant to prevent hackers, as hackers will crack it regardless.
A simple hashed code tied to their email or similar is probably good enough. Hardware based IDs always become an issue when people need to reinstall or update hardware.
Good thread on the issue:
http://discuss.joelonsoftware.com/default.asp?biz.5.82298.34
When generating the key, don't forget to concatenate the version and build number to the string you calculate the hash on. That way there won't be a single key that unlocks all everything you ever released.
After you find some keys or patches floating in astalavista.box.sk you'll know that you succeeded in making something popular enough that somebody bothered to crack. Rejoice!
I'm one of the developers behind the Cryptolens software licensing platform and have been working on licensing systems since the age of 14. In this answer, I have included some tips based on experience acquired over the years.
The best way of solving this is by setting up a license key server that each instance of the application will call in order to verify a license key.
Benefits of a license key server
The advantages with a license key server is that:
you can always update or block a license key with immediate effect.
each license key can be locked to certain number of machines (this helps to prevent users from publishing the license key online for others to use).
Considerations
Although verifying licenses online gives you more control over each instance of the application, internet connection is not always present (especially if you target larger enterprises), so we need another way of performing the license key verification.
The solution is to always sign the license key response from the server using a public-key cryptosystem such as RSA or ECC (possibly better if you plan to run on embedded systems). Your application should only have the public key to verify the license key response.
So in case there's no internet connection, you can use the previous license key response instead. Make sure to store both the date and the machine identifier in the response and check that it's not too old (eg. you allow users to be offline at most 30 days, etc) and that the license key response belongs to the correct device.
Note you should always check the certificate of license key response, even if you are connected to the internet), in order to ensure that it has not been changed since it left the server (this still has to be done even if your API to the license key server uses https)
Protecting secret algorithms
Most .NET applications can be reverse engineered quite easily (there is both a diassembler provided by Microsoft to get the IL code and some commercial products can even retrieve the source code in eg. C#). Of course, you can always obfuscate the code, but it's never 100% secure.
I most cases, the purpose of any software licensing solution is to help honest people being honest (i.e. that honest users who are willing to pay don't forget to pay after a trial expires, etc).
However, you may still have some code that you by no means want to leak out to the public (eg. an algorithm to predict stock prices, etc). In this case, the only way to go is to create an API endpoint that your application will call each time the method should be executed. It requires internet connection but it ensures that your secret code is never executed by the client machine.
Implementation
If you don't want to implement everything yourself, I would recommend to take a look at this tutorial (part of Cryptolens)
Besides what has already been stated....
Any use of .NET applications are inherently breakable because of the intermediate language issues. A simple disassembly of the .NET code will open your product to anyone. They can easily bypass your licensing code at that point.
You can't even use hardware values to create a key anymore. Virtual machines now allow someone to create an image of a 'licensed' machine and run it on any platform they choose.
If it's expensive software there are other solutions. If it's not, just make it difficult enough for the casual hacker. And accept the fact that there will be unlicensed copies out there eventually.
If your product is complicated, the inherent support issues will be create some protection for you.
The C# / .NET engine we use for licence key generation is now maintained as open source:
https://github.com/appsoftware/.NET-Licence-Key-Generator.
It's based on a "Partial Key Verification" system which means only a subset of the key that you use to generate the key has to be compiled into your distributable. You create the keys your self, so the licence implementation is unique to your software.
As stated above, if your code can be decompiled, it's relatively easy to circumvent most licencing systems.
I've used Crypkey in the past. It's one of many available.
You can only protect software up to a point with any licensing scheme.
I don't know how elaborate you want to get
but i believe that .net can access the hard drive serial number.
you could have the program send you that and something eles ( like user name and mac address of the nic)
you compute a code based off that and email them back the key.
they will keep them from switching machines after they have the key.
I strongly believe, that only public key cryptography based licensing system is the right approach here, because you don't have to include essential information required for license generation into your sourcecode.
In the past, I've used Treek's Licensing Library many times, because it fullfills this requirements and offers really good price. It uses the same license protection for end users and itself and noone cracked that until now. You can also find good tips on the website to avoid piracy and cracking.
The only way to do everything you asked for is to require an internet access and verification with a server. The application needs to sign in to the server with the key, and then you need to store the session details, like the IP address. This will prevent the key from being used on several different machines. This is usually not very popular with the users of the application, and unless this is a very expensive and complicated application it's not worth it.
You could just have a license key for the application, and then check client side if the key is good, but it is easy to distribute this key to other users, and with a decompiler new keys can be generated.
I've implemented internet-based one-time activation on my company's software (C# .net) that requires a license key that refers to a license stored in the server's database. The software hits the server with the key and is given license information that is then encrypted locally using an RSA key generated from some variables (a combination of CPUID and other stuff that won't change often) on the client computer and then stores it in the registry.
It requires some server-side coding, but it has worked really well for us and I was able to use the same system when we expanded to browser-based software. It also gives your sales people great info about who, where and when the software is being used. Any licensing system that is only handled locally is fully vulnerable to exploitation, especially with reflection in .NET. But, like everyone else has said, no system is wholly secure.
In my opinion, if you aren't using web-based licensing, there's no real point to protecting the software at all. With the headache that DRM can cause, it's not fair to the users who have actually paid for it to suffer.
You can use a free third party solution to handle this for you such as Quantum-Key.Net It's free and handles payments via paypal through a web sales page it creates for you, key issuing via email and locks key use to a specific computer to prevent piracy.
Your should also take care to obfuscate/encrypt your code or it can easily be reverse engineered using software such as De4dot and .NetReflector. A good free code obfuscator is ConfuserEx wich is fast and simple to use and more effective than expensive alternatives.
You should run your finished software through De4Dot and .NetReflector to reverse-engineer it and see what a cracker would see if they did the same thing and to make sure you have not left any important code exposed or undisguised.
Your software will still be crackable but for the casual cracker it may well be enough to put them off and these simple steps will also prevent your code being extracted and re-used.
https://quantum-key.net
How to use ConfuserEx?
https://github.com/0xd4d/de4dot
https://www.red-gate.com/dynamic/products/dotnet-development/reflector/download
I know this is an old question, but I referenced this when I was re-writing my licensing process for one of my applications.
After reading a lot of opinions out there and relying on past experience with license codes I came up with this process.
public static class LicenseGenerator
{
private static string validChars = "ACEFHJKMNPRSTUVWXYZ234579";
private static Random rnd = new Random(Guid.NewGuid().GetHashCode());
/// <summary>
/// Generate a license code
/// </summary>
/// <param name="length">length of each phrase</param>
/// <param name="number">number of phrases separated by a '-'</param>
/// <returns></returns>
public static string GetNewCode(int length, int number)
{
string license = string.Empty;
for (int numberOfPhrases = 0; numberOfPhrases < number; numberOfPhrases++)
{
license += getPhrase(length);
if (numberOfPhrases < number)
license += "-";
}
return license.TrimEnd('-');
}
/// <summary>
/// generate a phrase
/// </summary>
/// <param name="length">length of phrase</param>
/// <returns></returns>
private static string getPhrase(int length)
{
string phrase = string.Empty;
for (int loop = 0; loop < length; loop++)
{
phrase += validChars[rnd.Next(validChars.Length)];
}
return phrase;
}
}
You really don't want to provide a code that has similar letters; it makes for a mess when the end user goes to enter it in. Letters like 6 and G, B and 8, L, I, and 1. Of course if you do want them, you can always add them back in... The above code will generate a license like xxxx-xxxx-xxxx-xxxx using the characters in "validChars". Calling GetNewCode(4, 4) will return a code like above.
I'm using Azure functions to register then validate the code. When my app registers the code, it generates an encrypted hash with things that are unique to the install, device and/or user. That is provided to the registration function and is stored with the key in the DB in Azure.
The validate regenerates the key and provides it with the license code, IP address (which in my case will not change and if it does then it will need to be updated anyway), and the regenerated hash then the Azure function returns if the application is licensed. I do store a "temporary" key on their server that allows the app to run for a period of time without talking back up.
Of course, my app must be on the net for it to work regardless.
So, the end result is a simple key for the end user to type in and an easy process to manage the license on the backend. I can also invalidate a license if need be.
I solved it by interfacing my program with a discord server, where it checks in a specific chat if the product key entered by the user exists and is still valid. In this way to receive a product key the user would be forced to hack discord and it is very difficult.

Product activation with public key certificate

I need some ideas how to create a activation algorithm. For example i have demo certificate. Providing that the application runs in demo mode. When full version certificate is provided then application runs in full mode.
Is it even possible and how would be a good way creating this system?
One simple was i was thinking would be just have a 2 encrypted strings, now when the decryption is succsessful with the demo public key certificate then the application will run in demo mode and etc..
You could do something like:
Generate public/private key pair
As owner of private key, you can sign those "activation certificates" (called AC from now on)
In your app, with public key, you can check if the sign is correct
As Overbose mentioned -- you can't prevent reverse engineering. In general someone could take functionality and put it in his/hers own app and thus eliminate any possible activation algorithm. So you can only assume (or make) this is hard enough not to be worth the effort (this is the same as for cryptography -- when you make the cost of breaking the message greater then the profit of gaining it you can say it is well secured).
So you could:
Make executable self-verifying (signed by you, self-checking based on hard-coded public key (one thing: you must skip this value when self-checking)).
Do some tricks with pointers (point to the activation function, go to 7th bit and change value of it for something based on value of another pointer; in some weird places change hard-coded values to those based on occurrence of some bits in other places of the code; generally -- make it more difficult to break than by simply changing bits in executable with hex editor)
Try to make some protocol that your server would use to ask questions about the app ("gimme the value of 293 byte of yourself") and check answers.
Use imagination and think of some weird self-checking method nobody used before :)
As mentioned -- none of this is secure from cutting the authentication part off. But nothing is and this could make it harder for crackers.
Background: I've deployed an activation based system built on top of a third-party license system, i.e. server, database, e-commerce integrations. I've also separately written a C# activation system using RSA keys, but never deployed it.
Product Activation commonly means that the software must be activated on a given machine. I assume that's what you mean. If all you want to do is have two strings that mean "demo" and "purchased", then they will be decrypted and distributed within hours (assuming your product is valuable). There is just no point.
So. assuming you want "activation", then when the user purchases your software, the following process needs to happen:
Order-fulfillment software tells Server to generate "Purchase Key" and send to user
User enters "Purchase Key" into software
Software sends Purchase Key and unique Machine ID to server.
Server combines Purchase Key and Machine ID into a string and signs it with its certificate and returns it to user.
Software checks that signature is valid using Servers public key.
Software could check in lots of places: loading the sig in lots of places, checking it in others.
When generating Purchase Keys, the server can store not only what produce was purchased, but what level of product. You can also have "free" products that are time limited, so the user can try the full version of the software for 30 days.
You are using C#, so make sure you obfuscate the binaries, using dotfuscator or equivalent. However, even with that there is nothing you can do against a determined hacker. Your goal, I assume, is to force non-paying users to either be hackers themselves, or to have to risk using a cracked version: kids wont care, corporations might. YMMV.
The code that does the checking needs to be in every assembly that needs protecting, otherwise an attacker can trivially remove protection by replacing the assembly that does the checking. Cut and paste the code if you have to.
Or just buy something.
Another option is to have the server pre-generate "Purchase Keys" and give them to the Order fulfillment service, but then you dont get to link the key to the customers details (at least not until they register). Better to have the ecommerce server hit your server when a purchase has been made, and have your server send it out.
The hard part isn't so much the generation of activation keys as it is the creation of the server, database, and the integration with e-commerce software, and most of all, human issues: do you allow unlimited installs per Purchase Key? Only 1? If only 1 then you have to have customer-support and a way to allow a user to install it on a new machine. That's just one issue. All sorts of fun.
This guy wrote a blog post about a similar idea, explaining what he did with their own commercial software. Also wrote a list of recommendations about the most obvious cracking techniques. Hope it helps.
One simple was i was thinking would be just have a 2 encrypted
strings, now when the decryption is succsessful with the demo public
key certificate then the application will run in demo mode and etc..
Could be a simple solution. But this way you won't prevent someone to reverse engineer your binaries and make the execution jump to the correct line. Everyone has your program, has a complete version of it, so it's only a matter of find how to break this simple mechanism.
Maybe a better solution is encrypt a part of the binaries needed to use the full application version, instead of a simple string. This way to execute the application complete version someone need to decrypt those binaries in order to execute them.
Please take in consideration that even that solution isn't enough. There are other problems with that:
Does all the version of your tool will share the same encryption key? Breaking one of them for breaking all..
Even if you use a different key for each binary application released, does the encrypted binary are identical? Once cracked one, you can reuse the unencrypted binaries for all distributed applications.
How to solve these problems? There's no simple solution. Most of the more important commercial software with even sophisticated protection systems are broken just few hours or days after they have been released.
Product activation is not a problem that asymmetric cryptography can solve. Asymmetric cryptography is about keeping secrets from your adversary. The problem is that you can't keep a secret that is stored on you're adversaries machine, that would be security though obscurity.
The correct way to do product activation. Is to generate a Cryptographic Nonce that is stored in a database on your server. You give this Nonce to the customer when they buy the product, and then they activate it online. This activation process could download new material, which would make it more difficult for the attacker to modify the copy they have to "unlock" new features.
But even with DRM systems that require you to be online while using the product. Like the ones found in new games like "From Dust" are still broken within hours of their release.
One of the benefits of public key encryption is that you can verify the origin of a given piece of data. So if you store the public key in your assembly, then sign a given piece of data (say an authorization code or serial number) your assembly can verifiably determine that you were the one that created that data - and not a hacker. The actual data itself isn't all that important - it can be a simple pass/fail value.
This is actually pretty easy to do with .NET. You can use an x509 certificates or like we use in DeployLX Licensing the RSACryptoServiceProvider.
I would highly recommend buying a commercial product (doesn't really matter which one, though DeployLX is excellent) and not doing this yourself for 2 reasons
Even if you're a great developer, you'll probably get it wrong the first time. And any savings you might have enjoyed by rolling your own will be lost to recovering from that mistake.
You'll spend far more time working on your own system - time that you should spend making your product great.
The second phase in protecting the software is to make sure that it runs the way you created it - and hasn't been modified by a hacker. It really doesn't matter what encryption you use if hackers can check if( licensed ) to if( true ).
You can use AsProtect to solve this problem. This is good staring point.

Securely store a password in program code?

My application makes use of the RijndaelManaged class to encrypt data. As a part of this encryption, I use a SecureString object loaded with a password which get's get converted to a byte array and loaded into the RajindaelManaged object's Key at runtime.
The question I have is the storage of this SecureString. A user entered password can be entered at run-time, and that can be "securely" loaded into a SecureString object, but if no user entered password is given, then I need to default to something.
So ultimately the quesiton comes down to:
If I have to have some known string or byte array to load into a SecureString object each time my application runs, how do I do that? The "encrypted" data ultimately gets decrypted by another application, so even if no user entered password is specified, I still need the data to be encrypted while it goes from one app to another. This means I can't have the default password be random, because the other app wouldn't be able to properly decrypt it.
One possible solution I'm thinking is to create a dll which only spits out a single passphrase, then I use that passphrase and run it through a couple of different hashing/reorganizing functions at runtime before I ultimately feed it into the secureString object. Would this be secure enough?
Edit For clarity*: The encrypted data is being passed via files between machines. Think of it as a Zip file which always has a password, a default one is assumed if nothing is directly entered by the user.
There is no point in symmetrically encrypting with a string that's hard-coded into your executable. It will only give a false sense of security. No amount of hashing fixes this scheme.
See this Pidgin FAQ for the same point in a different context.
I am unclear why you think you need the inter-app communication to be encrypted. If this communication is local to the machine, then I don't see the need for encryption, particularly encryption that isn't user-specific. Is this a DRM scheme?
EDIT: If it's being passed to a different machine, perhaps you can hard-code a public key, and then have the other machine decrypt with the matching private key.
Let me tackle your final question first.
"Would this be secure enough?"
The only one that can answer that is you. Nobody here knows what "secure enough" means in the context of your application.
Are you building an application to keep the diary of teenage girls? Sure, it would be "secure enough".
Are you building an application to encrypt information or authentication for military grade secure systems? Nope, not even close.
You can only rely on one type of security if you intend to store the password in your source code and thus executable, and that is security by obscurity.
If your problem is that you can't, or won't, store the password in the source code, then moving it into a separate dll solves nothing, you've just moved the problem to a different project.
However, I'm wondering about something. You say "I have to default to something". Is that it? You're trying to store a default value for the secure password string in the source code? How about "THISISNOTAPASSWORD"?
Eric Lippert's You Want Salt With That? (original blog post)
Also read his post to Use the right tool for the job where he ends with the following tips:
If you possibly can, simply don’t go there. Encryption is extremely difficult to get right and is frequently the wrong solution in the first place. Use other techniques to solve your security problems.
If the problem is an untrustworthy client then don’t build a security solution which requires trusting the client.
If you can use off-the-shelf parts then do so.
If you cannot use off-the-shelf-parts and do have to use a cryptosystem then don’t use a cryptosystem that you don’t fully understand.
If you have to use a cryptosystem that you don’t fully understand, then at least don’t use it to solve problems it was not designed to solve.
If you have to use a cryptosystem to ski through the trees, then at least don’t allow the presumably hostile client to choose the message which is encrypted. Choose the token yourself. If the token must include information from the client then sanitize it in some way; require it to be only straight ASCII text, insert random whitespace, and so on.
If you have to allow the client to choose the token, then don’t encrypt the token itself. Sign a cryptographically-secure hash of the token. Its much harder for the attacker to choose a token which produces a desired hash.
Don’t use the same key pair for encrypting outgoing messages as you do for protecting incoming messages. Get a key pair for each logically different operation you're going to perform.
Encrypt the communications both ways.
Consider having a revocation mechanism, so that once you know that Eve is attacking you, you can at least revoke her license. (Or you can revoke a known-to-be compromised license, and so on.)
This article on securing SQL connection strings should be just as applicable for storing encrypted passwords, where you let the OS handle the encryption of the salting seed for your decryption.
It sounds to me like perhaps you should be using a PKI solution instead of encryption/decryption. If you have another application that needs to consume the encrypted data, then you could have a key pair for that application, and give the public key to the app that is doing the encryption. That way you are still keeping your data secure, but not introducing a bunch of additional code that ultimately doesn't give all that much protection.
A quick google search gave me this Code Project article that talks about using the Windows Certificate Store in .Net

Categories

Resources