01 Aug 2016

Breaking B0rken ElGamal KeygenMe, part 2

In part 1 of the tutorial, I explained how badly initialized PRNG causes a serious problems and allows us to find the private key. In this part of tutorial, I'll show how to use another weakness in crackme to find private key without using bruteforce.

Looking deeper in the keygenme

If you analyze serial check in more details, you'll notice part of code that processes blacklisted names and keys:

It looks like we have 2 blacklisted names & corresponding serials. We can quickly patch crackme and verify that these names and serials really work.

But did you also notice that those serials look a lot alike? That's weird.. Let's take a closer look at them:

First part of the serial is exactly the same! Let's go back to ElGamal basics and think a bit.

Revisiting ElGamal signing algorithm

I'm sure you already remember the algorithm from my previous blog post. But here it is again.. smile

To sign a message M, one would:

  • Make a hash of message, H(M). In this crackme, it's SHA1 of the username
  • Generate a random number K where K<P-1
  • Calculate R=G^K (mod P)
  • Calculate S=(H(M)-RX)*K^(-1) (mod P-1)
  • The signature will be the pair C(R,S).

So, in our case, R is always the same. G and P are hardcoded in the crackme. That means.. K is always the same. And that doesn't sound right! smile

Quick look in Wikipedia confirms that it's a really bad idea:

The signer must be careful to choose a different k uniformly at random for each signature and to be certain that k, or even partial information about k, is not leaked. Otherwise, an attacker may be able to deduce the secret key x with reduced difficulty, perhaps enough to allow a practical attack. In particular, if two messages are sent using the same value of k and the same key, then an attacker can compute x directly.[1]

The problem of reusing k and the attack itself is explained in Stinson's "Cryptography Theory And Practice", pages 290-291. Unfortunately, normal person has no chance to understand that "explanation".

Few Google searches later I found 2 writeups from Boston Key Party CTF 2015 which were slightly better:

So, let's try to get something useful out of them.

Reused K and recovering private key

As I said earlier, cryptography is a dark magic - if you don't spend years studying it, you can't understand it. So, I just took the code from those CTF writeups and added few more comments to it. And no, I still don't know why it works. smile

Conclusion

Wise man once said:

Knowledge is of two kinds. We know a subject ourselves, or we know where we can find information upon it.

You don't need to be a crypto wizard to solve crackmes - you just need to know where to find the necessary information. But if you're implementing cryptography in your software, better ask someone who understands those things.

Have fun!

22 Jul 2016

Breaking B0rken ElGamal KeygenMe by SmilingWolf

Some weeks ago I found a nice keygenme on URET forum. The description looked interesting enough:

Yet another company is making wild claims! Your mission: prove that people shouldn't trust companies promoting "revolutionary" crypto algos. Keygen this son of a crypto nightmare and write a DETAILED tutorial!

Rules:
1) The only acceptable solution is a keygen
2) No patching of course

It was not solved for few weeks, so I decided to take a look at it. smile

Crash-course in ElGamal signature scheme

I hate cryptography. It's complex, it's confusing and unless you're prepared to study this field for years, you can't really understand why stuff works this or that way.

So, here's a short version, just enough to solve this keygenme. It's based on the explanation in InfoSec Institute's tutorial.

Key generation

  • Generate a random prime number P with chosen length.
  • Generate two random numbers, G and X, with G<P and X<P.
  • Calculate Y=G^X mod P.
  • Public key consists of 3 numbers: (P, G and Y), Private key is X.

All 3 numbers of public key are hardcoded in keygenme and are 256 bits long. We can find them in disassembly:

Private key X is.. well, private. smile Without it we can't generate correct keys for a name of our choice. So, the challenge would be to recover the private key somehow.

Signing

To sign a message M, one would:

  • Make a hash of message, H(M). In this crackme, it's SHA1 of the username
  • Generate a random number K where K<P-1
  • Calculate R=G^K (mod P)
  • Calculate S=(H(M)-RX)*K^(-1) (mod P-1)
  • The signature will be the pair C(R,S).

Verification

To verify a given pair C(R,S), one would:

  • Compute V1=G^M (mod P)
  • Compute V2=Y^R * R^S (mod P)
  • If V1==V2, the signature is valid

Breaking ElGamal

Strength of ElGamal algorithm lies in the Discrete Logarithm Problem (DLP). What it means is that easy to calculate Y=G^X mod P, but it's bloody hard to find out X, if you know P, G and Y.

In the InfoSec Institute's tutorial the author is using figugegl's DLPTool to solve the problem for 128-bit integers. However, it's not even possible to enter 256-bit integers in that tool. And the rest of the suggested tools can't handle such large integers either.

So, we must find another way to break the keygenme. After all, it's called "B0rken ElGamal", so there must be a weakness somewhere!

Inside the keygenme

The keygenme itself is an application that generates ElGamal keys. It would be logical to assume that SmilingWolf used this same application to generate keys for the keygenme. So, let's examine the application and see how ElGamal is implemented in it.

I'll skip the boring "unpack modified UPX part", as it's been explained dozens of times already.

So, here's the relevant code for key generation:

Looks legit, right? smile Well, not so fast.

Random numbers don't just magically appear out of thin air. They are generated using random number generators. If the generators are flawed, the numbers are not really random. You can read a lot about such attacks on Wikipedia.

So, let's examine random number generator used in this keygenme.

If you search for those constants, you'll see that it's a very standard PRNG which is not great but supposed to be reliable enough. You could bruteforce all 2^32 possibilities but it will take a long time. Another dead end?

Well, not really. Any PRNG must be initialized somehow, see random_seed variable above. So, let's see how SmilingWolf is initializing his PRNG..

