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!

23 Mar

.NET, ScyllaHide and HEAP_CREATE_ENABLE_EXECUTE

While doing some research on ILProtector, I loaded my test executable in Olly. To much of my surprise, it refused to run and all I could see in Olly log, was this:

Something smells fishy! ;)

I disabled all non-standard plugins, and I was still getting the exception. It was only after I removed the remaining 2 plugins (ScyllaHide and ODBGScript) that my test application launched. Few more restarts and I was sure that ScyllaHide is the one causing the trouble.

OK, I’ve found a bug in ScyllaHide. But where is it? Which option is causing it? And how can I fix it?

Unfortunately, there is no easy way. Just go through one option after another, until you trigger the bug. 10 minutes and 100 rude words later I was sure that “HeapFlags” is the culprit.

A side note from Captain Obvious

If you’re seeing access violation in Olly and want to know where it’s happening, make sure you uncheck Ignore Memory access violation in Debugging Options:
olly debugging options
and then run your target:
crash on jit stub
Here we can see that there is a real code at this address – small stub calling mscorwks.dll and that the call comes from ILProtector’s protect32.dll.

It immediately gives you plenty of useful information about what’s happening. Unfortunately I debugged one instance of Olly from another instance of Olly – got the same results but it took me much longer.

Meet HEAP_CREATE_ENABLE_EXECUTE

It turns out that .NET Runtime Execution Engine (mscoreei.dll) loves to put executable code on heap:

but ScyllaHide prefers to mark all heaps as non-executable:

and these 2 options kinda conflict with each other. :)

Workaround & fix

This small bug can be used to detect ScyllaHide, as it’s enabled by default in all configurations, and tooltip explicitly suggests to leave it as-is:

Very important option, a lot of protectors check for this value.

Here is a suggested patch:

If you don’t want to recompile the entire Scylla, here’s the binary patch for the official ScyllaHideOlly1.dll from ScyllaHide_v1.3fix_Olly1.rar package:

As a simple workaround, you could uncheck “HeapFlags” in ScyllaHide when debugging .NET applications. However, I would really suggest to fix ScyllaHide instead.

Have fun and keep it safe!

16 Mar

Fighting comment spam

When I started this blog, I was aware that comment spam exists. What I didn’t know, is how common it really is. :)

Current statistics are:

Comment type Count %
Spam 39 56
Normal 29 41
Trashed 2 3
Total 70 100

What can be done?

WordPress has several anti-spam plugins. Some of the add captchas, some rely on JavaScript and others rely on continually updated blacklists for spammer IPs and/or keywords. I hate captchas, I respect users that use NoScript, and my webhost is running with allow_url_fopen = false which prevents automatic blacklist updates. Crap!

So, I’m left with a very few options, like blocking spammer IP address ranges using .htaccess file and mod_rewrite.

mod_rewrite magic

When you know what you’re doing, mod_rewrite does wonders. When you don’t, you might lock yourself out of web-admin interface. Trust me, it’s not fun! ;)

In the very simplest form, we can block one IP address:

RewriteCond %{REMOTE_ADDR} ^(123\.456\.789\.666)$
RewriteRule (.*) - [F,L]

First line is a condition – if visitor comes from IP address 123.456.789.666, then apply the rule. Keep in mind that mod_rewrite is matching IP address against regexp, so do not forget backslashes! Otherwise you might accidentally block more than you wanted..

Second line is the rule – whatever URL it tries to access, send response “403 Forbidden”. (.*) is a regexp matching anything1. [F] forbids access and [L] stops any other rules from applying, making it the last rule.

It will work, but my webhost does not allow custom 403 pages. So, we can adjust the example a bit:

RewriteCond %{REMOTE_ADDR} ^(123\.456\.789\.666)$
RewriteCond %{REQUEST_URI} !/error.html$
RewriteRule (.*) /error.html [R=302,L]

Now there are 2 conditions, first is matching IP address, 2nd is checking if requested page is not error.html. Note that by default all conditions must match (logical “and”).

Also, [R=302] is used to redirect users with Error 302 Found to error.html instead of sending Error 403 Forbidden.

It’s better, but we need to block several IP blocks. That’s easy too!

RewriteCond %{REMOTE_ADDR} ^123\.456\.789 [OR]
RewriteCond %{REMOTE_ADDR} ^555\.666
RewriteCond %{REQUEST_URI} !/error.html$
RewriteRule (.*) /error.html [R=302,L]

Flags [OR] say we’re checking if IP address begins with 123.456.789 or 555.666. Also, the regexp was changed to check only beginning of IP address, and ignore the rest.

That’s it. Easy, right? :)

Identifying spammer-friendly IP blocks

