Using UAC with C# – Part 3

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 a shield icon. This is the way Microsoft decided to inform the user about the effect of clicking that control.

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:

  1. Is not easy
  2. Will require you to recompile the interface if Microsoft decides to change the icon
  3. You need the icon in many sizes 16×16, 24×24, 32×32, etc. (extract it from MS’ DLLs)
  4. Will create a lot of overhead with layout (position icon relative to text size/position)

The second method is easier, safer and recommended by MS. All you need to do is send a specific message (BCM_SETSHIELD) 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 “System” (in C# “System.Windows.FlatStyle.System”). Without this you will not be able to see the shield.

The code provided in part 1 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.

In order to display the shield one needs to send the BCM_SETSHIELD (=0×0000160C) message to the button. This can be done by using the SendMessage function from user32.dll. This article will not cover what is and how to use SendMessage, if you need more information about it follow the previous link.

To set the shield of the “Elevate this application” button one needs to send the message in the following way:

SendMessage(btnElevate.Handle, BCM_SETSHIELD, 0, 1);

The first parameter is the handle of the button, the second one is the message, the third one is not used and must be ‘0′ and the last argument must be non-zero in order to draw the shield, zero otherwise.

If you try this it will not work :) Remember the ‘tricky’ thing told before? This is the full code to display the shield for btnElevate:

btnElevate.FlatStyle = FlatStyle.System;
SendMessage(btnElevate.Handle, BCM_SETSHIELD, 0, 1);

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’t know if this is against MS’ recommendation but in my opinion one must not be shown information that cannot be used in that context; in our case don’t show the elevate shield if there is nothing to elevate.

Part 1 described how to check if a user has full rights. Now we are just using that boolean variable:

if (!hasAdministrativeRight)
    SetUACShields();

Where SetUACShields will send the message to all buttons that require the shield drawn.

The full updated code from Part 1: Download IconUAC Code 3 (10.13 KB)

Tip #8: Make Firefox Better

What I want from a browser

  1. To show the pages correctly
  2. To show as much as possible from a page (to remove the need of scrolling)
  3. To provide me with an easy way of accessing pages.

What I don’t like at Firefox

  • The search bar is superfluous. I really like what Chrome is doing (and the latest version of Opera?): use the address bar as search bar.
  • There is no ad blocker
  • There is a lot of wasted space: bookmarks toolbar, menu bar (just think how often you use the top menu), big icons

After a few tweaks I got a browser looking like the one in the picture below that satisfies almost all my needs.

Tweaks applied and how/why to use them

Read the rest of this entry »

Tip 2: #if

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 only tests whether the symbol has been defined or not.

A predefined (by default) symbol on the “Debug” build configuration is DEBUG. 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.

using System;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
#if DEBUG
            Console.WriteLine("Debugging information");
#endif
            Console.WriteLine("Code that always executes");
        }
    }
}

The code above will print “Debugging information” and “Code that always executes” when build on Debug and will display only “Code that always executes” when build on another configuration.

You can suppress the definition of the DEBUG symbol from the project properties or by removing the DEBUG from the build argument “/define:DEBUG”. Also, you can define your own symbols in order to accommodate your needs.

Define as many build configurations and symbols you need but don’t abuse this feature!

Windows Mobile 6.5 on Toshiba G900

aboutBefore writing anything else I must warn all readers that changing the operating systems on your mobile will void the warranty. If the upgrade process fails the phone might be damaged and no service will fix that for free. Do it on your own risk and make sure the following list is satisfied:

  • Ask people about the ROM you want to install. Make sure it did not brake any phone.
  • The phone’s battery must be at least 50% charged (better 100%)
  • Make sure you have and UPS. Or a laptop with good battery because if you cancel the process after it started the results might be unexpected.
  • Make sure the USB cable is firmly connect and is not broken!

I cannot be made responsible for any damages caused directly or indirectly by this article.

Read the rest of this entry »

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 »

First CodeProject article – WPFDesigner

Today I’ve posted my first article on CodeProject.

The article describes how to create a custom control in which you add elements and you can move/resize them.

The article can be found here.

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 »