27 May

Static Enigma Virtual Box unpacker, part 2

Here comes a new version. :) This time I added support for unpacking external packages. “External packages” are data files that can be loaded by Enigma Virtual Box and can contain both embedded files and registry entries.

I also made my unpacker 100% Unicode-aware – there should not be any more problems with non-english filenames. But I had to switch to Delphi 2009 compiler to do this, so there might be some unexpected bugs lurking around.

And, of course, lots of internal bugs had to be fixed. My code is not perfect, you know! ;)

EnigmaVB Unpacker v0.30

Download link: https://www.mediafire.com/?tm5j3q93zbe5u71

P.S. Thanks to Manofwar for giving me few example files for development & testing!

25 May

Blogging is hard

When I started this blog, I wanted to try and see what will happen. I thought that I have so many things to say and to write about. I still do. :)

But as I found out soon enough, making a decent-quality blog post takes hours. And I don’t have that much free time. So, I had to choose between making half-assed posts with pretty kittens and lists of “Top-X things you don’t really care about“, or taking my time to write a proper post about something (technical) that I learned recently – at the expense of less frequent updates.

I chose to write less often. Currently I’m managing to make one proper post per week – and I really hope to keep it up that way. Of course, the more feedback I get, the more motivated I’d be to write. So, it’s all in your hands.. ;)

On a related subject, I added a simple captcha to the comment form. Looks like it’s working really well to keep most of the spambots away. But if you encounter any problems with it, please let me know.

19 May

Static linking of Bassmod in Delphi

BASS and BASSMOD are very well known freeware libraries for playing XM, IT, WAV and many more sound file formats. They are widely used in keygens and other apps. However, authors only distribute them in a DLL form, there is no LIB file or any other option for linking them statically.

Last week someone resurrected an old thread at Tuts4You and asked how to convert DLL to LIB and link it statically with Delphi. I gave poster the standard answer but he was still running in all sorts of issues. So, can it be done?

Then answer is – yes. But it’s not easy.

Note – This article is written for good old Delphi 6/7/2007. Since Delphi XE2 the process should be easier as the linker was improved to use COFF OBJ files directly. However, I don’t have those new Delphi versions, so I can’t test the claims.

Steps to be taken

I’ll make a list of all necessary steps first and then I’ll discuss them in details.

  1. Unpack the DLL properly
  2. Convert DLL to LIB
  3. Extract OBJ files from LIB
  4. Convert COFF OBJ files to OMF OBJ files
  5. Make those OMF files usable by Delphi
  6. Write a wrapper unit that works around Delphi limitations

Unpack the DLL properly

First step sounds easy, right? It isn’t.

The LIB provided in Tuts4you thread is badly unpacked. Sure, it can work when compiled with MASM. It can be made work with Delphi, but you’ll need to hex-edit compiled EXE file first. The reason for this is extremely primitive Delphi compiler/linker. You have no control over PE section names or attributes. It relies on specific section names and always makes code section read-only. But the LIB from tuts4you uses one segment for both code and data and it must have read-write-execute characteristics. Ooops.

So, we need to unpack DLL ourselves using all the standard steps. PE packer is a very simple one, so you can easily find OEP, dump the file, load DLL at different imagebase, find the OEP and make a 2nd dump, use 2 dumps to fix the relocations using Relox and finally restore Import Table using Scylla or ImpRec. Nothing new here.

Once you’ve unpacked the DLL, you will have to detect section boundaries and create new PE section table. When you’re at OEP of bass.dll, check the memory map in some process exploring tool. You’ll see the sections and their characteristics nicely:
BASS memory map in PETools

Now use any PE editor to create appropriate PE section headers:
Section headers in CFF
To make Delphi happy, code section should be named _TEXT and data section should be named _DATA. All the sections you don’t need in final OBJ file, should be named “.reloc”, “.edata” or similar – Dll2lib will remove them automatically.

Convert DLL to LIB

Well, this step is easy. Use DLL2LIB (google “DLL.To.Lib.v1.42.Full.Retail-DLL2Lib” or get trial version from official site), leave all the default settings and press “Start convert”.

Dll2lib

Extract OBJ files from LIB

For next few steps you’ll need objconv.exe by Agner Fog. It’s better to download the latest version, as earlier versions didn’t support extracting LIB files.

