<?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>Ex nihilo nihil fit &#187; C#</title> <atom:link href="http://victorhurdugaci.com/category/microsoft/c-microsoft/feed/" rel="self" type="application/rss+xml" /><link>http://victorhurdugaci.com</link> <description>Victor Hurdugaci&#039;s playground</description> <lastBuildDate>Tue, 29 Nov 2011 07:38:40 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=</generator> <item><title>Default indexer and Reflection glitch</title><link>http://victorhurdugaci.com/default-indexer-and-reflection-glitch/</link> <comments>http://victorhurdugaci.com/default-indexer-and-reflection-glitch/#comments</comments> <pubDate>Fri, 22 Apr 2011 13:28:07 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Code]]></category> <category><![CDATA[Reflection]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=2279</guid> <description><![CDATA[I was writing some C# unit tests that had to use Reflection in order to set properties on objects, when I got into an interesting problem. I will provide a simplified version of the code I wrote, first the version without reflection, then my reflection version that had an issue and, in the end, the [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">I was writing some C# unit tests that had to use Reflection in order to set properties on objects, when I got into an interesting problem. I will provide a simplified version of the code I wrote, first the version without reflection, then my reflection version that had an issue and, in the end, the correct version.</p><p
style="text-align: justify;"><em>TestClass </em>is a class that has a property of type <em>List&lt;int&gt;</em>:</p><pre class="brush: csharp; title: ; notranslate">
class TestClass
{
    public List&lt;int&gt; Value { get; set; }
}
</pre><p
style="text-align: justify;">Goal: create an instance of this class, set the property and print the second element in the list. Simple, huh? The code without reflection is:</p><pre class="brush: csharp; title: ; notranslate">
TestClass c = new TestClass();
c.Value = new List&lt;int&gt;() { 4, 5, 6 };
Console.WriteLine(c.Value[1]);
</pre><p
style="text-align: justify;">Seems straight forward to use reflection for this, right? Here is my attempt:</p><pre class="brush: csharp; title: ; notranslate">
//TestClass c = new TestClass();
object c = new TestClass();
//c.Value = new List&lt;int&gt;() { 4, 5, 6 };
Type t = c.GetType();
PropertyInfo prop = t.GetProperty(&quot;Value&quot;, BindingFlags.Public | BindingFlags.Instance);
prop.SetValue(c, new List&lt;int&gt;() { 4, 5, 6 }, null);
//Console.WriteLine(c.Value[1]);
int valueToOutput = (int)prop.GetValue(c, new object[] { 1 });
Console.WriteLine(valueToOutput);
</pre><p
style="text-align: justify;">Can you see the glitch? I can tell you that line 10 throws <em>TargetParameterCountException</em>. You know why?</p><p><span
id="more-2279"></span></p><p
style="text-align: justify;">Looking at the IL disassembled code for the program without reflection gives the answer (I added some comments for clarity and removed unnecessary lines):</p><pre class="brush: plain; highlight: [12,13]; title: ; notranslate">
//TestClass c = new TestClass();
IL_0001:  newobj     instance void ConsoleApplication1.TestClass::.ctor()
//c.Value = new List&lt;int&gt;() { 4, 5, 6 };
IL_0008:  newobj     instance void class [mscorlib]System.Collections.Generic.List`1&lt;int32&gt;::.ctor()
IL_0010:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1&lt;int32&gt;::Add(!0)
IL_0018:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1&lt;int32&gt;::Add(!0)
IL_0020:  callvirt   instance void class [mscorlib]System.Collections.Generic.List`1&lt;int32&gt;::Add(!0)
IL_0027:  callvirt   instance void ConsoleApplication1.TestClass::set_Value(class [mscorlib]System.Collections.Generic.List`1&lt;int32&gt;)
//Console.WriteLine(c.Value[1]);
IL_002e:  callvirt   instance class [mscorlib]System.Collections.Generic.List`1&lt;int32&gt; ConsoleApplication1.TestClass::get_Value()
IL_0034:  callvirt   instance !0 class [mscorlib]System.Collections.Generic.List`1&lt;int32&gt;::get_Item(int32)
IL_0039:  call       void [mscorlib]System.Console::WriteLine(int32)
</pre><p
style="text-align: justify;">Line 3 in the original program gets translated to a property get in order to obtain the <em>List&lt;nt&gt;</em> object and then, on that object, the <em>get_Item</em> method is called with the same arguments as the indexed property. This is where I was wrong, I was calling the property with the arguments that were supposed to be for method and, of course, not invoking the method. The correct approach is (changed lines are highlighted):</p><pre class="brush: csharp; highlight: [10,11,12]; title: ; notranslate">
//TestClass c = new TestClass();
object c = new TestClass();
//c.Value = new List&lt;int&gt;() { 4, 5, 6 };
Type t = c.GetType();
PropertyInfo prop = t.GetProperty(&quot;Value&quot;, BindingFlags.Public | BindingFlags.Instance);
prop.SetValue(c, new List&lt;int&gt;() { 4, 5, 6 }, null);
//Console.WriteLine(c.Value[1]);
object listObject = prop.GetValue(c, null);
MethodInfo mtd = listObject.GetType().GetMethod(&quot;get_Item&quot;, BindingFlags.Public | BindingFlags.Instance);
int valueToOutput = (int)mtd.Invoke(listObject, new object[] { 1 });
Console.WriteLine(valueToOutput);
</pre><p
style="text-align: justify;">In the end, two observations:</p><p
style="text-align: justify;">1. A method can&#8217;t have a default indexer and a method <em>get_Item</em> with the same argument. The following code will not compile because the method is defined twice.</p><pre class="brush: csharp; title: ; notranslate">
class TestClass
{
    public int this[int index]
    {
        get
        {
            return 0;
        }
    }
    public int get_Item(int index)
    {
        return 0;
    }
}
</pre><p
style="text-align: justify;">2. You can replace indices with calls to <em>get_Item</em>. This method is hidden by the Visual Studio Intellisense but it perfectly legal.</p><pre class="brush: csharp; title: ; notranslate">
TestClass c = new TestClass();
c.Value = new List&lt;int&gt;() { 4, 5, 6 };
//Equivalent with Console.WriteLine(c.Value[1]);
Console.WriteLine(c.Value.get_Item(1));
</pre>]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/default-indexer-and-reflection-glitch/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Modifying .NET binaries – Part 2</title><link>http://victorhurdugaci.com/modifying-net-binaries-part-2/</link> <comments>http://victorhurdugaci.com/modifying-net-binaries-part-2/#comments</comments> <pubDate>Wed, 21 Jul 2010 11:16:39 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Expert]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[.NET]]></category> <category><![CDATA[Advanced]]></category> <category><![CDATA[CFF Explorer]]></category> <category><![CDATA[Cracking]]></category> <category><![CDATA[IL]]></category> <category><![CDATA[WinDbg]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=2122</guid> <description><![CDATA[Description Objective Remove the &#8216;Trial protection&#8217; from an obfuscated .NET application Tools WinDbg CFF Explorer Target audience Advanced users The second part of the article discusses how to modify binaries that are obfuscated. For simplicity and clarity, I will not use obfuscated binaries. Doing this, allows the reader to understand what is actually happening. In [...]]]></description> <content:encoded><![CDATA[<table
class="tutorial-description" border="1" cellspacing="0"><tbody><tr><th
colspan="2">Description</th></tr><tr><td
class="header-column">Objective</td><td>Remove the &#8216;Trial protection&#8217; from an obfuscated .NET application</td></tr><tr><td
class="header-column">Tools</td><td><ul><li>WinDbg</li><li>CFF Explorer</li></ul></td></tr><tr><td
class="header-column">Target audience</td><td>Advanced users</td></tr></tbody></table><p
style="text-align: justify;">The second part of the article discusses how to modify binaries that are obfuscated. For simplicity and clarity, I will not use obfuscated binaries. Doing this, allows the reader to understand what is actually happening. In the demo I will completely ignore the name of the methods or the actual, non-obfuscated, code.</p><p
style="text-align: justify;">I recommend reading the <a
href="http://victorhurdugaci.com/modifiying-net-binaries-part-1/" target="_blank">first part</a>, if you didn&#8217;t already. It provides some information that might be needed to understand theis second part.</p><p
style="text-align: justify;">The same &#8216;TrialApp.exe&#8217; binary is used. The current approach, as opposed the the former one, is:</p><ol
style="text-align: justify;"><li>Load the application in debugger and break the execution when the trial message is displayed.</li><li>Get the call stack</li><li>Find the address of the trial check method</li><li>Remove the call</li></ol><h4 style="text-align: justify;">1. Load the application in debugger and break the execution when the trial message is displayed</h4><p
style="text-align: justify;">WinDbg can be obtained for free from Windows SDK (see the Microsoft Downloads website). If you are running a 64 bit OS, make sure you start the 32bit version of WinDbg (should be in Program Files (x86)).</p><p
style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg01.jpg"><img
class="alignright size-thumbnail wp-image-2130" title="WinDbg01" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg01-150x101.jpg" alt="" width="150" height="101" /></a>Load &#8216;TrialApp.exe&#8217; in WinDbg by clicking File -&gt; Load Executable. In order to run it you have 3 options:</p><ol
style="text-align: justify;"><li>Type &#8216;g&#8217; and press ENTER</li><li>Press F5</li><li>Click Debug -&gt; Go</li></ol><p
style="text-align: justify;">The application will start and the execution will stop when the message box is displayed. Is actually waiting for the user to click OK. At this point break the execution by pressing Debug -&gt; Break.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg02.jpg"><img
class="aligncenter size-large wp-image-2131" title="WinDbg02" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg02-1024x689.jpg" alt="" width="717" height="482" /></a></p><p
style="text-align: justify;">Before being able to debug the .NET application, 2 DLLs needs to be loaded. They help the debugger &#8216;understand&#8217; the .NET internals. The actual paths might differ on your configuration. Anyway, make sure you load the 32 bit version of these files (the 64 bit version are in the <em>Framework64 </em>folder). The <em>.load</em> command loads external libraries.</p><pre class="brush: plain; light: true; title: ; notranslate">.load c:\Windows\Microsoft.NET\Framework\v4.0.30319\SOS.dll
.load c:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll</pre><h4><span
id="more-2122"></span>2. Get the call stack</h4><p
style="text-align: justify;">A call stack is associated with a thread. Before getting the stack we need to figure out which is the thread for which we want it. Execute the following command and inspect the output&#8230;</p><pre class="brush: plain; light: true; title: ; notranslate">!threads</pre><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg03.jpg"><img
class="size-large wp-image-2132  aligncenter" title="WinDbg03" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg03-1024x689.jpg" alt="" width="717" height="482" /></a></p><p
style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg03.jpg"></a>There are two thread having IDs 0 and 2. Is quite easy to decide which is the main thread since just one of them is Single Thread Apartment (STA). Switch to the main thread and display the CLR stack using the following commands:</p><pre class="brush: plain; light: true; title: ; notranslate">~0s
!clrstack</pre><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg04.jpg"><img
class="aligncenter size-large wp-image-2133" title="WinDbg04" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg04-1024x689.jpg" alt="" width="717" height="482" /></a></p><h4>3. Find the address of the trial check method</h4><p
style="text-align: justify;">OK! You&#8217;re still with me? If yes, then take a look at the result of the last command. It displays the call stack of the main thread. Notice that OnCreateControl calls OnLoad, OnLoad calls From1_Load, etc. In the case of obfuscated code, the name would probably be strange and you would have to analyze each method in depth. Because the code was JIT compiled the call to the trial check was inlined.</p><p
style="text-align: justify;">Let&#8217;s take a look at the IL code for Form1_Load. To do this, first we need the address description of the MethodDesc structure of method. The <em>ip2md</em> command returns the structure. The argument is the IP address of the method. After this, just dump the IL for the address specified in MethodDesc. I want to make on observation here: if you look at the MethodDesc structure you can see the <em>mdToken</em> field. This field specified the table and the row in the table for the this method (the row corresponding to this method is the 6<sup>th</sup>, because the index starts at 0).</p><pre class="brush: plain; light: true; title: ; notranslate">!ip2md 003f01f9
!dumpil 00176304</pre><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg05_details.jpg"><img
class="aligncenter size-large wp-image-2135" title="WinDbg05_details" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/WinDbg05_details-1024x689.jpg" alt="" width="717" height="482" /></a></p><p
style="text-align: justify;">In case of obfuscated code, you would probably see just a call instruction to some cryptic method. It makes no difference. We can see that at IL_0001 (relative to the start of the method) we have a call and this instruction uses 5 bytes in the file (0006-0001 = 0005; in hex)).</p><p
style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/CFF01.jpg"><img
class="alignright size-thumbnail wp-image-2126" title="CFF01" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/CFF01-150x101.jpg" alt="" width="150" height="101" /></a>Having the size of the instruction, its position and the row of the method in the <a
href="http://msdn.microsoft.com/en-us/magazine/cc163791.aspx#S8" target="blank">methods table</a> we can proceed further. Open CFF Explorer and load the assembly.</p><p
style="text-align: justify;">Navigate to .NET Directory -&gt; MetaData Streams -&gt; #~ -&gt; Tables. Look for the Method table in the new tree and select the entry with number 5. Copy its RVA value.</p><h4>4. Remove the call</h4><p
style="text-align: justify;">With the RVA in hand (on clipboard :-) ), remove the call just like in the first part of the article. Replace the call bytes with zeros. One observation: we must also remove the instruction before the call (ldarg_0; opcode 02; no arguments). So, zero 6 bytes starting at the first in the method.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/07/CFF02.jpg"><img
class="aligncenter size-large wp-image-2127" title="CFF02" src="http://victorhurdugaci.com/wp-content/uploads/2010/07/CFF02-1024x692.jpg" alt="" width="717" height="484" /></a></p><p
style="text-align: justify;">In other words, replace:</p><pre class="brush: plain; light: true; title: ; notranslate">00 00 0A 02 28 08 00 00 06 2A 1E 02 28 06 00 00
06 2A 66 02 7B 02 00 00 04 2C 10 72 01 00 00 00</pre><p>with</p><pre class="brush: plain; light: true; title: ; notranslate">00 00 0A 02 28 08 00 00 06 2A 1E 00 00 00 00 00
00 2A 66 02 7B 02 00 00 04 2C 10 72 01 00 00 00</pre><p
style="text-align: justify;">Run the application. The trial check is gone.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/modifying-net-binaries-part-2/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Modifying .NET binaries &#8211; Part 1</title><link>http://victorhurdugaci.com/modifiying-net-binaries-part-1/</link> <comments>http://victorhurdugaci.com/modifiying-net-binaries-part-1/#comments</comments> <pubDate>Sun, 30 May 2010 17:11:00 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Expert]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[.NET]]></category> <category><![CDATA[Advanced]]></category> <category><![CDATA[CFF Explorer]]></category> <category><![CDATA[Cracking]]></category> <category><![CDATA[IL]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=2076</guid> <description><![CDATA[The content of this post can be used for good and bad purposes. Modifying the source code to bypass trial/license checks is what crackers do in order to get paid software for free. Be advised that the purpose of this article is not to teach you how to steal. My target for this article are [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">The content of this post can be used for good and bad purposes. Modifying the source code to bypass trial/license checks is what crackers do in order to get paid software for free. Be advised that the purpose of this article is not to teach you how to steal. My target for this article are the .NET developers who should understand what a cracker will (try to) do in order to get access to paid features.</p><p
style="text-align: justify;">Before reading any further you should understand that each protection measure (as long as the cracker can access the source code) is useless. Is just a matter of time, for a motivated person, before she will bypass any protection.</p><p
style="text-align: justify;">For the demo, we are going to use a very simple Windows Forms Application that will display a message box with a trial message and will exit after that. The goal is to show a few techniques that will prevent the application from exiting (and will remove the trial message).</p><p
style="text-align: justify;">The code for the &#8216;trial&#8217; application is kept in just one class. There is just one variable for checking the trial and we&#8217;ll consider that is always true &#8211; it makes no difference if there was a function call to determine if the trial has expired.</p><pre class="brush: csharp; title: ; notranslate">
public partial class Form1 : Form
{
    bool hasExpired = true;
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        CheckTrialApp();
    }
    private void CheckTrialApp()
    {
        if (hasExpired)
        {
            MessageBox.Show(&quot;Trial has expired&quot;);
            Application.Exit();
        }
    }
}
</pre><p
style="text-align: justify;">The binary used was compiled on the x86 Release configuration with VS2010 having .NET 4.0 as target framework. The IL Disassembler from VS2010 and a free application called <a
href="http://www.ntcore.com/exsuite.php" target="blank">CFF Explorer</a> are used to view and edit the binary.</p><p
style="text-align: justify;"><span
id="more-2076"></span></p><p
style="text-align: justify;">Opening the &#8216;TrialApp.exe&#8217; file (the target binary) in IL Dissasembler will reveal all the statements from each method. This is important but, more important is the <a
href="http://stackoverflow.com/questions/2170843/va-virutual-adress-rva-relative-virtual-address" target="blank">RVA</a> of the method containing the trial check, the bytes for each statement and their position relative to the RVA.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/05/BytesExplained.jpg"><img
class="aligncenter size-full wp-image-2087" title="BytesExplained" src="http://victorhurdugaci.com/wp-content/uploads/2010/05/BytesExplained.jpg" alt="" width="708" height="408" /></a></p><p
style="text-align: justify;">By knowing the RVA you are able to navigate to that address using CFF explorer and locate the bytes for the calls. Even without seeing the actual bytes, one is able to locate the calls (and their length) by looking at the offsets (ie: the byte 2C is located 0006 bytes from the beginning of the implementation) &#8211; more on this in Part2.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/05/ILMapping.jpg"><img
class="aligncenter size-large wp-image-2090" title="ILMapping" src="http://victorhurdugaci.com/wp-content/uploads/2010/05/ILMapping-1024x433.jpg" alt="" width="717" height="303" /></a></p><p
style="text-align: justify;">Having access to all this information gives not one but many possibilities of bypassing the trial check:</p><ol
style="text-align: justify;"><li>Remove the two calls to <em>Application.Exit</em> and <em>MessageBox.Show.</em></li><li>Change the <em>if</em> check.</li><li>Remove the &#8216;CheckTrialApp&#8217; call from &#8216;Form1_Load&#8217;.</li></ol><p
style="text-align: justify;">This post will cover just the first two possibilities, since the third is similar to the first.</p><h3>1. Remove the calls to <em>Exit </em>and <em>Show</em></h3><p
style="text-align: justify;">The bytes from the method implementation:</p><pre class="brush: csharp; light: true; title: ; notranslate">
         02 7B 02 00 00 04 2C 10 72 01 00 00 70
28 16 00 00 0A 26 28 17 00 00 0A 2A
</pre><p
style="text-align: justify;">A call to a method has the opcode 28. The next 4 bytes following the opcode represent the location of the method in the methods table (you can see this table using CFF explorer).</p><p
style="text-align: justify;">Now here comes the magic: in order to remove the calls to <em>Exit </em>and <em>Show, </em>one must  replace with NOP, all the bytes associated with these methods. Basically we are going the introduce a NOP byte (00) for each byte in the call.</p><pre class="brush: csharp; light: true; title: ; notranslate">
         02 7B 02 00 00 04 2C 10 72 01 00 00 70
00 00 00 00 00 26 00 00 00 00 00 2A
</pre><p>That&#8217;s all. Save the file and the trial is bypassed.</p><h3>2. Change the <em>if</em> check</h3><p
style="text-align: justify;">If you look in the disassembled IL you can see that at offset 0&#215;6 we have a <em>brfalse.s</em> opcode. This is a branch instruction that will branch to offset 0&#215;18 (IL_0018) if false. However, in the case of &#8216;TrialApp&#8217;, since <em>hasExpired</em> is always true, the branch will never take place and the code following it will be executed.</p><p
style="text-align: justify;">In order to change the meaning of the code &#8211; in other words &#8220;give the trial message if the application has NOT expired&#8221; &#8211; the check will be changed. Currently, is checking against <em>false</em> using the instruction <em>brfalse.s</em>, having the opcode 2C. By looking on MSDN, the opcode for <em>brtrue.s</em> can be found: 2D. Replacing 2C with 2D will make the branch happen always.</p><p
style="text-align: justify;">The method inside the binary, after replacing the <em>brfalse.s</em> opcode:</p><pre class="brush: csharp; light: true; title: ; notranslate">
         02 7B 02 00 00 04 2D 10 72 01 00 00 70
28 16 00 00 0A 26 28 17 00 00 0A 2A
</pre><p
style="text-align: justify;">That&#8217;s all. The message box will not be displayed since the body of the <em>if</em> statement is no longer executed.</p><p
style="text-align: justify;">There are some techniques that will make cracking difficult. Obfuscating the code is one of them. However, part 2 of this article will cover the modification of obfuscated binaries.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/modifiying-net-binaries-part-1/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Expression evaluation</title><link>http://victorhurdugaci.com/expression-evaluation/</link> <comments>http://victorhurdugaci.com/expression-evaluation/#comments</comments> <pubDate>Thu, 27 May 2010 17:44:33 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Tips]]></category> <category><![CDATA[Bug]]></category> <category><![CDATA[Coding]]></category> <category><![CDATA[Evaluation]]></category> <category><![CDATA[Expression]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=2035</guid> <description><![CDATA[Let&#8217;s start with a simple quiz: 7/2 = &#8230; . Of course is 3.5 but is this also true for code? If you somehow use a non-fractional data type for storing the result, you will always get the result 3. And that should not surprise you. However, if you choose to use a fractional data [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">Let&#8217;s start with a simple quiz: 7/2 = &#8230; . Of course is 3.5 but is this also true for code?</p><p
style="text-align: justify;">If you somehow use a non-fractional data type for storing the result, you will always get the result 3. And that should not surprise you.</p><pre class="brush: csharp; light: true; title: ; notranslate">
int result = 7/2; //expression is 3
</pre><p
style="text-align: justify;">However, if you choose to use a fractional data type, things will change &#8230;</p><pre class="brush: csharp; light: true; title: ; notranslate">
double result = 7/2;
</pre><p
style="text-align: justify;">&#8230; or not. The value stored in the variable <em>result</em> is still 3 (actually 3.0 or something really close to 3.0 &#8211; since floating point data types store the approximation of a number).</p><p
style="text-align: justify;">Why is this happening?<br
/> <span
id="more-2035"></span><br
/> Let&#8217;s take a look at the expression, <em>result = 7/2</em>. There are two operators: / and =. Based on their precedence, the first evaluated is the division operator; it is a binary operator so, it has two operands. The general definition of the / operator in C# is:</p><pre class="brush: csharp; light: true; title: ; notranslate">
public static TYPE1 operator /(TYPE2 op1, TYPE3 op2)
</pre><p
style="text-align: justify;">In our case 7 and 2 need to be matched to TYPE2 and TYPE3. In most languages, the operators for primitive types are defined only for the same type of operands (TYPE2 = TYPE3). In this way, for <em>n</em> types <em>n</em> operator overloads have to be defined, otherwise it could go up to <em>n<sup>2</sup></em> overloads.</p><p
style="text-align: justify;">The compiler will try to match the operands with one of the operator signatures. In our case, both operands are integer so, it will call <em>operator / (int, int)</em> which returns <em>int</em> (!!). The expression on the right hand side (RHS) of = is evaluated as an <em>int</em>.</p><p
style="text-align: justify;">After that, the = operator will be evaluated. Because its RHS operand is an <em>int</em>, a conversion will be performed to <em>double</em>, in order to match the type of the left hand side of the operator. At this point, is to late to get the fractional part because it was already disposed. The final result will be an integer represented as a double.</p><p
style="text-align: justify;">The following drawing shows the abstract syntax tree and its evaluation for the previously mentioned expression.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/05/AST1.jpg"><img
class="aligncenter size-large wp-image-2047" title="AST1" src="http://victorhurdugaci.com/wp-content/uploads/2010/05/AST1-1024x581.jpg" alt="" width="740" height="430" /></a></p><p
style="text-align: justify;">In order to fix the problem, you need to explicitly state that a certain part of the expression must be evaluated as double. The best way to do this is to make one of the operands double. For example:</p><pre class="brush: csharp; light: true; title: ; notranslate">
double r1 = 7.0/2;
double r2 = 7/2.0;
double r3 = 7.0/2.0;
double r4 = 7d/2d;
double r5 = ((double)5)/2; //This is not recommended but will work
</pre><p
style="text-align: justify;">In this above cases, the conversion node will be evaluated sooner, before any precision is lost, hence allowing you to get the expected result. The next image shows the AST for the expression <em>double result = 7 / 3.0</em>.</p><p><a
href="http://victorhurdugaci.com/wp-content/uploads/2010/05/AST2.jpg"><img
src="http://victorhurdugaci.com/wp-content/uploads/2010/05/AST2-1024x593.jpg" alt="" title="AST2" width="740" height="430" class="aligncenter size-large wp-image-2053" /></a></p><p
style="text-align: justify;">Understanding how an expression is evaluated is very important because non trivial statement can make your life harder. Take a look at the following examples and try to guess the results (r4 is similar to a bug we encountered).</p><pre class="brush: csharp; light: true; title: ; notranslate">
double r1 = 7 / 2;
double r2 = 6.0 + 7 / 2;
double r3 = 5 / 2 + 7 / 2;
double r4 = DateTime.Now.Millisecond * (1000 / 3600);
double r5 = 6.5 / (1 / 2);
double r6 = 10.0 * (1 / 2);
double r7 = 11.0 * 1 / 2;
</pre>]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/expression-evaluation/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Using UAC with C# – Part 3</title><link>http://victorhurdugaci.com/using-uac-with-c-part-3/</link> <comments>http://victorhurdugaci.com/using-uac-with-c-part-3/#comments</comments> <pubDate>Wed, 06 Jan 2010 22:02:28 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[Programming]]></category> <category><![CDATA[UAC]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1716</guid> <description><![CDATA[After a long period since I wrote part 2 of this article I decided to add some extra information. There is one thing that was missed by the previous two articles: the design of UAC enabled applications. If you use Windows Vista/7 then you know that buttons and links which elevate privileges are preceded by [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">After a long period since I wrote <a
href="http://victorhurdugaci.com/using-uac-with-c-part-2/" target="_blank">part 2</a> of this article I decided to add some extra information. There is one thing that was missed by the previous two articles: the design of UAC enabled applications.</p><p
style="text-align: justify;">If you use Windows Vista/7 then you know that buttons and links which elevate privileges are preceded by a shield icon. This is the way Microsoft decided to inform the user about the effect of clicking that control.</p><p
style="text-align: justify;">The first idea that might pop up is the reinvention of the wheel (or shield). In other words you could draw the shield on a button. This is OK except that:</p><ol
style="text-align: justify;"><li>Is not easy</li><li>Will require you to recompile the interface if Microsoft decides to change the icon</li><li>You need the icon in many sizes 16&#215;16, 24&#215;24, 32&#215;32, etc. (extract it from MS&#8217; DLLs)</li><li>Will create a lot of overhead with layout (position icon relative to text size/position)</li></ol><p
style="text-align: justify;">The second method is easier, safer and recommended by MS. All you need to do is send a specific message (<em>BCM_SETSHIELD</em>) to the button if the user has limited privileges and pressing that button will trigger the UAC window. Actually there is a second, tricky, thing that must be done: the style of the button must be &#8220;System&#8221; (in C# &#8220;<a
href="http://msdn.microsoft.com/en-us/library/system.windows.forms.flatstyle.aspx" target="_blank">System.Windows.FlatStyle</a>.System&#8221;). Without this you will not be able to see the shield.</p><p
style="text-align: justify;">The code provided in <a
href="http://victorhurdugaci.com/using-uac-with-c-part-1/" target="_blank">part 1</a> of this article will be modified in order to display the shield on the two buttons. Moreover, the shield will be displayed only when the user runs under an account with limited privileges or non-elevated administrator.</p><p
style="text-align: center;"><img
title="UACShield" src="http://victorhurdugaci.com/wp-content/uploads/2010/01/UACShield.png" alt="" width="700" height="280" /></p><p
style="text-align: justify;">In order to display the shield one needs to send the <em>BCM_SETSHIELD </em>(=<em>0x0000160C)</em> message to the button. This can be done by using the <a
href="http://msdn.microsoft.com/en-us/library/ms644950%28VS.85%29.aspx">SendMessage function from user32.dll</a>. This article will not cover what is and how to use SendMessage, if you need more information about it follow the previous link.</p><p
style="text-align: justify;">To set the shield of the &#8220;Elevate this application&#8221; button one needs to send the message in the following way:</p><div
class="wp_codebox"><table><tr
id="p17164"><td
class="code" id="p1716code4"><pre class="csharp" style="font-family:monospace;">SendMessage<span style="color: #008000;">&#40;</span>btnElevate<span style="color: #008000;">.</span><span style="color: #0000FF;">Handle</span>, BCM_SETSHIELD, <span style="color: #FF0000;">0</span>, <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">The first parameter is the handle of the button, the second one is the message, the third one is not used and must be &#8217;0&#8242; and the last argument must be non-zero in order to draw the shield, zero otherwise.</p><p
style="text-align: justify;">If you try this it will not work :) Remember the &#8216;tricky&#8217; thing told before? This is the full code to display the shield for <em>btnElevate</em>:</p><div
class="wp_codebox"><table><tr
id="p17165"><td
class="code" id="p1716code5"><pre class="csharp" style="font-family:monospace;">btnElevate<span style="color: #008000;">.</span><span style="color: #0000FF;">FlatStyle</span> <span style="color: #008000;">=</span> FlatStyle<span style="color: #008000;">.</span><span style="color: #000000;">System</span><span style="color: #008000;">;</span>
SendMessage<span style="color: #008000;">&#40;</span>btnElevate<span style="color: #008000;">.</span><span style="color: #0000FF;">Handle</span>, BCM_SETSHIELD, <span style="color: #FF0000;">0</span>, <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">There is only one thing that must be done in order to work properly. Remove the shield if the user has elevated privileges. I don&#8217;t know if this is against MS&#8217; recommendation but in my opinion one must not be shown information that cannot be used in that context; in our case don&#8217;t show the elevate shield if there is nothing to elevate.</p><p
style="text-align: justify;">Part 1 described how to check if a user has full rights. Now we are just using that boolean variable:</p><div
class="wp_codebox"><table><tr
id="p17166"><td
class="code" id="p1716code6"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>hasAdministrativeRight<span style="color: #008000;">&#41;</span>
    SetUACShields<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">Where <em>SetUACShields</em> will send the message to all buttons that require the shield drawn.</p><p
style="text-align: justify;">The full updated code from Part 1: <a
href="http://victorhurdugaci.com/download/uacapp3.zip"><img
src="http://victorhurdugaci.com/img/download-icon.jpg" alt="Download Icon" width="24" height="24" />UAC Code 3 (10.13 KB)</a></p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/using-uac-with-c-part-3/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Tip 2: #if</title><link>http://victorhurdugaci.com/tip-2-if/</link> <comments>http://victorhurdugaci.com/tip-2-if/#comments</comments> <pubDate>Thu, 23 Jul 2009 19:34:59 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tips]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[#if]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=1262</guid> <description><![CDATA[This is a C# tip When the C# compiler encounters an #if directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined. Unlike C and C++, you cannot assign a numeric value to a symbol; the #if statement in C# is Boolean and [...]]]></description> <content:encoded><![CDATA[<h2>This is a C# tip</h2><p
style="text-align: justify;">When the C# compiler encounters an<span><span> #if</span></span> directive, followed eventually by an #endif directive, it will compile the code between the directives only if the specified symbol is defined. Unlike C and C++, you cannot assign a numeric value to a symbol; the #if statement in C# is Boolean and only tests whether the symbol has been defined or not.</p><p
style="text-align: justify;">A predefined (by default) symbol on the &#8220;Debug&#8221; build configuration is <em>DEBUG</em>. Using this symbol you can define code that will be compiled only in Debug; for example, a debug window will be shown only when needed.</p><div
class="wp_codebox"><table><tr
id="p12628"><td
class="code" id="p1262code8"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System</span><span style="color: #008000;">;</span>
<span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008080;">System.Text</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">namespace</span> ConsoleApplication1
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">class</span> Program
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #6666cc; font-weight: bold;">void</span> Main<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> args<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
<span style="color: #008080;">#if DEBUG</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Debugging information&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008080;">#endif</span>
            Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Code that always executes&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></td></tr></table></div><p
style="text-align: justify;">The code above will print<em> &#8220;Debugging information&#8221;</em> and <em>&#8220;Code that always executes&#8221;</em> when build on Debug and will display only <em>&#8220;Code that always executes&#8221;</em> when build on another configuration.</p><p
style="text-align: justify;">You can suppress the definition of the <em>DEBUG</em> symbol from the project properties or by removing the DEBUG from the build argument <em>&#8220;/define:DEBUG&#8221;. </em>Also, you can define your own symbols in order to accommodate your needs.</p><p
style="text-align: justify;">Define as many build configurations and symbols you need but don&#8217;t abuse this feature!</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/tip-2-if/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>I.R. Certified</title><link>http://victorhurdugaci.com/i-r-certified/</link> <comments>http://victorhurdugaci.com/i-r-certified/#comments</comments> <pubDate>Fri, 24 Apr 2009 07:28:23 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Personal/Blog]]></category> <category><![CDATA[Brasov]]></category> <category><![CDATA[Bucharest]]></category> <category><![CDATA[Certification]]></category> <category><![CDATA[Exam]]></category> <category><![CDATA[MCP]]></category> <category><![CDATA[Pictures]]></category> <category><![CDATA[Train]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=846</guid> <description><![CDATA[I finally got it, my first Microsoft certification. Yesterday I went to Bucharest, Romania to take the 70-536 Microsoft .NET Framework &#8211; Application Development Foundation exam. It was an interesting experience because of the train which was 30 late. Got to Bucharest later than expected and I had to (almost) run to the exam center [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;"><img
class="alignleft" title="MCP Logo" src="http://victorhurdugaci.com/img/mcplogo.png" alt="" width="160" height="80" />I finally got it, my first Microsoft certification. Yesterday I went to Bucharest, Romania to take the <em>70-536 Microsoft .NET Framework &#8211; Application Development Foundation</em> exam.</p><p
style="text-align: justify;">It was an interesting experience because of the train which was 30 late. Got to Bucharest later than expected and I had to (almost) run to the exam center -  got there 1-2 minutes before the exam start.</p><p
style="text-align: justify;">The exam itself was a little different than what I was expecting (from the practice tests). I had 40 questions instead on 45 (why?) and there were a lot of .NET globalization questions. I would rate it as medium to hard but the time was more than enough and I was able to recheck my questions 3 times and still got out of the room with 50 minutes before deadline.</p><p
style="text-align: justify;">After the exam I took a walk through Bucharest and took some pictures. That city is so green (compared to Brasov)&#8230;</p><div
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3184.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-850" title="img_3184" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3184-150x112.jpg" alt="img_3184" width="150" height="112" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3187.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-851" title="img_3187" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3187-150x112.jpg" alt="img_3187" width="150" height="112" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3192.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-852" title="img_3192" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3192-150x112.jpg" alt="img_3192" width="150" height="112" /></a> <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3198.jpg" target="_blank"><img
class="alignnone size-thumbnail wp-image-854" title="img_3198" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/img_3198-150x112.jpg" alt="img_3198" width="150" height="112" /></a></div><p
style="text-align: justify;">Guess what? When returning the train, again, was late. Just this time there was almost an hour.</p><p
style="text-align: justify;"><strong>NOTE:</strong> I.R. stands for &#8220;I are&#8221; (see the animated TV series &#8220;I Am Weasel&#8221;).</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/i-r-certified/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Free C# book</title><link>http://victorhurdugaci.com/free-csharp-book/</link> <comments>http://victorhurdugaci.com/free-csharp-book/#comments</comments> <pubDate>Wed, 08 Apr 2009 14:59:09 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[C#]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Misc]]></category> <category><![CDATA[eBook]]></category> <category><![CDATA[Free]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=737</guid> <description><![CDATA[RedGate is offering for free download the ebook &#8220;Illustrated C# 2008&#8243;. This book is interesting for beginners because it has a lot of drawings and diagrams that explain better the concepts described by text. It could be used by persons migrating from C++ or VB to C# or it could even be the support material [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;"><img
class="alignleft size-full wp-image-738" title="illustratedcsharp" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/illustratedcsharp.gif" alt="illustratedcsharp" width="110" height="144" />RedGate is offering for free download the ebook &#8220;Illustrated C# 2008&#8243;.</p><p
style="text-align: justify;">This book is interesting for beginners because it has a lot of drawings and diagrams that explain better the concepts described by text. It could be used by persons migrating from C++ or VB to C# or it could even be the support material for a course.</p><p
style="text-align: justify;">In 730 pages the author, Daniel Solis offers a very visual approach – with lots of figures, diagrams and code samples – that will help you get to work with C# fast.</p><p
style="text-align: justify;">Go <a
href="http://www.red-gate.com/products/ants_profiler/boost_app_performance_ebook5.htm?utm_source=infoq&amp;utm_medium=textad&amp;utm_term=1506&amp;utm_content=boostappperf-ebook2&amp;utm_campaign=antsprofiler">here</a> to download your copy.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/free-csharp-book/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Using UAC with C# &#8211; Part 2</title><link>http://victorhurdugaci.com/using-uac-with-c-part-2/</link> <comments>http://victorhurdugaci.com/using-uac-with-c-part-2/#comments</comments> <pubDate>Fri, 03 Apr 2009 18:15:06 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[UAC]]></category> <category><![CDATA[User Account Control]]></category> <category><![CDATA[Vista]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=683</guid> <description><![CDATA[In part 1 of this tutorial I have presented how to run an application with and without elevation by specifying this from another process. However there are some situations when an application cannot be run without administrative rights. For example a system configuration utility requires administrative rights to change some global policies. In order to [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;">In <a
href="http://victorhurdugaci.com/using-uac-with-c-part-1/">part 1</a> of this tutorial I have presented how to run an application with and without elevation by specifying this from another process.</p><p
style="text-align: justify;">However there are some situations when an application cannot be run without administrative rights. For example a system configuration utility requires administrative rights to change some global policies.</p><p
style="text-align: justify;">In order to force an application to run only if the current user is administrator or can provide administrative credentials you must add a manifest to the C# project.</p><p
style="text-align: justify;">The manifest is an XML file named &lt;application_name&gt;.exe.manifest with the following content:</p><div
class="wp_codebox"><table><tr
id="p68310"><td
class="code" id="p683code10"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;?xml</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span> <span style="color: #000066;">encoding</span>=<span style="color: #ff0000;">&quot;UTF-8&quot;</span> <span style="color: #000066;">standalone</span>=<span style="color: #ff0000;">&quot;yes&quot;</span><span style="color: #000000; font-weight: bold;">?&gt;</span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;assembly</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;urn:schemas-microsoft-com:asm.v1&quot;</span> <span style="color: #000066;">manifestVersion</span>=<span style="color: #ff0000;">&quot;1.0&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;assemblyIdentity</span> <span style="color: #000066;">version</span>=<span style="color: #ff0000;">&quot;1.0.0.0&quot;</span> <span style="color: #000066;">processorArchitecture</span>=<span style="color: #ff0000;">&quot;X86&quot;</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;UACApp&quot;</span> <span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;win32&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;trustInfo</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;urn:schemas-microsoft-com:asm.v3&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;requestedPrivileges<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
            <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;requestedExecutionLevel</span> <span style="color: #000066;">level</span>=<span style="color: #ff0000;">&quot;requireAdministrator&quot;</span><span style="color: #000000; font-weight: bold;">/&gt;</span></span>
         <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/requestedPrivileges<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/security<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
   <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/trustInfo<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/assembly<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></td></tr></table></div><p
style="text-align: justify;">What is important is the <em>requestedExecutionLevel </em>element. It specifies what permissions (execution level) the application needs in order to start. If the current user does not have the required level then an elevation window is displayed (see part one of the tutorial that describes the elevation window).</p><p
style="text-align: justify;">The default value of <em>requestedExecutionLevel</em> if it is not specified in the manifest or the manifest does not exist is <em>asInvoker. </em>Except <em>asInvoker</em> and <em>requireAdministrator</em> there is another execution level. All three are described below:</p><table
border="0" cellspacing="0" cellpadding="2" width="100%"><tbody><tr><td
style="border:solid 1px black; text-align: center;"><strong>Value</strong></td><td
style="border:solid 1px black; border-left: 0px; text-align: center;"><strong>Description</strong></td><td
style="border:solid 1px black; border-left: 0px; text-align: center;"><strong>Comment</strong></td></tr><tr><td
style="border:solid 1px black; border-top: 0px; text-align: center;">asInvoker</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">The application runs with the same access token as the parent process.</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">Recommended for standard user applications. Do refractoring with internal elevation points, as per the guidance provided earlier in this document.</td></tr><tr><td
style="border:solid 1px black; border-top: 0px; text-align: center;">highestAvailable</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">The application runs with the highest privileges the current user can obtain.</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">Recommended for mixed-mode applications. Plan to refractor the application in a future release.</td></tr><tr><td
style="border:solid 1px black; border-top: 0px; text-align: center;">requireAdministrator</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">The application runs only for administrators and requires that the application be launched with the full access token of an administrator.</td><td
style="border:solid 1px black; border-left: 0px; border-top: 0px;">Recommended for administrator only applications. Internal elevation points are not needed. The application is already running elevated.</td></tr></tbody></table><p
style="text-align: justify;">In order to embed the manifest in the aplication&#8217;s executable you can choose one of the following options:</p><p><span
id="more-683"></span></p><p
style="text-align: justify;"><strong>1. The hard way &#8211; mt.exe</strong></p><p
style="text-align: justify;">The Mt.exe file is a tool that generates signed files and catalogs. It is available in the Microsoft Windows Software Development Kit (SDK). Mt.exe requires that the file referenced in the manifest be present in the same directory as the manifest.</p><p
style="text-align: justify;">The manifest will be embedded after a successful build so we need to add this the call of Mt.exe in the post-build event. In order to do this right click the project -&gt; Properties -&gt; Choose &#8220;Build Events&#8221; from the vertical left tabs.</p><p>Mt.exe is found in many places on disk so the path to it might be different on your configuration. The post build command is:</p><p><em>&#8220;C:Program FilesMicrosoft.NETSDKv2.0 64bitBinmt.exe&#8221; -manifest &#8220;$(ProjectDir)$(TargetName).exe.manifest&#8221; –outputresource:&#8221;$(TargetDir)$(TargetFileName)&#8221;;#1</em></p><p
style="text-align: justify;">Make sure the paths to mt.exe and the .manifest file are correct. You should get something like this:</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-hardway.png"><img
class="aligncenter size-full wp-image-713" title="uac-hardway" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-hardway.png" alt="uac-hardway" width="657" height="347" /></a></p><p
style="text-align: justify;">This method has a drawback. If you start the application with debugging from Visual Studio it will start with limited privileges. Running without debugging will ask you to elevate the parent process (in our case Visual Studio).</p><p
style="text-align: justify;"><strong>2. The easy way &#8211; designer</strong></p><p
style="text-align: justify;">Just create the manifest file, include it in visual studio, go to the &#8220;Application&#8221; tab in project&#8217;s properties and choose the manifest file from the Manifest combo box.</p><p
style="text-align: center;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-easyway.png"><img
class="aligncenter size-full wp-image-712" title="uac-easyway" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-easyway.png" alt="uac-easyway" width="597" height="394" /></a></p><p>Build.</p><p>This method that has another advantage. Even if running with Debug you will still be prompted to elevate Visual Studio.</p><p
style="text-align: center;"><img
class="aligncenter size-full wp-image-714" title="uac-vsmsg" src="http://victorhurdugaci.com/wp-content/uploads/2009/04/uac-vsmsg.png" alt="uac-vsmsg" width="509" height="248" /></p><p>The source code can be downloaded below (it is the application from part 1 but includes the manifest file):</p><h3><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/04/uacapp_manifest.zip">Download source</a></h3><p><strong>IMPORTANT:</strong> This tutorial is useless if you disabled UAC because all you processes (considering you are the administrator) run elevated.</p> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/using-uac-with-c-part-2/feed/</wfw:commentRss> <slash:comments>3</slash:comments> </item> <item><title>Using UAC with C# &#8211; Part 1</title><link>http://victorhurdugaci.com/using-uac-with-c-part-1/</link> <comments>http://victorhurdugaci.com/using-uac-with-c-part-1/#comments</comments> <pubDate>Wed, 01 Apr 2009 05:13:32 +0000</pubDate> <dc:creator>Victor</dc:creator> <category><![CDATA[.NET Framework]]></category> <category><![CDATA[C#]]></category> <category><![CDATA[Intermediate]]></category> <category><![CDATA[Microsoft]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[UAC]]></category> <category><![CDATA[User Account Control]]></category> <category><![CDATA[Vista]]></category> <guid
isPermaLink="false">http://victorhurdugaci.com/?p=638</guid> <description><![CDATA[User Account Control (UAC) is a new technology introduced by Microsoft in Windows Vista and most of the time it is misunderstood by users and developers. It&#8217;s main purpose is to protect the operating system by running applications with reduced privileges. Why should we use this? Most applications DO NOT require full privileges. Think to [...]]]></description> <content:encoded><![CDATA[<p
style="text-align: justify;"><img
class="size-full wp-image-650 alignright" title="user_account_control_administrator_dialog" src="http://victorhurdugaci.com/wp-content/uploads/2009/03/user_account_control_administrator_dialog.png" alt="user_account_control_administrator_dialog" width="307" height="169" />User Account Control (UAC) is a new technology introduced by Microsoft in Windows Vista and most of the time it is misunderstood by users and developers. It&#8217;s main purpose is to protect the operating system by running applications with reduced privileges.</p><p
style="text-align: justify;">Why should we use this? Most applications DO NOT require full privileges. Think to the applications you have written and ask yourself if most of the job can be done without full writes (if you write to disk think if you could write in the user&#8217;s folder or an isolated storage, if writing in registry to HKLM think if you could write to HKLU, etc). The answer is mostly sure &#8220;Yes&#8221;.</p><p
style="text-align: justify;">So why run applications with full privileges when they can be run with limited? Running with more privileges than required is just a security vulnerability -  If an attacker exploits a vulnerability in your application he will gain more control.</p><p
style="text-align: justify;">There are two mistakes developers tend to do:<img
class="size-full wp-image-649 alignright" title="unidentified_uac" src="http://victorhurdugaci.com/wp-content/uploads/2009/03/unidentified_uac.png" alt="unidentified_uac" width="322" height="258" /></p><ol
style="text-align: justify;"><li>Request the end-user to run an application with full rights even though this is not necessarily (most of the time because of bad design practices)</li><li>Do not request to user to run the application elevated but try to perform operations that require more rights</li></ol><p
style="text-align: justify;">By design UAC can only elevate code at process level and only at process&#8217; startup (means that a running process cannot be elevated). In the .NET world this also means that you cannot elevate code running in another app domain because the app domain is part of a running process. In order to elevate an existing application this must be closed and reopen with more privileges.</p><p
style="text-align: justify;">There are two types on UAC dialogs: blue and yellow. When you see a blue dialog you can be sure that the application requesting privileges is signed and trusted. The yellow dialog shows for any application that is not digitally signed and is not fully trusted.</p><p
style="text-align: justify;">User Account Control also prevents a lower privilege process to do the following (list below taken from MSDN):</p><ul
style="text-align: justify;"><li>Perform a window handle validation of higher process privilege.</li><li><em>SendMessage </em>or <em>PostMessage </em>to higher privilege application windows. These Application Programming Interfaces (APIs) return success but silently drop the window message.</li><li>Use thread hooks to attach to a higher privilege process.</li><li>Use Journal hooks to monitor a higher privilege process.</li><li>Perform DLL injection to a higher privilege process.</li></ul><p
style="text-align: justify;">Let&#8217;s see how an UAC aware application should look.</p><p
style="text-align: justify;"><span
id="more-638"></span>It should be composed of two executables (one that will be run with limited privileges and another one that will be started only with needed and with full rights) or two working modes (a mode for limited rights and another one for full rights). Either way you must remember that once you elevated the application and finalized the administrative tasks, the process should be destroyed in order to reduce an attacker&#8217;s privileges.</p><p
style="text-align: justify;">In order to launch an elevated process in Windows Vista the process must be started with the &#8220;<em>runas</em>&#8221; verb. The <em>Verb </em>property is part of System.Diagnostics.Process.StartInfo class. The code snippet that launches &#8220;notepad.exe&#8221; with full rights is showed below:</p><div
class="wp_codebox"><table><tr
id="p63814"><td
class="code" id="p638code14"><pre class="csharp" style="font-family:monospace;">    ProcessStartInfo processInfo <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> ProcessStartInfo<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    processInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">Verb</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;runas&quot;</span><span style="color: #008000;">;</span>
    processInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">FileName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;notepad.exe&quot;</span><span style="color: #008000;">;</span>
    Process<span style="color: #008000;">.</span><span style="color: #0000FF;">Start</span><span style="color: #008000;">&#40;</span>processInfo<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">If you choose to have only one executable file that acts differently based on permissions you should check if the user is part of the administrative group. In Vista even if your user is part of the Administrators group it runs with reduced privileges by default and gains his full rights on demand. The code below stores <em>true</em> in the <em>hasAdministrativeRight</em> boolean variable if the user&#8217;s privileges are administrative and <em>false</em> otherwise.</p><div
class="wp_codebox"><table><tr
id="p63815"><td
class="code" id="p638code15"><pre class="csharp" style="font-family:monospace;">    WindowsPrincipal pricipal <span style="color: #008000;">=</span> <a href="http://www.google.com/search?q=new+msdn.microsoft.com"><span style="color: #008000;">new</span></a> WindowsPrincipal<span style="color: #008000;">&#40;</span>WindowsIdentity<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrent</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">bool</span> hasAdministrativeRight <span style="color: #008000;">=</span> pricipal<span style="color: #008000;">.</span><span style="color: #0000FF;">IsInRole</span><span style="color: #008000;">&#40;</span>WindowsBuiltInRole<span style="color: #008000;">.</span><span style="color: #0000FF;">Administrator</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;">To elevate the current application you must create a process with elevated rights and close the existing instance. However you cannot start a process with limited privileges &#8211; I couldn&#8217;t find a solution. Anyone knows how to start a less privilege process from a higher privilege one? The sample creates an elevated instance of the current executable and closes the existing one.</p><div
class="wp_codebox"><table><tr
id="p63816"><td
class="code" id="p638code16"><pre class="csharp" style="font-family:monospace;">    RunElevated<span style="color: #008000;">&#40;</span>Application<span style="color: #008000;">.</span><span style="color: #0000FF;">ExecutablePath</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Close</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></td></tr></table></div><p
style="text-align: justify;"><em>RunElevated</em> is a method that takes the name of an executable and spawns it in a new elevated process (see the attached code).</p><p
style="text-align: justify;">I have created a sample application that illustrates all the things written so far: it displays the user&#8217;s rights, elevates the current application and starts a process with more privileges. In order to see all features of the application you must have UAC enabled. You can download the code from <a
href="http://victorhurdugaci.com/wp-content/uploads/2009/03/uacapp.zip">this link</a>.</p><p
style="text-align: justify;">Please note that here I recommend to run applications with limited privileges but there are situations when applications need to run unrestricted &#8211; this is the case of system configuration utilities or other special applications. What I want to say is that you should run applications in an unprivileged environment when possible.</p><p
style="text-align: justify;">This is part one of the tutorial. Part 2 will explain how to use the manifest file to specify that an executable must be always run with full privleges.</p><h3 style="text-align: justify;"><a
href="http://victorhurdugaci.com/wp-content/uploads/2009/03/uacapp.zip" target="_self">Download Source Code</a></h3> ]]></content:encoded> <wfw:commentRss>http://victorhurdugaci.com/using-uac-with-c-part-1/feed/</wfw:commentRss> <slash:comments>22</slash:comments> </item> </channel> </rss>
