Tuesday, February 26, 2013

Preventing Vim from automatically inserting line breaks

I recently had a very frustrating issue with Vim where it was inserting a line break automatically for me whenever a line exceeded the 80 character mark.

After some searching around, I realized that I had textwidth (tw) set to 79 in my _vimrc file. From the documentation:

textwidth.
Maximum width of text that is being inserted. A longer line will be broken after white space to get this width. A zero value disables this.

So as you can see from the documentation, fixing it was very trivial: set tw = 0

Wednesday, December 19, 2012

Auto-Generating EventArgs classes with T4

T4 is a code generator built into Visual Studio. In this post, I will present a T4 template file which I've used to help auto-generate Event Arguments classes in C#.

Normally, event arguments classes always follow the same structure. You typically have a set of public properties in a class which extends EventArgs and a constructor which takes in the same number of formal arguments.

Here's a typical event arguments class:

public class OperationCompletedEventArgs : EventArgs
{
    public bool Result { get; private set; }

    public OperationCompletedEventArgs(bool result)
    {
        Result = result;
    }
}

Given the repetitive nature of how typical event arguments classes are structured, they make a perfect fit for an example of code generation.



The intent of my template file for generating event arguments classes is to be able to define a declaration of what classes I want to be generated and then let the template generate those classes for me.

The declaration part of the template looks something like this:

var collection = new List<EventArgumentsRepresentation>
                 {
                     new EventArgumentsRepresentation("OperationCompleted")
                     {
                         Members = new Dictionary<string, string> { 
                             {"Result", "bool"}
                         }
                     },
                     new EventArgumentsRepresentation("GenericAndPartial")
                         {
                             AccessModifier = "internal",
                             IsPartial = true,
                             GenericTypes = new List<string>() { "T", "TK"},
                             Members = new Dictionary<string, string> { 
                                 {"GenericMember1", "T"},
                                 {"GenericMember2", "TK"}
                             }
                         }
                 };


Given the above structure, the template would then generate the following two classes for me:

public class OperationCompletedEventArgs : EventArgs
{
    public bool Result { get; private set; }

    public OperationCompletedEventArgs(bool result) 
    {
        Result = result;
    }
}

internal partial class GenericAndPartialEventArgs<T, TK> : EventArgs
{
    public T GenericMember1 { get; private set; }
    public TK GenericMember2 { get; private set; }

    public GenericAndPartialEventArgs(T genericMember1, TK genericMember2) 
    {
        GenericMember1 = genericMember1;
        GenericMember2 = genericMember2;
    }
}

The next I would want a new event arguments class, I would just add a new instance of EventArgumentsRepresentation to the list and let the template do the work.



And now, for the entire template file. If you want to use it for your own projects, create a new "Text Template" (.tt file) in Visual Studio and copy the below template into it. Once you then save the template file, the classes will be generated into a .cs file.

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ output extension=".cs" #>

<#
var namespaceName = "EventArgumentsGenerationDemo";
var usings = new List<string> {
    "System",
};

var collection = new List<EventArgumentsRepresentation>
                 {
                     new EventArgumentsRepresentation("OperationCompleted")
                     {
                         Members = new Dictionary<string, string> { 
                             {"Result", "bool"},
                         },
                     },
                     new EventArgumentsRepresentation("GenericAndPartial")
                         {
                             AccessModifier = "internal",
                             IsPartial = true,
                             GenericTypes = new List<string>() { "T", "TK"},
                             Members = new Dictionary<string, string> { 
                                 {"GenericMember1", "T"},
                                 {"GenericMember2", "TK"},
                             },
                         },
                     
                 };
#>
namespace <#=namespaceName#>
{
<#
foreach (var usingDirective in usings) {
#>
    using <#=usingDirective#>;
<#
}
#>

    /*
     * This file is autogenerated.  
     *
     * If you want to edit anything from here, use the EventArgumentsClasses.tt file.
     */

<#
foreach (var eventArgsRepresentation in collection) {
#>
    <#=eventArgsRepresentation.ClassSignature#>
    {
<#
foreach (var member in eventArgsRepresentation.Members) {
#>
        public <#=member.Value#> <#=EventArgumentsRepresentation.ToPascalCase(member.Key)#> { get; private set; }
<#
}
#>

        public <#=eventArgsRepresentation.ClassName#>(<#=eventArgsRepresentation.GetConstructorArguments()#>) 
        {
<#
foreach (var member in eventArgsRepresentation.Members) {
#>
            <#=EventArgumentsRepresentation.ToPascalCase(member.Key)#> = <#=EventArgumentsRepresentation.ToCamelCase(member.Key)#>;
<#
}
#>
        }
    }

<#
}
#>
}

<#+
internal class EventArgumentsRepresentation
{
    public string ClassName { get; private set; }

    public string AccessModifier { get; set; }
    public bool IsPartial { get; set; }
    public List<string> GenericTypes {get; set;}
    public Dictionary<string, string> Members { get; set; }
    public string ClassSignature {
        get {
            return String.Format("{0} {1}class {2}{3} : EventArgs", AccessModifier, IsPartial ? "partial " : "", ClassName, GetGenericTypesSignature());
        }
    }

    public EventArgumentsRepresentation(string name)
    {
        ClassName = String.Format("{0}EventArgs", ToPascalCase(name));
        AccessModifier = "public";
        GenericTypes = new List<string>();
        Members = new Dictionary<string, string>();
    }

    public string GetGenericTypesSignature() {
        if (GenericTypes.Count < 1) {
            return "";
        }

        return String.Format("<{0}>", string.Join(", ", GenericTypes.ToArray()));
    }

    public string GetConstructorArguments() {
        if (Members == null || Members.Count < 1) {
            return "";
        }

        return String.Join(", ", Members.Select(k => String.Format("{0} {1}", k.Value, ToCamelCase(k.Key))).ToArray());
    }

    public static string ToPascalCase(string text) {
        return char.ToUpper(text[0]) + text.Substring(1);
    }

    public static string ToCamelCase(string text) {
        return char.ToLower(text[0]) + text.Substring(1);
    }
}
#>

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; }();