I just went through my inbox and looked at the “Please moderate” emails:

Author : Adrienne (IP: 104.168.70.107 , 104-168-70-107-host.colocrossing.com)
E-mail : hekhwrjjrab@mail.com
URL : http://Adrienne
Whois : http://whois.domaintools.com/104.168.70.107
Comment:
Hi, my name is Adrienne and I am the sales manager at {Spammer Company}. I was just looking at your When software is good enough | Life In Hex website and see…

So, the offending IP address is 104.168.70.107.

DomainTools tells us it’s owned by ColoCrossing, and how large the IP block is:
IP Location: United States United States Williamsville Proxy R Us.com
ASN: United States AS36352 AS-COLOCROSSING - ColoCrossing (registered Dec 12, 2005)
Resolve Host: 104-168-70-107-host.colocrossing.com
Whois Server: whois.arin.net
IP Address: 104.168.70.107
NetRange: 104.168.0.0 - 104.168.127.255

Going through other notification emails, I identified 2 more spammer-friendly proxy/vps services: AS15003 and Krypt. It covers almost all comment spam, the rest are residental IP addresses in China and Vietnam – most likely part of some botnet and not really worth blacklisting.

Putting it all together

Armed with basic knowledge about mod_rewrite and offending IP addresses, I put it all together:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !/403.html$
RewriteCond %{REQUEST_URI} !/403.png$
RewriteCond %{REQUEST_URI} !/403.css$
RewriteCond %{REQUEST_URI} !/sad.png$
RewriteCond %{REMOTE_ADDR} ^23\.108\.170 [OR]
RewriteCond %{REMOTE_ADDR} ^23\.94 [OR]
RewriteCond %{REMOTE_ADDR} ^104\.168 [OR]
RewriteCond %{REMOTE_ADDR} ^98\.126
RewriteRule (.*) /403.html [R=302,L]
</IfModule>

So, anyone coming from those IP address blocks will get redirected to http://lifeinhex.com/403.html. Problem (hopefully) solved! :)

Further reading

These sites were invaluable in adding simple spam block to my blog:
How to redirect requests from particular IP addresses or networks with mod_rewrite – basic usage.
System: mod_rewrite: Examples – great examples, explained well.
mod_rewrite Cheat Sheet – all I ever wanted to know, and little bit more.
How To Ban And Block Proxy Servers? – I didn’t have to take this approach yet. And it wouldn’t work against “elite” proxies anyway.

Footnotes

1. Actually, the pattern in the RewriteRule does not need to match the _whole_ URL, so you might encounter "$", "(.*)", "." and many more variations in these kinds of rules.

11 Mar

Miserable state of open source code

Yesterday I wanted to make a small API hook detector in C#. It has to parse PE file, find exported functions, read bytes from the beginning of function and then compare them with the bytes in process memory. Sounds simple, right?

Well, good luck finding a PE parser that actually works!

Looking for PE parser

Most of PE parsers stop at parsing DOS header, NT headers and section headers. But I needed something that would also parse export table for me. After a couple of Google searches I ended up with PEReader by DKorablin. From the first look it’s decent and even has a demo application. What else could you want?

Hmmm, how about working correctly on really simple files? ;)

Sorry, nope.

Results from PEReader and CFF
It sure finds exported functions but it mismatches function names & RVAs. So, if you wanted to examine, say, CreateFileW, you will end up examining DeleteFileA. Or some other random API. Great job!

But it’s opensource. Just fix it and submit a patch!

Umm, no. I was looking for a PE parser that I can take, load it in VS and use it. I don’t want to spend days hunting down bugs and fixing them – this stops me from doing what I really want to do.

So, dear opensourcer, if you are publishing your code, make sure it actually works. If it doesn’t work, please don’t publish it at all – it’s not helping anyone. Don’t waste other people’s time..

P.S. I ended up with using DNLib and writing my own PE export parsing. At least, I know it works properly..

10 Mar

Gigaom suspends operations

This day started with some sad news:

Gigaom recently became unable to pay its creditors in full at this time. As a result, the company is working with its creditors that have rights to all of the company’s assets as their collateral. All operations have ceased.

Gigaom is (was?) a very nice technology site. I liked it. And I’ll certainly be sad to see it go. However, this failure proves something I’ve said for years, yet everyone else seemed to disagree:

If your web-based business depends on ad revenue, you’re going to fail.

Sure, some stay at home moms can get few hundreds of bucks per month by blogging about the color of their baby poop. And some other stay at home moms will read this shit blog, looks at the ads, and possibly even click on Pimpers(tm) picture to buy some. Yes, that can work.

But you can’t build a real business based on ad revenue.

Nobody loves ads

