SystemIcons.Shield

Sat, December 15, 2007, 06:42 AM under dotNET | Windows | Vista | UAC
Seasoned Windows Forms developers will be familiar with the System.Drawing.SystemIcons class that has a bunch of properties returning standard system icons. For example, if you throw on a form a picturebox and a button with its event handler the following code shows how you can take advantage of SystemIcons:
void button1_Click(System.Object sender, System.EventArgs e)
{
// use Error
pictureBox1.Image = Bitmap.FromHicon(SystemIcons.Error.Handle);

// use Warning
this.Icon = SystemIcons.Warning;

// use Information
int h = button1.ClientSize.Height / 2;
Icon ico = new Icon(SystemIcons.Information, h, h);
Bitmap bitmap1 = Bitmap.FromHicon(ico.Handle);
button1.Image = bitmap1;
button1.ImageAlign = ContentAlignment.MiddleLeft;
}
With Service Pack 1 of .NET Framework v2.0 we get a new member of that class: SystemIcons.Shield. So, if you are on Windows Vista and you are working with User Account Control, you may find it a useful icon to use (for example on a menu).

Below is a screenshot of what the code above looks like side by side, before clicking the button and after. The screenshot at the bottom is after replacing the 3 icons with shield:

Video: Build UAC aware apps with VS2008

Thu, August 23, 2007, 04:22 PM under Orcas | VisualStudio | UAC
One of the improvements in Visual Studio 2008 for building Windows Vista applications that work correctly with User Account Control is the ability to embed manifests in Visual Basic and C# projects. Watch my 15' video to see how.

More VS2008 UAC integration

Thu, August 2, 2007, 04:12 PM under Orcas | VisualStudio | UAC
I've shown before one example of VS2008 integrating nicely with UAC, but today I found another one:

The above dialog appeared after I tried creating a new SharePoint Workflow project. After selecting the "Restart" option, Visual Studio closed, I confirmed the UAC Consent dialog and VS then reopened elevated (with the title bar showing its mode) in the same state it was before.

If you find any other examples of actions that result in an elevation prompt in Visual Studio 2008, please drop me a line (other people collect stamps, I collect UAC screenshots).

UAC Settings in VB

Thu, August 2, 2007, 02:32 AM under Orcas | VisualStudio | UAC
Regular readers of my blog will know that a requirement (and more importantly good common sense) for your applications that will run on Vista is that they have an embedded manifest declaring their requested privilege for working better with UAC. With Beta 1 of VS2008 I showed how this has become a doddle for C# projects. At the time, there was no such easy option for VB projects.

With Beta 2, VB also gets an easy way to do this. If you find the GUI of the C# approach confusing, then you'll be pleased to find that the VB approach is a single button named View UAC Settings, as per the following screenshot:

Clicking on it adds a pre-populated manifest file to your project which you can optionally further tweak to your liking, of course.

Note that in C#, you can manually add Application Manifest Files yourself:

...and switch between them from the IDE. This does not seem possible from the GUI provided by the VB team.

Further note that this feature is obviously applicable for v2.0, v3.0 and v3.5 client project templates in both languages. My advice to you is to open all your client projects in VS2008 and embed the default manifest now with no further thought. Later you can determine if you need to tweak things...

VS2008 integration with UAC

Wed, June 20, 2007, 02:52 PM under Orcas | VisualStudio | UAC
You know that when you run VS2005 on Vista (even with SP1 and the SP1 update) you get advised to run elevated. You also know that VS2008 has better indication when you run it elevated.

What I haven't explicitly stated before is that VS2008 does not require you to run it elevated from the start. Instead it is a good Vista client and plays nicely with UAC by only prompting you to restart the IDE when you truly need to. For some type of projects this will equate to always run elevated of course, but it is good that it doesn't force this behaviour on all of us and that it offers to do it for you as needed.

Recently I discovered one scenario where it plays nicely. I double clicked on a solution file in explorer and because it was in a place requiring admin rights, I got the following dialog from VS2008


This is cool (even though I suspect the final text will be slightly different as there are a couple of errors there e.g. UAC = User Account Control).­­­­­­­­­­­­­

Programmatically determine if UAC is enabled