It’s a simple command objconv.exe -lx bass.lib

Convert COFF OBJ files to OMF OBJ files

That’s also simple. Just run objconv.exe -fomf bass.obj bass-omf.obj

Make those OMF files usable by Delphi

Delphi imposes quite a few limitations to OBJ file format. Some of them are documented, some of them aren’t. So, it’s better to rely on special tools made for this purpose, like omf2d.exe by EliCZ.

I’m sure that objconv.exe can do the same, but I’m too lazy to try to figure the right command line parameters. So, just run omd2f.exe bassmod-omf.obj bassmod-omf-d.obj

Note – omd2d.exe will mess up some decorated names from msvcrt.dll, like “??2@YAPAXI@Z”. That’s not a problem, we’ll fix that in the wrapper unit.

Write a wrapper unit that works around Delphi limitations

This is also tough. And again the problems are caused by the primitive Delphi compiler/linker.

Delphi doesn’t support direct API calls, all API calls will go through the thunk table. When you try to reference any external API from Delphi code, in reality you’ll get address of the thunk code.

For the same reason in Delphi you can’t access exported global variables from another DLL.

Unfortunately BASS/BASSMOD uses both direct API calls and global variables from msvcrt.dll. Little bit of clever hacking is required to work around that – you’ll have to load msvcrt and other DLLs from unit initialization code and use GetProcAddress to get the required addresses.

So, the implementation part of the unit will look like this:

In addition to that we need to call the original DllMain function to make sure that BASS is initialized properly:

As a final touch, in the finalization part of unit we’ll have to call DllMain again to make sure all resources are freed properly.

Putting it all together

I already outlined all the steps needed. Anyone with proper skills should be able to replicate them and make his/her own BASS unit.

For those who are lazy – here is the package with Delphi units+obj files + all the intermediate files + compiled projects from BASS/BASSMOD examples to show that it really works.

Have fun!

Useful links

Unpacking DLLs #1: Tutorial by Mr. eXodia
Unpacking DLLs #2: How to use Relox in few simple steps
Omf2d: https://www.mediafire.com/?hsksyjwnwlaw3zb

13 May

Fixing choppy sound in Chrome within RDP connection

Some things and services are banned from work computers. Like your collection of MP3s. Or p2p-based television. Or access to Pandora. :) But everyone knows that music is a really great motivator! So, I decided to try a small trick – use RDP connection to my home PC and play my MP3s from home PC.

It turns out that playing MP3s in Winamp works great. However, playing Pandora radio or anything else in Chrome produced a very choppy sound and video framerate was around 3fps.. That’s not great at all.

Quick Google search locates this 1.5-years old Chrome bug: Issue 310983: choppy sound playing videos within RDP session (not only Flash, also HTML5). As it happens quite often – it’s reproduced by several people but nobody gives a flying fcuk about actually fixing it. So much for the open-source and quick fixes..

Lucky for me, there was a workaround suggested in the comments – install RDP 8.0 server and client.

Hmm, I haven’t heard anything about RDP versoin 8.0. How is that possible?

Turns out, it comes by default on Windows 8.x but must be manually installed and explicitly enabled on Windows 7. It’s one of those hidden treasures very few people know about!

So, on my home Win7 box I installed updates KB2574819, KB2592687 and restarted. Automatically received Security Update KB2965788 and got another restart. Made the necessary changes in group policy settings, and – you guessed right – yet another restart. Got locked out of my box because suddenly my username was not in “Remote Users” group, and I had to re-add it manually. Logged in and everything works as it should. Pandora sounds great, video is suddenly smooth and watchable and my work productivity goes… UP! :)

Happy happy joy joy!

Further reading

List of new features in RDP v8.0
Technical blog explaining technologies behind RDP v8.0 magic

11 May

Improving Meltdown

More than 2 years ago I released Meltdown. It’s a proof-of-concept tool that showed several security issues in Faronics DeepFreeze products. Faronics are infamous for their attempts to hide the issues, so I was really curious how it will work out.

Bugs in my code

First, a few bugs in my code surfaced. None of them were in the core components dealing with DeepFreeze, I had that part tested thoroughly. But I overlooked issues with UAC, possibility that Windows are not installed on drive C:\, empty passwords and other edge cases.