Hmm, that's weird. Normally PRNG is initialized using rdtsc instruction or something even less predictable than that. And what exactly is arg_0? It's a handle of the DialogBox - not random at all!

Finally, we've found a reason why this ElGamal implementation is broken! smile

Bruteforcing the private key

Now that we know the weakness, we can write a bruteforcer that will go through all possibilities of random seeds and generate all possible ElGamal keys. Once we generate a key that has the same P, G and Y as in the keygenme, we will also know the correct private key X. But generating all these numbers is a slow process!

Let's look back at the code and see what we can optimize.

1) We don't need to generate all the numbers. It's enough if we find correct P - the rest of numbers will match automatically. So, let's remove the rest of the code.

2) First 32 bits of 256 bit integer will almost certainly not change when searching for nearest prime. Therefore, we could get rid of bigint_find_nearest_prime call which is the slowest piece of code. This means we won't be looking for number FE6D5B4400B30374A403F88CFBA3642435FB269AEC2BE5C8C2F331545EF37AB3, but any number starting with FE6D5B44...

3) Multiplication by 2. Another unnecessary step. Let's just divide P by 2 and look for that number. Instead of looking for FE6D5B44..., we'll look for 7F36ADA2...

4) Copying bigints. Unnecessary.

There's not much left, I'm satisfied.

Now, how to bruteforce random seed? It's a window handle. Window handles are always even. Also, they consist of 2 parts, high word and low word. Low word is the actual handle. It is almost never higher than 0x2000. High word is the "uniquifier" - just a counter. It's usually quite small - on my PC it's never larger than 0x800.

Taking all these assumptions into account, my pseudo-code for bruteforcer would look like this:

I implemented the bruteforcer in MASM32 with 95% of code ripped from keygenme and let it run. In less than 2 hours I had one (of the several possible) seed:

Once we know X, implementing keygen is a child's play. Again, lots of ripped code and small UI around it. Problem solved!

Keygen for download: https://mega.nz/#!JtgVUDwb!xs3SgCDK3t5h3MabOfoNsDFYCj1mpHcI7GbQT-K1_RE

Further reading

InfoSec Institute's tutorial about ElGamal: http://resources.infosecinstitute.com/breaking-software-protection-elgamal-signature-scheme/
Interactive webpage showing how ElGamal works with small numbers: https://asecuritysite.com/encryption/elgamal

Final thoughts

As SmilingWolf told me after solving his keygenme - there is another way how to break this keygenme. There's one more thing broken in this implementation that makes generating keys really easy. smile So, if you're interested, try to figure out what is it and how to abuse it.

05 Nov 2015

Keygen templates in Visual Studio

I'm lazy and I hate doing the same tasks over and over again. Making UI for my crackme solutions is one of such tasks. It always goes like this: open Visual Studio, create new Windows Forms project in C#, drop 2 labels, 2 edit boxes and one button on the form. Set label texts to "Name" and "Serial", set button title to "Generate..", set the project icon, etc., etc..

There must be a better way!

..and it's certainly not the way Blue Indian did his keygen template:

To build this template on your own, open the solution in Visual studio, comment out the calls for uFMOD and implement your own logic, after successful build of keygen, close the Visual studio, open the Form_Main.cs file in any text editor and uncomment those two calls to uFMod, save it. Now double click on the build.bat file to built it finally.
...
-To change the ICON and XM tune, edit the mini.res (resource file) with any resource editor like Restorator or any of your choice.

Open this, delete those, compile that, and what? I'm already confused, sorry.

Introducing Visual Studio project templates

I'm sure you know that when you click "New project" in Visual Studio, you're presented with number of choices, like "Windows Forms Application", "Console Application", "Class Library" and so on. All these are project templates that are installed by default.

They provide all the files that are required for a particular project type, include standard assembly references, and set default project properties and compiler options. Hmm, that's exactly what I needed! smile

This article at MSDN nicely explains that project template is simply a ZIP file that contains all the necessary files and a special .vstemplate file. This .vstemplate file is an XML file containing metadata Visual Studio needs to display the template in the "New Project" dialog.

Let's try to put it all together.

Making simple keygen template

Making a new template is actually very easy. You take an existing Visual Studio project, replace project-specific strings with template parameters and press File->Export Template.

Here is my keygen for Mr. eXoDia's simple crackme:
keygen_template1
Obviously, template should not contain code for specific crackme. Let's change that to something trivial and mark as FIXME:
keygen_template2
Now I need to remove all references to crackme name. I will replace them with template parameter $safeprojectname$ in all files. After this change, project won't compile anymore, so you need to be extra careful when changing stuff!
keygen_template3
Hardcoding year in the (c) string is not a good idea because I want to use this template in year 2016 as well:
keygen_template4
Now I just need to update AssemblyInfo.cs to make sure each project has correct name, (c) and GUIDs:
keygen_template5
Did it work? Let's see... File->Export Template, follow the wizard and...

It works. Kinda. The created template still has quite a few references to Mr eXodia's crackme, I'll need to modify project and solution files manually. Unzip the template, fix the files in text editor and ZIP them back. And now it works!

Few more cosmetic fixes (like using $projectname$ where possible), using $if$ and $targetframeworkversion$ to target all .NET framework versions, better namespace names and we have a template that's actually useful.

Download here: https://www.mediafire.com/?sx1i5ba1uijjkii

It's not particularly pretty but that's pretty much what I've been using for 2+ years now - and hopefully it can inspire you to do something similar with your own code. wink

Further reading

Reason→Code→Example : Creating Visual Studio project templates
Rebuilding template cache
How to: Manually Create Project Templates
How to: Create Multi-Project Templates