<July 2014>
SunMonTueWedThuFriSat
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

On this page...

Search

Links

Member of...


ASP Insiders

MVP Visual Developer ASP/ASP.NET

Enter CodeZone

Blog Categories

Microsoft

Blogroll

Deutsche Resourcen

Management

Sign In
 

#  Friday, February 16, 2007

In my last blog entry UAC Elevation in Managed Code: A .NET COM Component Elevated I showed how to get up and running with an all-managed code solution for UAC and COM elevation. Today I want close out my series on UAC with some information on how to properly organize the project plus present a library you can reuse to get up and running quickly - without many of the manual and tedious steps from the previous proof of concept example.

Speaking of the previous sample: it is still the basis for this best practice, so the following directory layout will look familiar to you:

Before diving into code, I want to start out with the SampleSetup directory, which contains the executables. As you can guess, the starting point is Step1Register. It contains register.bat, which you have to execute:

Note that on machines without the .NET Framework SDK, there is no gacutil.exe. In that case, you have to drag & drop ManagedElevator.dll to c:\windows\assembly.

And in case you have been wondering from this screenshot, yes, the application now also plays nicely on Windows XP:

Of course, there is no consent UI popping up, nor is there a shield icon like there is on Windows Vista:

The magic for this cross-platform functionality is hidden in the UACHelper project - which brings us to the source section of this blog post:

All the necessary COM elevation magic is now moved to this neat little library - including the adapted UAC bits of VistaBridgeLibrary (no longer necessary). The names already give away the purpose of each class and where they are used:

  • COMRegistration Used by the elevated component to automatically register the necessary registry keys.
  • ShieldButton Used by the client to display a button with a shield icon (on Vista). For XP, no shield is rendered.
  • COMElevation Starts the requested component with admin privileges.
  • ElevatedProcess If you want to start a simple process elevated. Not used in this guidance.

The first customer of this library is the elevated component, so we start discussing this guy next:

At first glance, this is similar to the previous POC implementation. The main difference now is that I have broken down the functionality by feature area into namespaces:

  • The "main" namespace
  • The .Components namespace
  • The .Guids namespace
  • The .InterOp namespace

Let's look at these one by one.

The "main" namespace

Here, we have one class only:

class RegisterFunctions
{
  [ComRegisterFunction]
  public static void CustomRegister(Type t)
  {
    COMRegistration.RegisterForElevation(Assembly.GetExecutingAssembly().Location,
       SampleComponent.ClassToElevate,
       Global.AppId,
       100);

    // add additional "for elevation" components here by duplicating the above
  }

  [ComUnregisterFunction]
  public static void CustomUnregister(Type t)
  {
    COMRegistration.UnRegisterFromElevation(Assembly.GetExecutingAssembly().Location,
        Global.AppId);
  }
}

It is called when the assembly is regasm'ed, and it is here where you call into COMRegistration.RegisterForElevation to add all the necessary registry keys for elevation:

public static void RegisterForElevation(string assemblyLocation,
    string classToElevate,
    string appId,
    int localizedStringId)
{
 if (!UACHelperFunctions.IsUACEnabledOS()) return;

 // [HKEY_CLASSES_ROOT\CLSID\{71E050A7-AF7F-42dd-BE00-BF955DDD13D4}]
 // "AppID"="{75AB90B0-8B9C-45c9-AC55-C53A9D718E1A}"
 // "LocalizedString"="@E:\\Daten\\Firma\\Konferenzen und Talks\\..."
 RegistryKey classKey = Registry.ClassesRoot.OpenSubKey(@"CLSID\{" + classToElevate + "}", true);
 classKey.SetValue("AppId", "{" + appId + "}", RegistryValueKind.String);
 classKey.SetValue("LocalizedString", "@" + assemblyLocation + ",-" + localizedStringId.ToString(), RegistryValueKind.String);

 // [HKEY_CLASSES_ROOT\CLSID\{71E050A7-AF7F-42dd-BE00-BF955DDD13D4}\Elevation]
 // "Enabled"=dword:00000001
 RegistryKey elevationKey = classKey.CreateSubKey("Elevation");
 elevationKey.SetValue("Enabled", 1, RegistryValueKind.DWord);
 elevationKey.Close();

 classKey.Close();

 // [HKEY_CLASSES_ROOT\AppID\{75AB90B0-8B9C-45c9-AC55-C53A9D718E1A}]
 // @="ManagedElevator"
 // "DllSurrogate"=""
 RegistryKey hkcrappId = Registry.ClassesRoot.OpenSubKey("AppID", true);
 RegistryKey appIdKey = hkcrappId.CreateSubKey("{" + appId + "}");
 appIdKey.SetValue(null, Path.GetFileNameWithoutExtension(assemblyLocation));
 appIdKey.SetValue("DllSurrogate", "", RegistryValueKind.String);
 appIdKey.Close();

 // [HKEY_CLASSES_ROOT\AppID\ManagedElevator.dll]
 // "AppID"="{75AB90B0-8B9C-45c9-AC55-C53A9D718E1A}"
 RegistryKey asmKey = hkcrappId.CreateSubKey(Path.GetFileName(assemblyLocation));
 asmKey.SetValue("AppID", "{" + appId + "}", RegistryValueKind.String);
 asmKey.Close();

 hkcrappId.Close();
}