All in all, it was a good learning experience.

Requests for source code

The very first version of Meltdown came with a full source code and explanation of the vulnerabilities in Faronics products. Once I started fixing bugs, I released only the updated binary. Yet quite a few people kept asking for the updated source.

To be honest, I have no idea why. So far, I haven’t seen a single tool that would be based on my source code, not even a straightforward rip with a changed name and copyrights. Weird..

Bug reports

People reported bugs. Big bugs, small bugs, non-bugs and everything in between.

Most bug reports came from arabic-speaking guys. Some of them even didn’t bother to use Google Translate and wrote in their native language. No, I really don’t speak Arabic, German, French or Indonesian.

Also, most bug reports came without any actionable information whatsoever. Just “It doesn’t work”. Well, that’s not helpful at all! I really want to help you, but you must tell me more than that. In later versions, I added information to main window about detected OS, 32/64bits, detected DF version, etc, etc. And then I can just ask for a screenshot, it contains most of the info I need to replicate the issue.

It was a good learning experience again. I learned how to make my tools more user-proof.

Faronics response

For a year, there was none.

Then in June 2014 they released DeepFreeze Enterprise 8.11 where the issue was fixed. At least the changelog says so:

7936 Resolved a security issue that could result in the user accessing Deep Freeze without authorization.

Yeah, right.. In reality they just added yet-another-layer of xor-encryption and removed useful data from frzstate2k.exe. But the same data are still present in dfserv.exe.

Wow, that’s what I call “resolving a security issue”! :)

In September 2014 they released DeepFreeze Standard 8.10 where the other vulnerability was fixed. However, there was no mention of anything like that in the changelog. From a quick glance, it looks like they finally got their code right and aren’t sending xor-encrypted password from driver to usermode anymore.

What now?

I’m presenting you an updated version of Meltdown.

Meltdown v1.5
It shows that vulnerabilities in Enterprise version are still present, just slightly more obfuscated. But security through obscurity does not work!

The glaring vulnerability in Standard version is fixed, and 8.x Standard versions seem to be safe. Funny, isn’t it – you’d expect a corporate product to provide better security than home-edition, yet this is not the case.. :)

Download link for Meltdown v1.5: http://www.mediafire.com/?0wc0vv1kauhwxbb

29 Apr

How to learn Reverse Engineering

Every other days or two a new guy appears at Tuts4You asking “I want to learn Reverse Engineering, where do I start?”.

Hmmm…

There are lots of suggestions, eg. in this Reddit thread. One of the most common recommendation is to with Lena151’s tutorials. And there’s a good reason for that – these tutorials give a good overview of most common tasks, most common tools and provide “instant gratification”. But do they actually teach you Reverse Engineering? I don’t think so.

Why Lena151’s tutorials are bad

Apparently I’m not the only one who thinks so:

I have been thinking about why this happens. Thinking back to myself, I started learning reverse engineering by reading the Lena151 tutorials. I thought they were awesome until Daeken told me that was an awful approach to learn reverse engineering.

At first I didn’t understand why they were so bad. After all, Lena’s tutorials had taught me how to crack my first software.

And that’s exactly the problem. You managed to crack your first software. Instant gratification! But what did you actually learn? Run some common tools, find the “bad boy jump” and patch it? Wow! You must be so l33t!

In reality, these tutorials have produced entire generation of wanna-be-crackers who can only use ready-made tools, but are actually unable to think for themselves. For every problem they need a video tutorial. For every small obstacle they create a new topic asking for help.

And that’s only half of the problem.

Video tutorials made by beginners are even worse

Albert Einstein once said:

The more I learn, the more I realize how much I don’t know.

Beginners who watched Lena151’s series don’t realize that. They cracked their first program and they consider themselves to be reversers. And what’s even worse, they try to spread their “knowledge” by making an incredible amount of incredibly crappy video “tutorials” to be watched by next generation of wannabes.

I’ve actually watched a 15 minute movie titled “How to unpack CryptoObfuscator”. You know how? You drag-and-drop the file on de4dot. Yes, that simple. Yes, someone made 15 minute movie to teach you that.

So, what’s the alternative?