Thu, April 26, 2007, 07:38 PM under Windows | Vista | UAC
This is a question I get often:
"How can I determine if User Account Control is on or off via code?"
The answer I always give:
"You are asking the wrong question. Who cares?"
The point being that, regardless of whether the user has turned off UAC or not, your application should still be partitioned and work correctly for both admins and non-admin users. It is irrelevant if UAC is on or off. You should still display the shields, you should still gracefully fail if the user is not an admin (same as you would if the elevation prompt came up and the user cancelled, same as you should if you were running on XP). The academic answer to the original question is that you can read it from the registry (much like the built-in Security Centre does). Since there is no genuine requirement to know this stuff from code, there is no API for it.

So the only question to answer programmatically is how to know if the user has admin rights. I have shown how to do this before but here goes again:
 // using System.Security.Principle;
private bool IsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal p = new WindowsPrincipal(id);

return p.IsInRole("Administrators");
}
I have read blogs where others get further information regarding elevation about the user's account by pinvoking native APIs, but again, I remain totally unconvinced about that need. Your app shouldn't care about anything else: all that matters is if the user has admin rights at the moment your admin code is about to execute, nothing else.

If you disagree and think you have a genuine reason for knowing more than what I describe above, then please post your scenario to the relevant forum linked to from here.

UAC Elevation with COM

Thu, April 19, 2007, 01:05 PM under Windows | Vista | UAC
You've probably read my posts on UAC (tip: read bottom up), and in my talks I always explain how to factor out into separate processes any admin functionality.

What I've never explained is how to factor into out-of-proc COM objects the admin functionality. Christoph has explained that on his blog and has done it all in managed code no less! Check his posts out starting here (and follow his links for the rest).

Embedding manifests in Orcas

Tue, March 6, 2007, 04:45 AM under Orcas | VisualStudio | UAC
The first thing you should do with your applications on Windows Vista (and indeed a logo certification requirement) is embed a manifest in your application that effectively tells Windows that your app is aware of User Account Control. I have explained how to do this with VS2005 here. Also Catherine listed a few ways here. Bottom line: create a manifest like this, and embed it in your project with a post-build command: "$(DevEnvDir)..\..\Common7\Tools\Bin\mt.exe" -manifest "$(ProjectDir)$(TargetName).exe.manifest" –outputresource:"$(TargetDir)$(TargetFileName)";#1

In VS Orcas C# projects, life becomes slightly easier. Effectively, there is a combobox under the Application tab in the project properties that allows you to point to a manifest and then it will embed it in the application. I cannot find this option in VB projects yet.

To me, there isn't much difference between pasting the command line from further above in the post build box and instead choosing a combobox item. However the latter does have the advantage of being more discoverable :-)

UPDATE: FYI, I got the below from Saurabh Jain (a dev on the team responsible) with regards to the March CTP:
"There is more support for manifests then you might see.

Firstly, the compilers have new switches for manifest, so there is no post build event.

C:\>csc.exe /? | findstr -i man
/win32manifest:<file>   Specify a Win32 manifest file (.xml)
/nowin32manifest        Do not include the default Win32 manifest
Secondly, if you have a .manifest file in your project, that file will appear in the dropdown. You can then select the file, and it will be passed to compiler. This is how one can add a custom manifest file."

Administrator in VS Orcas title bar

Mon, March 5, 2007, 04:11 AM under Orcas | VisualStudio | UAC
Anyone running on Vista knows about the new security feature of UAC. A known trick is to right click on a command window shortcut and select "Run As Administrator" to get an elevated command window.


Following that, anything you launch from the elevated cmd will also be elevated. Of course this can be dangerous so when a command window is elevated, it is prefixed with the word "Administrator" (so you can distinguish it from non-elevated command windows).


No other window on Vista will tell you in its caption that it is running as administrator. The reason for that is that you will not typically run an interactive process elevated for a long period of time plus most apps cannot do the accidental damage that an elevated cmd window can. Of course each application developer can decide for their own app what they want to do.

The VS Orcas team decided that they wanted to differentiate an elevated VS instance from a non-elevated instance. They do this by appending a "(Administrator)" string on the title as the following screenshot shows:


I like this, although I would have also liked some consistency between cmd and VS and in fact maybe some official Windows guideline that all apps follow.

Launch elevated and modal too

Fri, December 15, 2006, 01:22 AM under Windows | Vista | UAC
Those of you that have attended my talks on UAC will have seen the demo where we extract a process and run it elevated (i.e. an elevation prompt requires the consent of the user). Here I want to add some extra juice to that one.