Face it – people hate ads. That’s why people install adblockers. It’s not because they hate you, the poor publisher. It’s not because adblocker speeds up web page loading time. And it’s certainly not because people need to save some traffic.

You can remind them nicely:
flightradar

You can nag and deny access to your precious content, like ArsTechnica did in 2010, or lots of sites try to do today:
playindiafilms

But no matter how hard you try, you can’t make a long-term business based on ads.

R.I.P. GigaOm, I hope others will learn from your failure.

05 Mar

Improved static Enigma Virtual Box unpacker

Last few weeks have been really hectic. I moved to a new apartment, so lots of time was spent on packing, unpacking, cleaning, and other non-computer related chores. Finally it’s done, I got a great new place to live and I’m happy. :)

To relax and get back into shape, I spent an evening with one of my old projects – Enigma Virtual Box unpacker. I fixed few little bugs and added support for x64 executables.

EnigmaVB unpacker

Get it here: https://www.mediafire.com/?mie1wida3aicrrt

26 Feb

When software is good enough

Microsoft, Google and Apple make software for everybody. Millions of users run this software every day. It must be stable and user friendly, so that Aunt Judy and Average Farmer Joe can use it. If it crashes, clueless user can’t do much about it – and that’s bad. That’s why these companies spend thousands of hours in testing and improving usablility.

On the other hand, reversers make tools. A specialized software for solving small and nasty problems, like hiding debugger, defeating specific protection or bypassing some authorization check. Tools are made by a reverser for a reverser, so there are completely different expectations for them. Nobody expects that today’s DNGuard unpacker will work with next year’s DNGuard binaries, or that DRM authors won’t change their encryption mechanisms.

That’s why reversers make tools that are just “good enough”.

Olly, Confuser and de4dot

Funny thing happens when reversing tools suddenly become extremely popular. Newbies start using them, ordinary users start using them – and the expectations change. Suddenly the author is overwhelmed with extremely helpful “bug reports” like “cannot unpack latest reactor” or “obfuscation fails for my application”. It’s annoying, wastes reverser’s time and is not helpful in any way. Therefore I totally understand 0xd4d’s reaction:

There’s no support. Don’t email me if you can’t use it or if it fails to deobfuscate a file obfuscated with an updated obfuscator.

Instead, try to update de4dot yourself. It’s a lot easier than you think. If you can’t, search the Internet and you should find a couple of forums where you can ask your question.

TitanHide is good enough

Earlier this month I made few posts about bugs in TitanHide. Are these real bugs? Yes. Is it important to fix them? Not really. Let’s face it – there are literally dozens of ways to detect TitanHide. But until commercial protectors start doing that, nobody cares.

TitanHide works and does its job well – that’s all that matters. :)

The two bugs I mentioned earlier

First bug was a confusion about CONTEXT_DEBUG_REGISTERS flags. You see, CONTEXT_DEBUG_REGISTERS is defined as

which is quite unexpected. :) So, the code

was accidentally removing CONTEXT_i386 flag from ContextFlags. Such call to should fail, I’m pretty sure it did fail in some cases in my VMWare, but in real world it works just fine.

Second bug is in checking if CONTEXT structure is writeable when calling SetThreadContext. Why should it be – SetThreadContext is only reading from it.. So, this pseudo-code lets you defeat TitanHide hardware breakpoint protection with ease:

Again, it’s a small bug, nobody is abusing it yet, so there is no real reason to fix it.

20 Feb

String decryption with de4dot

Introduction

de4dot is a wonderful tool for deobfuscating known and unknown .NET protections. Dealing with known and supported protections is easy – drag&drop executable on de4dot and it will create deobfuscated assembly. Removing unknown protections is a little bit harder and requires supplying correct command-line parameters to de4dot.

In this article I’ll show how de4dot can be used to deobfuscate strings in almost any .NET assembly, some undocumented features of de4dot, and a few bugs in de4dot too. :)

Basics of string encryption/decryption

To show how string encryption works, let’s start with a simple C# program.

Hint – you don’t have to copy-paste all the code, sample files are available in the archive at the bottom of the post.

As you can see, all the strings are in the clear view and it’s obvious that correct password is “secret”. No protection whatsoever.

To slow down reversing efforts, obfuscators offer to encrypt user strings. They locate all strings in assembly, encode them somehow, and replace access to string with call to obfuscator code. To keep the code simple, I’ll just encode all strings using Base64 – however, the same approach would work for almost any string encryption method (xor, Rijndael, or anything else).

New code looks like this:

No more obvious strings! :) Let’s see how we can decrypt them using de4dot..

de4dot and basic string decryption