ReverseWithMe blog suggests to learn:

  1. x86 assembly (electronics and wires in the car analogy)
  2. How operating systems work and how they manage memory (the engine of the car)
  3. The compiling process from C-code to assembly (this is equivalent to knowing how a car-fabric is assembling a car)
  4. The life of a binary (equivalent to everything that happens in the car from the key-switch to the off-switch)

I don’t think this is the correct approach either.

It’s like learning a foreign language by reading a dictionary. Start with an “a”, and once you finish with “z”, you’ll know all the words. Maybe. But you won’t be able to make a proper sentence, let alone speak or understand a native speaker.

To put it into context: I’ve been reversing .NET executables for 10 years now. I’ve written unpackers for pretty much every .NET protection there is. And yet I still don’t know IL assembly “by heart”. Why? Because I don’t need to. What’s the mnemonic for “branch-if-equal”? Is it be, beq or bre? Does it pop one or two arguments from stack? I don’t know. If I’ll ever need that, the answer is one Google search away.

Yes, to be a great reverser, you will need to master most of those items. But you don’t need to know all that at the start of your journey.

Gimme a solution, goddamit!

Well, start with Lena151’s tutorials. Yes, I said they are not good, but that’s the best there is. And if you follow few extra advices, you’ll do just fine:

  • Learn to think for yourself. That’s the most important part. Don’t just blindly follow tutorials, try to understand why it works and how it works.
  • Learn to search. Most questions have already been answered, you just need to find the answer. Make sure Google is your friend!
  • Learn your tools. You don’t need to know every single option and feature of them. Most people use ~10% of all Microsoft Excel features. Power Users use around 20%. It’s the same with RE tools. If you’ve mastered 10% of Olly or IDA features, you’re good to go.
  • And last but not least – have fun! Nothing kills your productivity faster than boredom. If the problem is too hard, let it go, try something else and come back to it later.
24 Apr

Sniffing correct serial in .NET crackmes

Introduction

In this tutorial I’ll show you a generic way how to break most of the crackmes written in VB.NET. It uses the fact that most crackmes made by beginners will calculate correct serial and do a simple comparison “if enteredSerial = correctSerial then”

To break such a crackme, you only need to find this comparison and sniff the correct serial. This is a very common approach in x86 world but in .NET world it’s not that popular yet.

As for my target, I’m using “RDG Simple Crackme .NET v4 2015

GetProcAddress in .NET

In x86 world you can use GetProcAddress function to get address of any API function from any DLL. Can we do something similar in managed environment like .NET? It turns out that we can, but it’s a little bit harder.

So, for example, to get address of Assembly.Load(byte[]) you need to do:

This works well with static classes and static methods. How about non-static methods like RijndaelManaged.CreateDecryptor(byte[], byte[])?

That’s doable as well, like this:

To make this reference almost complete – here’s how to get address of .ctor:

There are a few gotchas, however..

  • In case your target type is located in assembly that’s not NGEN’ed yet, I suggest that you use ngen and install the assembly in cache. That can prevent certain problems later.
  • Addresses of functions are obviously different in .NET 2.0 and 4.0. You must compile for correct framework version and target the correct .NET assembly.
  • Addresses of functions are different for x86 and x64 framework versions, too. Make sure your assembly is compiled correctly.

Sniffing string compare

Suprisingly, string comparison in VisualBasic.NET and other .NET languages is different. It’s caused by Option Compare statement present in Visual Basic language. So, if the crackme is made in VB.NET, you need to examine Operators.CompareString(string,string,bool) function. For crackmes made in other languages, you’ll need to examine string.Equals(string) or some other variation of this method.

So, using the code I mentioned above, I learned that address of Operators.CompareString(string,string,bool) on my PC is 599F1D30. Now I need to sniff data passed to this function.

There are several possible approaches. You can try using VisualStudio & Reflector plugin as SpoonStudio tried, you can try using ILSpy and it’s debugger plugin, or you can inject DLL into crackme process, as suggested by noth!ng – but I prefer to use OllyDbg.

Load crackme in OllyDbg, make sure that all the anti-anti-debug plugins are working, all the exceptions ignored, put a breakpoint on 599F1D30 and hope for the best.

Nope. Operators.CompareString is called literally thousands of times. So, we need to do something smarter.

