Thursday, November 1, 2012

F5 not building before running in Visual Studio 2012

I recently started using Visual Studio 2012 but got quite annoyed after I realized that the F5 shortcut was not building the projects in my solution before actually running them. Because of this, I was ending up with inconsistencies between the running application the source code.

Long story short, here's how to fix this.

Open the Options box from Debug > Options and Settings, then from Projects and Solutions > Build and Run, make sure that the dropdown for On Run, when projects are out of date:, the "Always build" value is set:

Thursday, October 25, 2012

Fixing "Not a debug ModuleBuilder." thrown by SetLocalSymInfo

This was the first problem I had when I started playing with CIL and emitting CIL code with C#'s Emit; an InvalidOperationException: Not a debug ModuleBuilder:


The reason this was happening was because of this line:

ModuleBuilder mb = ab.DefineDynamicModule(an.Name, "MainModule");

The DefineDynamicModule has an overload which lets you specify whether symbol information should be emitted, and by default it's false.

By setting this emitSymbolInfo argument to true, it will also emit the pdb file for your assembly.

So I passed in the argument and my problem was solved:
ModuleBuilder mb = ab.DefineDynamicModule(an.Name, "MainModule", true);

Monday, October 15, 2012

Taking a screenshot of an application in C#

Recently I needed a way to take screenshots of applications programmatically in C# and I wrote this small application to accomplish that task for me.

You can find the source here: https://github.com/dreasgrech/Screenshotter.

The only requirement I had was that I supply the pId (process ID) and the application takes a screenshot of that process for me...but the application can be very easily extended to accept a process name or anything that can identify a process.


Sunday, October 14, 2012

Cracking .NET applications - a simple tutorial

For this tutorial, I will be making use of Reflector and a plugin for Reflector called Reflexil, and also Gray.Wolf to partially view unobfuscated C# code.

Patching the CIL with Reflexil

Here is a very trivial example of how a simple application can validate a license key:
static void Main(string[] args)
{
    var invalidKey = "48011147";

    if (LicenseManager.Verify(invalidKey))
    {
        Console.WriteLine("Thank you for buying our product!");
    } 
    else
    {
        Console.WriteLine("Invalid license key; continue evaluation.");
    }
}
static class LicenseManager
{
    private static string validKey = "112358";

    public static bool Verify(string key)
    {
        return key == validKey;
    }
}
From the code, it's fairly easy to see that to bypass the license key validation logic in our application, we simply need to modify the LicenseManager.Verify method to just return true rather than check for the valid license key.

Running the unmodified application yields the following, since the equality check obviously fails:


So now let's start patching the application by first doing some reconnaissance. Fire up Reflector, add our compiled exe file and navigate to the LicenseManager.Verify method:


Now there are couple of ways we can modify the code with Reflexil...but let's start with the harder way, by modifying the CIL code directly.

If you look at the current CIL, we see that we have four operations: ldarg.0, ldsfld, call and ret:


Here's what's going on:
  1. ldarg.0 loads and pushes the actual argument at position 0 (string key) to the stack.
  2. ldsfld loads and pushes the value of the static field validKey ("112358") to the stack.
  3. call invokes the System.String::op_Equality(string, string) method by popping the last two values from the stack, comparing them and then popping the returned boolean value on the stack.
  4. ret pops and returns the value that the op_Equality last pushed on the stack.

Now that we know what's going on, we need to change these instructions to simply return true rather than comparing the strings.

This means that our code should instead do:
  1. ldc.i4.1 to push the constant value of 1 onto the stack.
  2. ret to pop and return that value.

Note that if we didn't know how to actually write a method which just returns true in CIL, we could have simply wrote the method in C#, compiled it and then view it's corresponding CIL with Reflector:


As for why you see a .maxstack in the above examples, you can find a pretty good explanation here. It seems that this is used by analysis tools.

Using Reflexil, we can now remove the existing operations and replace them with our desired code:


Once that's done, we should now save our modified executable:


Running our newly patched compilation now shows:


Which is exactly what we strived for, since the validation logic has now been eliminated!