For the rest of you, basically, if you have some admin task in your application that you cannot redesign (i.e. get rid of), you still should not mandate that your whole application runs elevated (i.e. requires admin privileges). Instead, you should refactor that functionality in a separate process. When you require the use of that admin functionality from your main application, launch the other process elevated to do the work for you. There are a few ways you can launch the application elevated but the best one in this case is to manifest the application. An example of a manifest is here; change the level from asInvoker to requireAdministrator. Embed it in your project by pasting the following line in the “Post-build event command line” textbox of the project properties:
"$(DevEnvDir)..\..\Common7\Tools\Bin\mt.exe" -manifest "$(ProjectDir)$(TargetName).exe.manifest" –outputresource:"$(TargetDir)$(TargetFileName)";#1

So what is the extra juice I want to add in this post? Well there are two things that were nagging me with the way I showed how to launch the process.

One was that the UAC consent dialog that comes up was not modal to the main application (since it was being launched for another application). By default you do not observe this but since in my setup I have disabled the policy “Switch to the secure desktop when prompting for elevation”, it affects me [NOTE: I do not recommend you disable that policy, it just happens that I have it like that for historical irrelevant reasons]. I was tipped-off that to make the UAC dialog modal, you must pass to the ShellExecute call the handle of the main app.

The other thing I didn’t like was that if the process we launch elevated has its own UI, then that is also not modal to the application.

So here is the code that addresses both of the issues above:
private void LaunchElevatedProcess()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true; // default, but be explicit
startInfo.WorkingDirectory = Environment.CurrentDirectory; //or other if you prefer
startInfo.FileName = @"some_path_to.exe";

//// if the other process did not have a manifest
//// then force it to run elevated
//startInfo.Verb = "runas";

// Two lines below make the UAC dialog modal to this app
startInfo.ErrorDialog = true;
startInfo.ErrorDialogParentHandle = this.Handle;


try
{
Process p = Process.Start(startInfo);

// block this UI until the launched process exits
// I.e. make it modal
p.WaitForExit();

}
catch(Exception ex)
{
// user cancelled
MessageBox.Show(ex.Message, "caught it!"); //for demo purposes
return;
}
}

Enjoy :)

UAC: Get your links here!

Mon, November 27, 2006, 06:05 AM under Windows | Vista | UAC
Unsurprisingly, after my UAC talk this morning (that I mentioned here), there was a lot of interest and I promised to publish helpful UAC links (in addition to previous mentions on this blog here, here and here). True to my promise, find them below!

1. Understanding the feature before jumping to questions is important. Don't take anything I say as gospel (always a dangerous tactic!) and instead read the official word:

- Short what is it by security MVP on technet.

- UAC for developers (written during Beta 1 but still valid)... and an updated one here.

- UAC for IT Professionals (surprisingly even though I am a developer, I found it quite interesting).

- UAC 91 page document for developers is available for download (a must read).

- The COM Elevation Moniker (all you want to know and more)

2. Now that you understand the feature, start testing your applications as standard user on Windows XP. If it works there, from a UAC point of view, it will work on Vista.

- Standard User Analyzer tool... requires the Application Verifier.

- Get the Application Compatibility Toolkit (ACT) 5.0

3. A lot of the compatibility issues are relevant to installations.

- UAC in MSI blog.

- MSI Patching Technology (tip: explore the other links from the tree on the left).

4. Related topics that I received questions on and promised I'd provide links to
- IE7 Protected Mode on Vista.
- Service changes in Vista.

5. Still got questions? Get them answered using the resources below:
- Even though it is now closed, there is good content on the UAC blog.

- Still active and open to questions is the Vista Security blog.

- When all else fails, first check the msdn forums where you can post any question you like:
* MSDN forum, security for applications.
* MSDN forum, app compat on Vista.

6. For your non-technical, non-developer friend:
For a non-technical plain English version of the UAC story (as plain English as the topic can get) this isn't bad and it also is not an official Microsoft explanation but it makes good reading!

I provided other generic Vista links a while back, and Karl just dropped me a line telling me about their community site that looks interesting: AeroXperience.

Vista: UAC internals

Sun, October 8, 2006, 03:15 AM under Windows | Vista | UAC
I have explained before what you (a managed developer) has to do about User Account Control in Vista (and also expanded a bit on UAC policies).

The other day I got asked exactly how this works under the covers. Luckily, my mate Kenny covers this on his article (butchered quote):
When an administrator logs on to a computer ... the system ... creates ... two different tokens representing the same logon session. The first token grants all the permissions and privileges afforded to the administrator while the second token is a restricted token ... offering far fewer permissions and privileges. ... The system then creates the shell application using the restricted token.