Please take note that when the component is registered on eg Windows XP, no registry entries are written. After all, they are not needed.

The .Components namespace

Not much of a change - it contains the administrative component(s).

The .Guids namespace

The guids have been moved to a separate namespace. The reason? That way you can reference the assembly in the client project and use the guids directly - no magic strings anywhere any more.

The .InterOp namespace

This is the most important change with regards to the POC project - defining the correct ComImport'ed interface is now the responsibility of the implementer of the elevated component. That way, anyone needing access to this component only needs to reference the assembly and they are good to go. It is a bad idea to have this interface part of the client codebase!

Speaking of the client... here is the button code for DemoForm.cs:

private void cmdLaunch_Click(object sender, EventArgs e)
{
 if (UACHelperFunctions.IsUACEnabledOS())
 {
   IHelloWorld ihw = COMElevation.Start<IHelloWorld>(
        SampleComponent.ClassToElevate, SampleComponent.IHelloWorld);
   ihw.SayHello();
   COMElevation.Release(ihw);
 }
 else
 {
   ManagedElevator.Components.ClassToElevate c = new ManagedElevator.Components.ClassToElevate();
   c.SayHello();
 }
}

What looks interesting at first is COMElevation.Start as well as Release:

public class COMElevation
{
 public static TIFace Start<TIFace>(string IID_Class, string IID_Interface)
 {
  return Start<TIFace>(new Guid(IID_Class), new Guid(IID_Interface));
 }

 public static TIFace Start<TIFace>(Guid IID_Class, Guid IID_Interface)
 {
  object o = UACManager.LaunchElevatedCOMObject(IID_Class, IID_Interface);
  return (TIFace)o;
 }

 public static void Release(object o)
 {
  Marshal.ReleaseComObject(o);
 }
}

Actually all it does is encapsulate the necessary calls to UACManager and Marshal. Why is there no if / else using IsUACEnabledOS here? Well, at first I thought I'd build such a switch, but then I thought again: why would I use COM InterOp if I don't have to? I already referenced the assembly for the component (for the guids and interop interface), so why not use managed all the way and save time? That's what I did in the cmdLaunch_Click event handler.

That's it for the code folks, now a little discussion at the end on why in the world would you even think about doing this in a cross-platform way, or why it is a stupid idea all along:

This approach is only sensible if your application runs as administrative user on XP, otherwise all the calls in the administrative component will fail. However, the cross-platform part is only there to make it a complete best practice, there is no "you must use it cross-platform" - if you build applications for Windows Vista with the eventual need to elevate a task, then UACHelper is definitely for you! (and forget about that it would even work on XP)

Oh, and I almost forgot - here is the complete download, source code included of course (my code is BSD licensed):

AutomaticRegistration.zip (91.92 KB)

Categories: Security | UAC | Use the source Luke | Vista
Friday, February 16, 2007 8:02:29 AM (W. Europe Standard Time, UTC+01:00)  #    Comments [1]

 



© Copyright 2014 Christoph Wille

newtelligence dasBlog 2.3.9074.18820
Subscribe to this weblog's RSS feed with SharpReader, Radio Userland, NewsGator or any other aggregator listening on port 5335 by clicking this button.   RSS 2.0|Atom 1.0  Send mail to the author(s)

 
Don't contact us via this (fleischfalle@alphasierrapapa.com) email address.