Opening our patched application in Reflector, we can now see the new code:


Patching by modifying the C# code directly

Using Reflexil, there's an even easier way of patching our code...by actually writing C# code rather than CIL!

Using a modified version of our first application from the previous example, we will now patch the code by writing C# code.

This is our new, slightly more "complex" licensing code:
static void Main(string[] args)
{
    var invalidKey = "48011147";

    if (LicenseManager.Verify(invalidKey) )
    {
        Console.WriteLine("Purchased license: {0}", LicenseManager.LicenseType);
    } 
    else
    {
        Console.WriteLine("Invalid license key; continue evaluation.");
    }
}
static class LicenseManager
{
    private static string validKey = "112358";
    public static string LicenseType { get; set; }

    public static bool Verify(string key)
    {
        if (key == validKey)
        {
            LicenseType = "Enterprise";
            return true;
        }

        return false;
    }
}

Notice how now, for the validation process to properly succeed, we need to set the LicenseKey property to "Enterprise" before returning true from the method.

Now of course, we can do this in CIL again, but this time we'll use a much easier method.

Open up the application with Reflector, but this time, instead of changing the CIL opcodes directly, right click the Reflexil window and choose "Replace all with code...":


This will bring up this window:


From here, we now need to type in the code that will set the LicenseType property to "Enterprise" and then return true from the method. After you input the code and press the Compile button, you should end up with the following:


Looking at the generated CIL code, we see the opcodes from before:
  1. ldstr to load the "Enterprise" string onto the stack.
  2. call which invokes the set_LicenseType method (Properties in C# are just syntactic sugar for fields and their backing get/set methods) by popping the "Enterprise" string and using it as an actual argument.
  3. ldc.i4.1 to push the integer 1 on the stack.
  4. ret for popping and returning our boolean.

Saving and running our patched application, we now get:


What if the assembly is obfuscated!?

Sometimes, when you try to open a .NET assembly with Reflector, you will be slapped in the face with this message:


Or, even worse, when I obfuscated the last example program we wrote with a trial version of babelfor.NET, Reflector crashed when I tried to open our LicenseManager.Verify method:


Note though that Reflexil still shows us the CIL code, so we don't have any problems when we need to work with CIL code directly...although it will be a bit harder to understand the code by looking at the CIL code only.

And also, if you change the language in Reflector to IL, you will prevent it from crashing but of course you still won't be able to view the raw C# code:


But what we want to do for now is to find a way to view unobfuscated C# code, and that's where an application such as Gray.Wolf comes to the rescue!

Opening our application in Gray.Wolf and navigating to the Verify method, we get:


As you can see from the right pane, it couldn't completely deobfuscate all of our code for this example but it's at least giving us a very good hint as to what's going on without studying the CIL code.

From the C# code, we can see that there is an if-statement and although Gray.Wolf couldn't deobfuscate the two operands used in the statement, we can make out what they are from the CIL code because the two values that are pushed on the stack before the op_Equality is called are done using ldarg.0 which loads the first only actual argument in the method and ldsfld which loads a value from a static field and since the only possible static that we have which makes sense to compare to is validKey, we can be pretty certain that it's using that value.

Sunday, September 23, 2012

Immediately-invoking functions with an exclamation point in JavaScript

Recently I had to make use of Twitter buttons and I noticed something particularly interesting in their bootstrap code:
!function(d,s,id){var ... }(document,"script","twitter-wjs");

What's interesting to note here is this incantation:
!function () {

}();

Notice how this looks awfully familiar to how one would normally express an immediately-invoked function:
(function () {

}());

In fact, they are fundamentally doing the same thing, yet the former is a byte shorter.


Note that this technique can be accomplished with the other unary operators as well:
-function(){}();
~function(){}();
+function(){}();

What's happening here is that the unary operators are turning a function declaration [function () {}] to a function expression [!function () {}], which can then be immediately-invoked.

One limitation to using this method is that you can't get back the output of the function, unless you are expecting a truthy/falsy value.

This is because the return value is coerced to a boolean when using the exclamation point and negated (since the function invocation has higher precedence, which is why this technique works), and you can't undo that boolean coercion operation on complex types, strings and numbers.

You can however undo the negation operation if you are expecting a truthy/falsy value by simply double negating the output: var truthy = !!function () { return 1; }();


Webroulette: Take me somewhere random!

So once again, what follows is the result of a weekend-project-during-the-week kind of thing.

Similar to chatroulette.com where you shuffle through random people, I wrote this so that you can shuffle through random websites instead:


You can also specify a single word to be used as a form of bias:


You can see it in action here: http://dreasgrech.com/upload/webroulette/.

Source code

As usual, the source for this project resides on github.

How it's done

In a nutshell, I basically do a Google Custom Search API call with a randomly constructed query and then show the first result from the collection of hits.

The server
On the server, I have a file of ~8.5k commonly used English words, and based on the length query string value, I select a number of these words in a random manner.

Note that I enforce a hard limit on the range for the allowed values of length; currently, the range is [0, 10]. If no length is specified, I default it to 3.

This is the word-list that I'm currently using is at http://dreasgrech.com/upload/webroulette/komuni.txt

If a bias is specified, I use it as the first word in the phrase and once this phrase is built, it's echoed so that it can be read by the client.

Here are some examples of the script in action:

http://dreasgrech.com/upload/webroulette/louie.php
http://dreasgrech.com/upload/webroulette/louie.php?bias=obfuscation
http://dreasgrech.com/upload/webroulette/louie.php?bias=douglasadams&length=6

The client
So what the client does is an Ajax call to this PHP script to get the query and then do an Ajax call to the Google Custom Search API to get a list of hits. Btw, I'm also using a query string which I termed iesux which I use for a unix timestamp, and I had to do this because calls to the same url were being cached by Internet Explorer and so I needed this timestamp to introduce variety to the urls.

What I then show on screen is the first result from the list of google hits from that query.

Why not embed an I'm Feeling Lucky link in the iframe?
Halfway during the project, I realized that this functionality is pretty similar to the I'm Feeling Lucky functionality that Google still offers (for some reason?).

I figured that this way, I would eliminate the need to use the API (which, btw, has a 100 queries a day limit) but instead use an I'm Feeling Lucky url (like http://www.google.com/search?&btnI=745&q=obfuscation) for the source of the iframe.

But after I tried a couple of queries like this, I realized that sometimes, an I'm Feeling Lucky url redirects to an actual Google Search page and since Google prevents their site to be rendered in an <iframe>, I was getting a lot of blank pages in the <iframe>...and that sucks.

What about the 100 query limit?
For the free offering of the Google Custom Search API, Google enforces a 100 queries per day (per project) limit.

To work around this, I created five projects (i.e. 5 API keys) and whenever someone loads the page, I serve one of the five keys at random. If it turns out that that particular key is used up, the client requests another API key.

You can also specify your own API key (make sure your that the the Custom Search API service is turned on) using the key query string, as follows:

http://dreasgrech.com/upload/webroulette/?key=AIzaSyCCv2V9wF1cO1uck19H5uuAodJ-Ml0rBgg

Monday, March 5, 2012

A run-length encoder in JavaScript

Run-length encoding is one of the most trivial forms of data compression methods. It works by combining runs of characters into a value containing the number of times that character is repeated in the run and the actual character itself.

So something like:
UUUXXXXXXXXXXXXXXXXXXXXTTTTTKKKKK
would be encoded to:
3U20X5T5K
In this case, the encoded version of the text has been reduced by ~73%. But note that there may be cases where the encoded text would end up larger than the actual (decoded) plain text; this happens when the text contains many isolated characters rather than runs of characters.

Take for example abcdefghijklmnopqrstuvwxyz (26 characters); if you 'compress' that using a run-length algorithm, you'll end up with 1a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1r1s1t1u1v1w1x1y1z (52 characters) which is a 100% increase from the decoded version.

Source and demo

The source can be found at https://github.com/dreasgrech/runlength-js

And the demo of the encoder is at http://dreasgrech.com/upload/runlength/

Note that as of current, the code does not handle instances where the decoded text contains digits.