Follow this link for the full unedited story.

Vista UAC Security Policies

Mon, September 4, 2006, 05:20 PM under Windows | Vista | UAC
In the office today I was reading a popular PC magasine here in the UK and in the contents it said Dave (sorry I forget surname) looks at User Account Control in Windows Vista. I went to the page and read the article that left me quite disappointed. First, it doesn't really explain the goals behind UAC and how UAC achieves that: this information is available online (two clicks from my blog entry on User Account Control). Second, over half of the article is basically what seems to me a rant on the 'virtualization' feature (again, I cover virtualization on my UAC post). While I advise devs not to take advantage of virtualisation, I understand its purpose in offering crutches to some legacy applications that would otherwise break. In any case, the most disappointing thing about the article was that it didn't even mention how to turn off virtualization. While I did this at the nugget I link to from here, let's repeat it in written form.

1. In your Windows start menu go to the search box and type "sec" to bring up the "Local Security Policy"
2. Navigate to 'Security Settings->Local Policies->Security Options' and scroll to the bottom.
3. There you'll find 9 policies pertaining to User Account Control. Double click on the last one ("Virtualize file and registry write failures to per-user locations")
4. Change the value from Enabled to Disabled

With Vista RC1 there is an improvement to the dialogs that come up for each policy. There is an additional tab: "Explain". Click on this one to read about what the policy does :-) For the policy we've been talking about it looks like this:



I leave it to you to read the explanations for the other 8 policies:
- Switch to the secure desktop when prompting for elevation
- Run all users, including administrators, as standard users
- Only elevate UIAccess applications that are installed in secure locations
- Only elevate executables that are signed and validated
- Detect application installations and prompt for elevation
- Behavior of the elevation prompt for standard users
- Behavior of the elevation prompt for administrators in Admin Approval Mode
- Admin Approval Mode for the Built-in Administrator account

BTW, with RC1 (build 5600), the number of UAC prompts you get is significantly smaller than earlier builds so go check it out!

Vista: User Account Control

Sat, July 29, 2006, 02:30 PM under Windows | Vista | UAC
You, yes *you*, may not be gearing up to Windows Vista just yet but there is one core security element of Vista that IMO you must understand as soon as possible, and start working for it today on whatever Windows OS you are on. The feature in question is User Account Control. Please follow the links from item 5 here (it allows me a central place for updating resources).

Now that you've read those, I hope you understand UAC. In essence, when you set up user accounts on Vista, even if you set some of them as administrator, all interactive processes will run as standard user! The benefit is that any malicious code that gets on the user's machine also runs as standard user. If your applications require administrator privileges for some features, they will basically break on Vista (oversimplification aimed to scare you, but essentially true if you choose to ignore understanding UAC).

To work with this security feature, you must understand elevation, shields, virtualisation and security configuration options plus what you need to do programmatically for you applications to run on Vista. So, watch my nugget here or download it here to get the full picture...

There is one important bit of UAC that I do not cover in that short video (due to time): manifests. So after you’ve watched the video, come back and continue reading…

Fundamentally, on Vista you should declare that your app is aware of UAC (logo certification requirement). To do that you must embed a manifest in your application. Here are the steps on how to do that for managed applications in Visual Studio 2005 on Windows Vista:

1. Add to your VS2005 C# project this manifest file (replacing MyProjectNamewith your actual project name). Open the file in notepad and replace MyProjectNamewith your actual project name, same for description and Version.
2. Add this rc file to your project (replacing MyProjectName with your actual project name and removing the .txt extension). Open it with notepad and change MyProjectName to your actual project name.
3. Open your project file (csproj) in your favorite XML editor, scroll to the bottom and add/paste the following just before the closing Project element (replacing MyProjectNamewith your actual project name):
<propertygroup>
<win32resource>MyProjectName.res</win32resource>
</propertygroup>
<propertygroup>
<prebuildevent>"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\rc.exe" "$(ProjectDir)$(ProjectName).rc"</prebuildevent>
</propertygroup>

4. Rebuild!

The big clue that this has worked for you, apart from no compilation errors, is that virtualization gets turned off for your app (regardless of the security policy setting, which I show in my nugget). Try writing to HKLM and watch it fail with the manifest and succeed without.

If you change the level attribute of the requestedExecutionLevel element in the manifest from asInvoker to requireAdministrator, then you'll get the elevation prompt at startup (do this only if your app is explicitly aimed at administrators).
--
UPDATE: Also see this