I.R. Certified

I finally got it, my first Microsoft certification. Yesterday I went to Bucharest, Romania to take the 70-536 Microsoft .NET Framework – 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 -  got there 1-2 minutes before the exam start.

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.

After the exam I took a walk through Bucharest and took some pictures. That city is so green (compared to Brasov)…

img_3184 img_3187 img_3192 img_3198

Guess what? When returning the train, again, was late. Just this time there was almost an hour.

NOTE: I.R. stands for “I are” (see the animated TV series “I Am Weasel”).

Using UAC with C# – Part 2

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 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.

The manifest is an XML file named <application_name>.exe.manifest with the following content:

< ?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> 
   <assemblyidentity version="1.0.0.0" processorArchitecture="X86" name="UACApp" type="win32"/>
      <trustinfo xmlns="urn:schemas-microsoft-com:asm.v3">
      <security>
         <requestedprivileges>
            <requestedexecutionlevel level="requireAdministrator"/> 
         </requestedprivileges>
      </security>
   </trustinfo>
</assembly>

What is important is the requestedExecutionLevel 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).

The default value of requestedExecutionLevel if it is not specified in the manifest or the manifest does not exist is asInvoker. Except asInvoker and requireAdministrator there is another execution level. All three are described below:

Value Description Comment
asInvoker The application runs with the same access token as the parent process. Recommended for standard user applications. Do refractoring with internal elevation points, as per the guidance provided earlier in this document.
highestAvailable The application runs with the highest privileges the current user can obtain. Recommended for mixed-mode applications. Plan to refractor the application in a future release.
requireAdministrator The application runs only for administrators and requires that the application be launched with the full access token of an administrator. Recommended for administrator only applications. Internal elevation points are not needed. The application is already running elevated.

In order to embed the manifest in the aplication’s executable you can choose one of the following options:

Read the rest of this entry »

Using UAC with C# – Part 1

user_account_control_administrator_dialogUser 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’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 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’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 “Yes”.

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.

There are two mistakes developers tend to do:unidentified_uac

  1. 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)
  2. Do not request to user to run the application elevated but try to perform operations that require more rights

By design UAC can only elevate code at process level and only at process’ 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.

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.

User Account Control also prevents a lower privilege process to do the following (list below taken from MSDN):

  • Perform a window handle validation of higher process privilege.
  • SendMessage or PostMessage to higher privilege application windows. These Application Programming Interfaces (APIs) return success but silently drop the window message.
  • Use thread hooks to attach to a higher privilege process.
  • Use Journal hooks to monitor a higher privilege process.
  • Perform DLL injection to a higher privilege process.

Let’s see how an UAC aware application should look.

Read the rest of this entry »

Access private data with Reflection

This article shows how one of the basic OOP principles – encapsulation – can be violated using reflection.

Let’s assume that we have a simple class with a private field called “someHiddenValue”.

class ClassThatHidesSomething
{
    private int someHiddenValue = 5;
}

We want to modify that field from outside the class. This can be done extremely easy through Reflection. First of all we need to get the Type of the ClassThatHidesSomething and get some information about the someHiddenValue field.

Type classThatHidesSomethingType = typeof(ClassThatHidesSomething);
FieldInfo field = classThatHidesSomethingType.GetField(
                         "someHiddenValue",
                         BindingFlags.NonPublic | BindingFlags.Instance);
  • BindingFlags.NonPublic specifies that we want to search in all fields; by default it searches only the public fields – actually here is the trick that violates encapsulation.
  • BindingFlags.Instance specified that we want to search in instance fields also; by default it searches only in static ones.

Now that we have the FieldInfo of that specific field we can do whatever we want with it. Let’s display its value. But first, because the field is an instance field we need an instance of ClassThatHidesSomething.

ClassThatHidesSomething c = new ClassThatHidesSomething();
 
int hiddenFieldValue = (int)field.GetValue(c);
Console.WriteLine("Hidden field value: {0}", hiddenFieldValue);

Using the same instance c we can set the private field’s value.

field.SetValue(c, 6);

Below you can see the entire code (it is a console application):

Read the rest of this entry »

Binding in WinForms like in WPF Part 1

If you have ever used Windows Presentation Foundation (WPF) then you might have been impressed by the binding features of it.

Part one of this tutorial will show how to bind properties of the same type while the second one will also anlyse type conversion.

Using data binding you can synchronize object properties. The source of the binding is the object or property that is changing the value and the destination is the one who receives it (the new value).

There are two types of binding:

  • one way binding – there is only one source that updates the information and as many destinations who receive the update.
  • two way binding – every binding element can update and can receive updates so there is no distinction between source and destination.

Read the rest of this entry »

How expensive are cross-domain operations?

I was curios how expensive is a cross domain operation so I have made a test.

The test procedure is simple. Perform a number of cross-domain and non cross-domain operations (get the value of NextNumber() from same domain and from another domain) and measure the time elapsed. For each value I have runned the application 3 times, recorded the time (in milliseconds) and created the mean of this three.

For this I’ve created a Console Application containing two classes, the main class and “NumberClass” which has a method that returns the next long. The code for this two is below:

NumberClass:

//MarshalByRefObject is used because this object will cross domain boundary
class NumberClass:MarshalByRefObject
{
    public ulong number = 0;

    public ulong NextNumber()
    {
        return number++;
    }
}

The Main method from the main class:

Read the rest of this entry »

EventInfo.AddEventHandler – bug or not?

Reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming. [Wikipedia]

Working a few days ago on a plugin architecture on .NET Framework I’ve found something very interesting. The method System.Reflection.EventInfo.AddEventHandler does late-binding. You’ll probably say “so what?”. Let’s see the problem with an example:

Using Visual Studio 2005/2008, create two C# projects (a windows forms application project and a class library one). Rename the class from the class library project to “TestClass.cs”.

Read the rest of this entry »