<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Sharpe Coding</title>
	<atom:link href="http://sharpecoding.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://sharpecoding.com</link>
	<description>All things code</description>
	<lastBuildDate>Wed, 26 Oct 2011 00:57:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Dot Net Deobfuscation &#8211; Generic String Decryption</title>
		<link>http://sharpecoding.com/2011/10/09/dot-net-deobfuscation-generic-string-decryption/</link>
		<comments>http://sharpecoding.com/2011/10/09/dot-net-deobfuscation-generic-string-decryption/#comments</comments>
		<pubDate>Sun, 09 Oct 2011 17:59:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Reverse Engineering]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sharpecoding.com/?p=210</guid>
		<description><![CDATA[Thanks to metadata, the object-oriented paradigm, leverageable framework libraries, and a well-documented assembly structure, Microsoft&#8217;s .Net Framework has gained a following among developers who don&#8217;t need the performance benefits of an unmanaged language like C++. However, for these same reasons, the resulting assembly &#8230; <a href="http://sharpecoding.com/2011/10/09/dot-net-deobfuscation-generic-string-decryption/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Thanks to metadata, the object-oriented paradigm, leverageable framework libraries, and a well-documented assembly structure, <a href="http://www.microsoft.com/net/">Microsoft&#8217;s .Net Framework</a> has gained a following among developers who don&#8217;t need the performance benefits of an unmanaged language like C++. However, for these same reasons, the resulting assembly is also much easier to decompile and reverse engineer. Obfuscation can be used to make an assembly harder to decompile by &#8220;muddying&#8221; the assembly to a human&#8217;s eye. Obfuscation has many parts, one of which is string encryption.</p>
<p>Strings can be crucial information for finding execution paths in an assembly, therefore it is always wise to encrypt them. String encryption comes in many flavors, some closer to &#8220;encoding&#8221; rather than &#8220;encryption&#8221;. Maybe I will do a case study on encryption some day, but for now, let&#8217;s have some fun and delve into removing the string encryption.</p>
<h3>String Encryption in IL</h3>
<p>One of the beauties of  programming is that there are many ways to implement an idea. Likewise, there are many ways of implementing string encryption, and I will focus on a method I found in a recent assembly I was researching. <span id="more-210"></span></p>
<pre class="brush: csharp; title: ; notranslate">
L_0030: ldstr &quot;&lt;Cipher Text&gt;&quot;
L_0035: ldc.i4 &lt;IntCode&gt;
L_003a: call string &lt;Namespace&gt;.&lt;Class&gt;::&lt;Method&gt;(string, int32)
</pre>
<p>Of course I masked the specific parts for obvious reasons. As shown above, a cipher text string is pushed onto the stack followed by a integer code and a call to the decryption method. Important note: the arguments are constant. If they were changing, this sort of attack wouldn&#8217;t be possible, as we won&#8217;t be running the assembly from its entry point. It is also crucial for the decryption method to also not depend on any external variables, as those won&#8217;t be initialized when we use reflection.</p>
<h3>The Attack</h3>
<p>The basic idea behind this patching method is to load the assembly in question, run the decryption method to generate the plain text, repatch the assembly, and thus allow us to search the assembly for strings.</p>
<h3>Using Mono</h3>
<p>After loading the assembly with Mono, and iterating through the modules, types, and methods, we can access the actual instructions via MethodBody.Instructions. Now, we perform a linear search on the method body until we find the three instructions above: ldstr, ldc.i4, and call. Just preform a check on the call instruction to make sure we are calling the decrypt method by checking the namespace or the method name.</p>
<p>Now we need to collect the cipher text and integer code using Instruction.Operand. Now we have the full method name, and our arguments. Time to use reflection.</p>
<pre class="brush: csharp; title: ; notranslate">

Instruction current = instructions[i];
Instruction next = instructions[i + 1];
Instruction last = instructions[i + 2];

if ((current.OpCode == OpCodes.Ldstr) &amp;&amp;
(next.OpCode == OpCodes.Ldc_I4) &amp;&amp;
(last.OpCode == OpCodes.Call))
{
	//Process
	string encrypted = current.Operand as string;
	int key = (int)next.Operand;
}
</pre>
<h3>And Reflection</h3>
<p>Next step is to give the assembly life and Load it using <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx">Assembly.LoadFrom</a>. Now time to execute the assembly.</p>
<pre class="brush: csharp; title: ; notranslate">
object result = decryptMethod.Invoke(null, new object[] { encrypted, key });
string decrypted = result as string;
</pre>
<p>We are using the power of Reflection to execute the decryption method on the assembly using its constant arguments. We have our plain text, and therefore don&#8217;t need the cipher text or integer code any more.</p>
<h3>Patching the Assembly</h3>
<p>Mono is pretty powerful, and can actually replace instructions. The three above instructions are useless and now should be replaced by just a single call to ldstr to push the plain text string on the stack.</p>
<pre class="brush: csharp; title: ; notranslate">
//Now replace instructions
Instruction newInstruction = worker.Create(OpCodes.Ldstr, decrypted);
worker.Replace(current, newInstruction);
worker.Replace(next, worker.Create(OpCodes.Nop));
worker.Replace(last, worker.Create(OpCodes.Nop));
</pre>
<p>Dont forget to call AssemblyFactory.SaveAssembly to save the patched assembly to disk.</p>
<h3>Final Thoughts</h3>
<p>This type of attack is a simple and effective way of removing string encryption from assemblies as long as they use constant arguments to invoke a constant function. One final thing to note &#8211; depending on the target (a lot of viruses and malware is written in .Net as more can get done for less work), it might be best to remove the string encryption on a Virtual Machine to avoid running any of the assembly&#8217;s code.</p>
]]></content:encoded>
			<wfw:commentRss>http://sharpecoding.com/2011/10/09/dot-net-deobfuscation-generic-string-decryption/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Windows Live Writer Plugins – Part 2</title>
		<link>http://sharpecoding.com/2011/10/04/windows-live-writer-plugins-%e2%80%93-part-2/</link>
		<comments>http://sharpecoding.com/2011/10/04/windows-live-writer-plugins-%e2%80%93-part-2/#comments</comments>
		<pubDate>Tue, 04 Oct 2011 22:45:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://sharpecoding.com/?p=202</guid>
		<description><![CDATA[Well, it is time for part 2. In this part I will detail rendering the syntax highlighting to an Image, showing that image just in the Editor view. Generating the HTML In order to generate an image of the code &#8230; <a href="http://sharpecoding.com/2011/10/04/windows-live-writer-plugins-%e2%80%93-part-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Well, it is time for part 2. In this part I will detail rendering the syntax highlighting to an Image, showing that image just in the Editor view.</p>
<h3>Generating the HTML</h3>
<p>In order to generate an image of the code highlighting, I needed to actually generate an HTML page and make the call to the JavaScript library. By looking at the samples on <a href="http://alexgorbatchev.com/SyntaxHighlighter/manual/installation.html">SyntaxHighlighter&#8217;s Installation Page</a>, it is pretty easy to construct a template html page to be embedded in your plugin library as a resource. I wrote a helper class in charge of consuming the resource, linking the JavaScript, linking the CSS, and finally substituting our plugin&#8217;s html.</p>
<h3>Generating the Image</h3>
<p>Generating an image of the rendered HTML is pretty straight forward, thanks to the <a href="http://msdn.microsoft.com/en-us/library/aa738928.aspx">HtmlScreenCapture </a>class. The constructor takes the html as an argument, and the CaptureHtml method takes a timeout as an argument.</p>
<h3>Linking the Image</h3>
<p>One of the hardest parts of this phase was determining how to display a dynamic local image in the Editor window. For this, I turned to WindowsLiveLocal.WriterPlugin.dll, specifically the MapContenSource. First, we need to be able to save the generated image somewhere temporary, and then we need to recall it, telling WLW to render it. I knew there was a built in plugin for Bing&#8217;s Map API, and it makes sense that this type of plugin would need to answer the same questions.</p>
<p>Due to the lack of resources I found, reverse engineering became crucial for the success of this plugin. Back in the MapContentSource (using Reflector or your favorite .Net Decompiler), I came across the solution to the first part: UpdateMapImage. <span id="more-202"></span></p>
<pre class="brush: csharp; title: ; notranslate">
internal static void UpdateMapImage(ISmartContent content, MapSettings settings, Size newSize)
{
	...
	HtmlScreenCapture capture = new HtmlScreenCapture(...);
	Bitmap image = capture.CaptureHtml(0xafc8);
	if (image != null)
	{
		...
		content.Files.AddImage(settings.ImageFileId, image, ImageFormat.Jpeg);
	}
}
</pre>
<p>Notice after generating the Map image, MapContentSource adds the image to a &#8220;Files&#8221; collection with some sort of unique ID. Displaying this map is found in the GenerateHTML Method:</p>
<pre class="brush: csharp; title: ; notranslate">
private string GenerateHtml(ISmartContent content, bool editor, string blogId)
{
    ...
    Uri uri = content.Files.GetUri(settings.ImageFileId);
    if (uri != null)
    {
        caption = string.Format(CultureInfo.InvariantCulture,..., new object[] { HtmlServices.HtmlEncode(uri.ToString()), str3, HtmlServices.HtmlEncode(plainText) });
    }
}
</pre>
<p>As show above, the solution is simply to reference the image again using that same unique ID. The result is a uri that can be used directly as the &#8220;src&#8221; attribute of the image.</p>
<h3>Wrapping this Up</h3>
<p>Using the findings from above, here is the compiled code my plugin uses to generate an image on the fly that is given just to the editor, and not the publisher (remember the two methods from part 1?).</p>
<pre class="brush: csharp; title: ; notranslate">
public override string GenerateEditorHtml(ISmartContent content, IPublishingContext publishingContext)
{
    string html = PreviewHtmlCreator.Create(publishingContext, _language, _code);

    HtmlScreenCapture capture = new HtmlScreenCapture(html, Width) { MaximumHeight = (int)(_lineCount * 16) };//16 lineheight in IE

    Bitmap image = capture.CaptureHtml(1000);
    content.Files.AddImage(ImageFieldId, image, ImageFormat.Bmp);

    Uri uri = content.Files.GetUri(ImageFieldId);
    return String.Format(...image tag..., HtmlServices.HtmlEncode(uri.ToString()), _size.Width, _size.Height);
}
</pre>
<p>And for comparison:</p>
<pre class="brush: csharp; title: ; notranslate">
public override string GeneratePublishHtml(ISmartContent content, IPublishingContext publishingContext)
{
    return String.Format(ContentFormat, _language.ToLower(), _code);
}
</pre>
<h3>In Summary</h3>
<p>We have explored the Windows Live Writer API, and found a way to create a plugin that allows for dynamic image content while maintaining separate html for preview and editor files. Check out the plugin page for more information.</p>
]]></content:encoded>
			<wfw:commentRss>http://sharpecoding.com/2011/10/04/windows-live-writer-plugins-%e2%80%93-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Windows Live Writer Plugins &#8211; Part 1</title>
		<link>http://sharpecoding.com/2011/08/16/windows-live-writer-plugins-part-1/</link>
		<comments>http://sharpecoding.com/2011/08/16/windows-live-writer-plugins-part-1/#comments</comments>
		<pubDate>Tue, 16 Aug 2011 14:50:55 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Reflector]]></category>
		<category><![CDATA[Windows Live Writer]]></category>

		<guid isPermaLink="false">http://sharpecoding.com/?p=178</guid>
		<description><![CDATA[Looking for another way to add content to this site without using a browser and have a few more features, I came across Windows Live Writer. I quickly realized I needed a way of adding Code tags (with Syntax Highlighting), &#8230; <a href="http://sharpecoding.com/2011/08/16/windows-live-writer-plugins-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Looking for another way to add content to this site without using a browser and have a few more features, I came across <a href="http://explore.live.com/windows-live-writer">Windows Live Writer</a>. I quickly realized I needed a way of adding Code tags (with Syntax Highlighting), and being a programmer, went about looking at my options. I figured a Plugin would be the best way of doing this.</p>
<h3>ContentSource</h3>
<p>There are numerous sources on how to do this by deriving your plugin from ContentSource (WindowsLive.Writer.Api.dll) except I quickly realized a problem &#8211; the HTML being displayed in WLW and being published are the same for these sources. This is a problem &#8211; the preview for the code tag won&#8217;t have any Syntax Highlighting as you locally don&#8217;t have the library.</p>
<h3>Enter SmartContentSource</h3>
<p>According to the official <a href="http://msdn.microsoft.com/en-us/library/aa738863.aspx">Documentation</a>:</p>
<blockquote><p>Enable the insertion of HTML content with &#8220;smart&#8221; editing capabilities into a post. These capabilities include atomic selection, two-way editing by using the Sidebar, the ability to be resized, and the ability to have distinct HTML representations for editing and publishing contexts.</p></blockquote>
<p>This is exactly what I was after &#8211; distinct representations. However, web searches revealed no references. As I have written in my plugin&#8217;s page <a title="Live Syntax" href="/application-programming/windows-live-writer-plugins/live-syntax/">Live Syntax</a>, I turned to reverse engineering/decompiling the included assemblies. Using the WindowsLiveLocal.WriterPlugin.MapContentSource plugin as a guide, I looked into solving my biggest problem &#8211; having separate editing and publishing HTML.<span id="more-178"></span></p>
<h3>WindowsLive.Writer.Api.SmartContentSource</h3>
<p>SmartContentSource is an abstract class with the following definition (according to Reflector).</p>
<pre class="brush: csharp; title: ; notranslate">public abstract class SmartContentSource : WriterPlugin
{
    // Methods
    protected SmartContentSource();
    public virtual DialogResult CreateContent(IWin32Window dialogOwner, ISmartContent newContent);
    public virtual DialogResult CreateContentFromLiveClipboard(IWin32Window dialogOwner, XmlDocument lcDocument, ISmartContent newContent);
    public virtual void CreateContentFromUrl(string url, ref string title, ISmartContent newContent);
    public abstract SmartContentEditor CreateEditor(ISmartContentEditorSite editorSite);
    public virtual string GenerateEditorHtml(ISmartContent content, IPublishingContext publishingContext);
    public abstract string GeneratePublishHtml(ISmartContent content, IPublishingContext publishingContext);
    public virtual void OnResizeComplete(ISmartContent content, Size newSize);
    public virtual void OnResizeStart(ISmartContent content, ResizeOptions options);
    public virtual void OnResizing(ISmartContent content, Size newSize);

    // Properties
    public virtual ResizeCapabilities ResizeCapabilities { get; }
}</pre>
<p>As we can see, there exists two seperate methods for generating HTML, exactly what we are looking for. There are also Resize functions to check out (and overriding the related property), and CreateContent which occurs when the button is clicked on the WLW UI. This plugin creates a DialogWindow to get its content.</p>
<h3>Are we done?</h3>
<p>Not quite. At this point, I wanted to have the Plugin render an Image of the highlighted syntax, as it would place a bit nicer with WLW and how it handles SmartContentSources. Now the next step is to render an image of the highlighted syntax in action, and find a way of writing it just to the Editor HTML. All this in part 2.</p>
]]></content:encoded>
			<wfw:commentRss>http://sharpecoding.com/2011/08/16/windows-live-writer-plugins-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Put on a helmet&#8230;</title>
		<link>http://sharpecoding.com/2011/06/01/put-on-a-helmet/</link>
		<comments>http://sharpecoding.com/2011/06/01/put-on-a-helmet/#comments</comments>
		<pubDate>Wed, 01 Jun 2011 15:38:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Construction]]></category>
		<category><![CDATA[Zune 30gb]]></category>

		<guid isPermaLink="false">http://sharpecoding.com/?p=30</guid>
		<description><![CDATA[Under construction. Joomla has been ditched for WordPress and hopefully new content to go along with the CMS change. I should have the site up soon, including links to the Zune 30gb games: Asteroids and GuessTheSong. I have taken a &#8230; <a href="http://sharpecoding.com/2011/06/01/put-on-a-helmet/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Under construction.</p>
<p>Joomla has been ditched for WordPress and hopefully new content to go along with the CMS change.</p>
<p>I should have the site up soon, including links to the Zune 30gb games: Asteroids and GuessTheSong.</p>
<p>I have taken a more open stance on source distribution &#8211; I will be posting source as much as possible to accompany releases.</p>
]]></content:encoded>
			<wfw:commentRss>http://sharpecoding.com/2011/06/01/put-on-a-helmet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