If you check de4dot help, you’ll see that you need to supply 2 command line options for a string decryption to work. First, you need to choose a string decrypter type using –strtyp option: static, delegate, emulate. Then you need to tell de4dot which is string decrypter method using –strtok option.

Let’s find which method is responsible for string decryption. Good decompiler can show method tokens, for example, SAE shows it as a tooltip, when you hover over the method:SAE method token

So, for our very basic protection we could run de4dot with commandline:

and the result will look like this:
decompiled cleaned file
So far, so good!

Advanced string decryption

But what happens if obfuscator uses more than one string decryptor? Let’s change the code a little bit:

Now there are 3 methods that decrypt strings, and each of them is slightly different. Of course you could run de4dot 3 times, but it’s just a pain-in-the-butt.

de4dot help doesn’t tell you this, but it is possible to to specify more than one string decryption method:

This is a little bit awkward, but works.

But what to do if there are hundreds of methods – specifying each of them by token is time-consuming and command-line might get too long.

de4dot has solution for that too. Hidden in the middle of help file, is this little gem:

–strtok METHOD String decrypter method token or [type::][name][(args,…)]

It turns out that you can tell de4dot the name of obfuscator class/methods responsible for string decryption and it will resolve tokens automatically. :)

So, the following command-lines will work:

  •  
    This tells de4dot that string decryptor is method with full name Demo.Obfuscator::DecryptString.
  •   This tells de4dot to check all methods in class Demo.Obfuscator and pick the ones which look like string decryptors.
  •   This tells de4dot which class to look at and what kind of parameters string decryption method has.
  •   This tells de4dot to look at all classes for a method called DecryptStringA and use that as string decryptor.

If you want to know more about possible options and the combinations, I suggest that you look at de4dot source code, file de4dot.code\ObfuscatedFile.cs, lines 454-511.

You said something about bugs?

Ok, ok, there are few issues here.. It still works 99% of the time, so no complaining!

First bug is in the checking of string decryptor parameters. When I said that –strtok “Demo.Obfuscator::(System.Int32)” will select only methods that take Int32 as a parameter, I lied. :)

Look at the source:

The continue instruction here does nothing, it just goes on to check next parameter. I guess 0xd4d wanted to stop evaluating this method and go to next one, but got it wrong.

Second bug is in selecting string decryptors – you cannot select a method which takes no parameters. Sample code showing this type of protection is in hello-4.cs (see below).

Look again at the source:

If you don’t supply hints about parameters, then methods with 0 parameters will be ignored because of 2nd if. If you do supply hints – then no method with 0 parameters can pass the 3rd if.

Fixing these 2 bugs is left as an exercise to the reader.

Conclusion

In this article explained how to use de4dot to decrypt strings in any .NET assembly, including some lesser known options. Hope this helps you next time you encounter .NET protection that’s not directly supported by de4dot. :)

All sample files and their source code: https://www.mediafire.com/?2kwnf7d7vre4uv8

16 Feb

Why you should not worry about HARES

Last week Wired published an article about HARES – Hardened Anti-Reverse Engineering System. The article is really great example of what happens when some idiot starts to write about things he has no clue about.

I wanted to write a full-length post about that, but Errata Security beat me to it. So, please enjoy this great writeup instead. :) Thank you, guys!

So, can HARES be used in malware?

Wired article states that:

[HARES] could also mean the start of a new era of well-armored criminal or espionage malware that resists any attempt to determine its purpose, figure out who wrote it, or develop protections against it.

First, HARES requires a hypervisor. If the attacker had ability install hypervisor on your system, you were screwed anyway. This also means that 99.999% of today’s malware won’t be able to take advantage of HARES.

Second, modern antimalware solutions do not need to analyze code. They can analyze behavior of the process, monitor network connections, registry changes, file system changes – and that’s enough for a successful detection. HARES doesn’t interfere with that.

You can go to sleep peacefully tonight, the world is still spinning and no magical malware is going to appear overnight.

Further reading

HARES FAQ
PDF: MoRE Shadow Walker: TLB-splitting on Modern x86
Youtube video: Virtualization: MoRE Shadow Walker The Progression of TLB Splitting on x86
PAGEEXEC and TLB Splitting

12 Feb

Rapidshare is closing. And nothing of value was lost.

As reported by Neowin, Rapidshare customers today are greeted with the message:
rapidshare_closing_notice

Which makes me wonder – was anyone still using Rapidshare? Really?

From my experience, their service was really crappy for last 3 years. Files were quickly deleted “due to inactivity” and free download speeds reminded me good old times with 56kbps modem.

Alexa’s Traffic Rank seems to agree:
Rapidshare popularity graph

R.I.P. Rapidshare. All hail Mediafire, MEGA or Oboom.