For example, we can use conditional logging breakpoints in Olly. Those breakpoints are quite slow, but it’s still faster than to write some sort of hooking DLL and inject it into crackme. So, we need to set 2 logging breakpoints – one for each string compared. Here is first one:
crackme_conditional_breakpoint
Place second breakpoint at the next instruction (59CD1D31) and log string at edx+8.

Run the crackme, enter some fake but easily recognizable serial and few minutes later we have the answer:
crackme_logged_results
My entered serial was “1234567890123456789012345678901234567890” and it’s being compared to “C49476D583364356253377056314435396D456F44796C7A55746431564433544″. Hmm, could that be the correct serial for my nickname? ;) Yes, it is!

Final notes

This was quite nice crackme and I only showed the simplest way to beat it. When you start looking into it, you’ll find some nice anti-debug tricks, some nice anti-patching tricks and pretty nicely obfuscated code.

But that’s a matter for another story. Have fun!

16 Apr

About e-governments

Two days ago Google released Chrome 42. It’s the answer to life, the universe and everything. And among other things, it disables all NPAPI plugins by default, finally putting that Java nightmare into it’s grave. Good riddance!

But what about other NPAPI plugins? Like, you know, the ones used for electronic documents, digital signatures and other e-government thingies?

Well, here are 2 ways how government agencies approach the same problem:
e-governments compared

Welcome to the 21st century. If you’re Estonian, that is..

08 Apr

Catch me when you can

Introduction

Exception filters have been part of ECMA-335 specification since the very beginning. I’m guessing, they were added because Visual Basic used them extensively and therefore Visual Basic.NET had to support them as well. They look something like this:

Until now C# supported try/catch but did not have support for filters. That’s going to change in C# 6.0/VS2015.

How does it work

In early versions of VS2015 the syntax was “catch-if”, as you can see in the initial announcement. In the latest VS2015 CTP builds, they changed syntax to “catch-when”, and there’s a good reason for it.

So, how does it work and what does it mean for reversers?

It’s a compiler-level feature

As I mentioned before, .NET Framework has supported exception filters since the very beginning. So, this feature works even in .NET 2.0 – if you decide to target .NET 2.0 Framework in VS2015 project settings. Not that you really want to do that..

It’s very useful for debugging

catch-when is implemented as an IL exception filter. So, when an exception is thrown, exception filters are processed before the stack is unwound. This means that filter method has created an error report that included the current stack trace, it would show the frame in which the exception occurred. Sounds complicated? It isn’t.

Let’s implement exception filtering in the “old” way:

and this is how the stack looks when we get to filter(ex):
stack_trace_old
You can’t see much here. All the context is gone, you must rely on exception stack trace and message. That’s what we’ve always done, right? :)

If we write it in a “new” way, the code looks like this:

and stack trace will give us full context of exception:
stack_trace_new
Much better, isn’t it? You can see which method threw the exception, on which line, you have access to local variables and everything else. Yummy! :)

Decompiler support for exception filters is crappy

They say, a picture is worth thousand words.. In a very simple example, Reflector gets the code structure right, just filter conditions are missing:
catch_when_reflector
ILSpy handles it slightly worse, filters are messed up and unreadable. Filter code is gone, too:
catch_when_ilspy
And the latest JustDecompile just throws an exception:
catch_when_justdecompile

Have fun with it!

Here is a small keygen-me for you to play with: https://www.mediafire.com/?k5b9vy0p9dfgb97

The difficulty is 2/10, you should be able to solve it in 30 minutes or so. The entire protection is designed to show you try-catch-when feature, so avoid patching – you can’t learn anything by nopping-out few instructions. ;)

31 Mar

The malware arms race

Today’s Slashdot features a very nice question:

We’ve been in a malware arms race since the 1990s. Malicious hackers keep building new viruses, worms, and trojan horses, while security vendors keep building better detection and removal algorithms to stop them.

My question: will the balance continue, or is one side likely to take the upper hand over the next decade or two? Which side is going to win?

In the comments you’ll see a lot of libertarian psychobabble about how NSA/CIA/{whatever-3-letter-organization} caused this, how you are going to surrender your fundamental rights to a few corporations who pretend to protect you, how everything sucks and will suck even more in the future.

Well, that IS Slashdot, afterall.

But this comment made my day so much better:
Idiots will lose

Have fun and keep your schlongs safe!