Tag Archives: Code

.NET Wrapper for COM Elevation

Microsoft has ramped up the security in their latest operating system – Windows Vista, which means that developers now have to pay more attention to certain security constraints imposed by the operating system when developing applications.   Those of you readers who have read my prior posts on User Access Control in Vista (and the further reading article), may be interested in this small software project I put together. 

The Problem in a Nutshell

Vista requires that ALL users (even administrators) obtain an elevated security token before being permitted to execute protected API calls or accessing protected system resources (the registry for example).  In prior versions of Windows, system administrators were given a privileged security token at login and permitted to perform any task without further confirmation from the interactive user.  Windows Vista now allocates a low security token by default to all users and administrators, and an elevated token is only obtained with credentials (users) or confirmation (administrators) when required.

Elevation request is determined by Vista before any process is loaded – so if a particular process is running non-elevated then access to protected resources and APIs within that process is denied.  This is an important caveat, as it affects the way in which software developers approach application design.

How does one Elevate their Process?

There are several articles on the Internet about developing elevated processes in Vista, so I’ll not dwell on the steps here (my previous articles cover this subject), but essentially elevation request involves decorating .NET assemblies and WIN32 executables with elevation status in the application manifest file (may be embedded or side-by-side).

The COM Elevation Moniker is another method for obtaining elevation.  Using the CEM it is possible to host a COM (Component Object Model) component in elevated state using the dedicated system process – DLLHost.exe.  The Windows Vista SDK provides details on adding the necessary code to your project to elevate an out-of-proc component and making it available to your non-elevated application.

So why use the COM Elevation Moniker?

The CEM permits a non-elevated process to execute protected API calls and access protected resources by calling across process boundaries into an elevated process.  This is how Vista achieves mid-application elevation – look for the shield symbols in forms and property pages, to get an idea of what I am talking about. 

So what’s the big deal?

Development of a CEM component typically involves some work in C++.  Development of COM components in VB and .NET is of course possible, but when it comes down to accessing WIN32 calls to perform COM elevation most of the examples are published in C++.  Developing a managed CEM is possible but involves some work to get it operating correctly.

What about cross boundary communication? – This is the klutz of the problem with authoring CEM components, how to communicate across process boundaries?  COM development answered this problem a long time ago, and the same is true now as it was then – marshalling data and cross process communication is handled by the COM infrastructure.  But what about managed code?  If you’ve managed to solve the problem of invoking a .NET assembly as a COM CEM component, you still have to communicate over .NET interop, which may not be ideal.

Surely someone must have a way to perform elevation in the managed world?

The .NET Wrapper for COM Elevation

I wanted a way for managed developers to attribute their code classes in such away that embedded methods of these classes would request elevation from the Vista operating system before execution of such methods.  So I went about developing a library to encapsulate the complexities of the COM Elevation Moniker.  The end result is available to download from here.

After downloading the ZIP files and unpacking it, the library is packaged as an MSI installer file, which must be installed as an administrator to make use of the library functionality.  The installer also installs some example code to demonstrate use of the library.

How does the Managed Wrapper Library Work?

Essentially, the wrapper library exists as a managed and non-managed server.  The non-managed COM server provides the infrastructure to elevate managed code by hosting it’s own .NET AppDomain.  The managed server assembly is loaded into the elevated AppDomain and executes code developed by the end user of my library.

Communication between the hosted managed server and client code is achieved using an IPC (Inter-Process Communication) channel developed against WCF (Windows Communication Foundation).  The exact specifics of this set up is beyond the scope of this blog post, but involves the use of CodeDOM (dynamic code generation) to create a dynamic messaging system between elevated code and non-elevated client proxy. 

My wrapper library is very much “beta” at present.  I’ve published my library in the hope that I can attract a number of developers to use it and let me know their initial thoughts.  Documentation is sparse, but I am working on publishing a technical manual. It is important to understand that end-users of my library require no knowledge of WCF development, C++, or COM expertise, which makes my library versatile and easy to use by managed developers of different skill-level.

For now, I’ll end this post with a thank-you – for taking an interest in my project.  I look forward to receiving feedback (good and bad), especially any pertaining to security aspects.

Pass by Reference

Contrary to the beliefs of some developers, .Net reference types do not need to be passed as reference parameters (ref in C#, ByRef in VB) when a method is going to alter the contents of an object instance.

Passing a object reference by reference parameter just means the method can reassign the reference to a new object instance. The following reference parameter shown below is unnecessary:

class foo
public int i;

… void fooMethod(ref foo fooInst)
fooInst.i = 10;

.Net is smart enough to pass object instances using address – not the whole object across the stack. In C++ land, the parameter should be passed as a pointer or explicit reference (using &).

Failed to open XML parser COM object.

I came across a problem when launching any PPC emulator through Visual Studio’s Device Emulator Manager – I’d receive an error of the sort: Failed to open XML parser COM object.

After digging around Google for a while I found the problem was related to a missing installation of MSXML Parser Version 3 (why MS are not using MSXML6 I do not know).

If you have the DLL on your PC the following command should solve the problem -:

regsvr32 %windir%system32msxml3.dll

If you’re missing the DLL the parser can be downloaded from Microsoft.

C# Value Types and Ranges

Just because it’s good to know…..






true and false



0 to 255



-128 to 127



-32768 to 32767



0 to 65535



-2,147,483,648 to 2,147,483,647



0 to 4,294,967,295



-9,223,372,036,854,775,808 to



0 to 18,446,744,073,709,551,615



to 79,228,162,514,264,337,593,543,950,335



-1.79769313486232e308 to



-3.402823e38 to 3.402823e38



0 to 65535

Code Access Security – A Primer


This post serves as a primer for software developers interested in learning about Code Access Security (CAS) in .NET. The following information is not exhaustive of the subject matter and contains the basic overview of Code-Access-Security. Those interested in this subject are encouraged to read further.

The following articles cover code security and are a good follow-up to this post.




Shawn Farkas is one of many experts on Code Access Security, and as well as the author of many magazines, he posts regularly on his weblog:



What is Code Access Security?

Most computer users and security experts are accustomed to Role-Based Security (RBS), where particular users belong to specific groups, assigned permissions to protected resources. Windows XP/2003, SQL Server, IIS, and a host of server applications use Role-Based Security to provide access protection.

Code Access Security is different to Role-Based Security in that it restricts access to protected resources at the code level. Coming from a role-based way of thinking, code access security can be a confusing concept because there is no user attempting access in the typical sense. Code Access Security defines a set of permissions and the policy, which defines assignment of those permissions, by evaluating the evidence belonging to the code requesting access.


Why should we care about Code Access Security?

Typically, software development and security roles are very distinctive:

Software developers create software to run on workstations and servers, and security experts lock down access at the user level to these workstations and servers.

The above approach has been in place for as long as developers have been creating software and the software has been manipulating secured data; however, this methodology has a few flaws:

  • Deployment of software in the above scheme is troublesome – developers are used to writing and testing software with a full set of permissions. When deploying software, developed in this fashion, in a locked-down environment, the software often fails.
  • The best software developers are not always the best security experts, and vice versa. Software developers hate to work through security constraints and security experts often like to lock down systems to the point where they are sometimes unusable.

Code Access Security is a new way of thinking. Just as industry has learned that performance is not a last minute consideration in the software development lifecycle, neither is security. Code Access Security prevents malicious code penetrating secure systems by detecting insecure code before it executes, and potential security holes be pinpointed to code modules that demand a higher permission set.

With Code Access Security, you can:

  • Restrict what code can do
  • Restrict who can call code
  • Identify code

Code Access Security works hand-in-hand with security design and threat modeling, in that any .NET assembly can be marked as “security transparent.” Security transparent assemblies contain code that does not access protected resources, and is safe to operate in partial trust environments. More on security transport assemblies later in this post.

Some environments, in which custom code may execute, are partial trust. Microsoft guidelines suggest that all ASP.NET installations hosting multiple applications be set at medium trust to guarantee autonomy. Developers writing code for hosted environments will have no choice but to make sure their code runs at ASP.NET medium trust level. The next version of SharePoint (Office 12 Server and WSS 3.0) operates at partial trust out of the box.


The Fundamentals

As mentioned in the previous section, Code Access Security does not use user or role identification, so how does Code Access Security in .NET work?

Before execution of verifiable code, the .NET platform determines if the code has permission to complete its function successfully. This process involves collecting information about the code – evidence, determining the required permissions to complete execution by obtaining the current policy for the enterprise/machine/user/app domain. The list below further documents the main constituents to Code Access Security:

  • Evidence is a set of attributes that belong to code. For example, certain .NET assemblies may be strong named and have a particular public key token. Other assemblies may have originated via “Click Once Deployment” at a certain web address, or reside within a particular directory on the file system.

  • Permissions represent access to a protected resource or the ability to perform a protected operation. The .NET Framework provides a number of classes that represent different permissions. For example, if some code needs access to files on disk then a FileIOPermission is required; the ReflectionPermission is required for any code that attempts to perform refection, etc.

  • Permission Set is a collection of permissions. The system defines several permission sets and different assemblies in a .NET application may fall into zero, one or more of these permission sets. The Framework defines a number of default permission sets, including “Full Trust” – a set that contains all permissions, and “Nothing” – a set that contains no permissions.

  • Code Group is mapping of evidence to permission sets. Code groups combine to form a tree where code must exhibit the desired evidence to satisfy membership of the group.
  • Security Policy is a configurable set of rules that the CLR follows when determining the permissions to grant to code. There exist four independent policy levels:

  • Enterprise – All managed code in an enterprise setting
  • Machine – All managed code on a single computer
  • User – Managed code in all processes associated with the current user
  • Application Domain – Managed code in the host’s application domain

What about ASP.NET?

ASP.NET builds atop of Code Access Security and provides five permission sets; each set depicted as a trust level:

  • Full
  • High
  • Medium
  • Low
  • Minimal

Each trust level above contains permissions, ranging from a complete set of permissions – “Full” trust – to limited permissions – “Minimal” trust.

A separate policy configuration file exists for each trust level and packaged with the ASP.NET installation. An ASP.NET application stipulates the level of trust and location of policy file in the application configuration file (web.config):

<trustLevel name=”High” policyFile=”web_hightrust.config”/>

Applications that operate in partial trust (not full trust) and require elevated permissions can run in a higher trust level or by defining custom permissions in a new policy file. If an application only requires a handful of permissions, not present at the current trust level, then it makes sense to define a custom policy and permission set. Increasing the trust level may add many more permissions not required by the application, creating security vulnerability.


Applying Code Access Security

Two different kinds of syntax are available when adding Code Access Security to code: declarative and imperative.

Declarative syntax involves applying attributes to methods, classes, or assemblies. The “Just-in-Time” (JIT) compiler reads meta-data generated from these attributes to evaluate these calls.

[FileIOPermission(SecurityAction.Demand, Unrestricted=true)]

public class Foo { … }

Imperative syntax involves the use of method calls to create instances of security classes at runtime.

public class Foo


public void MethodOne(..)


new FileIOPermission(PermissionState.Unrestricted).Demand();



Both of the examples above are requesting unrestricted access to the file system. Most of the security permission classes in the .NET framework provide properties to customize the level of access; the FileIOPermission includes properties to permit read/write access to particular files and directories in the file system. The example below permits all access to a particular file by changing the parameters passed to the constructor:

new FileIOPermission(FileIOPermissionAccess.AllAccess,”C:Test.txt”).Demand();

So, what happens when code declares a security permission attribute or instantiates a new permission class imperatively?

All three examples above call a “demand” on the desired permission class. The demand instructs the CLR to walk the call stack of the current process making sure that each method call has the desired permission requested. If one of the calling methods in the stack does not have the permission then the CLR throws a security exception.

Most of the classes in the .NET Framework demand (or link demand) permissions when accessing protected resources. If a developer writes code that uses one of the framework classes, say to access a database or perform reflection, and the developer’s code is running in partial trust, then the developer’s code must the desired permission, otherwise the CLR will throw a security exception.

By default, any code developed against the .NET framework runs as “full trust.” except in the following cases:

  • The developer explicitly creates a sandbox application domain with partial trust
  • Configures application assemblies as partial trust using the .NET Framework Configuration tool
  • Runs the application code in ASP.NET at a trust level other than full
  • Is running the code in some other host application preconfigured to partial trust
  • The code is executed across a network

When operating at “full trust” all security demands made by classes in the framework (or by custom developer classes that are security aware) succeed. Only during deployment to a partial trust environment is there a problem. Developers should get in the habit of developing under partial trust when developing code that access protected resources.

Permission demand is one of several actions that applicable to permission classes, other actions available are:

  • SecurityAction.Demand – All callers higher in the call stack must have the permission specified by the current permission object.

  • SecurityAction.LinkDemand –Only the immediate caller in the call stack must have the permission specified by the current permission object.

  • SecurityAction.InheritanceDemand – Derived classes or overriding methods must have the permission specified by the current permission object.

  • SecurityAction.Assert – If the calling code has the desired permission then the stack walk for permission check stops. Use asserts only when encapsulating code that is known to be secure because callers further up the stack running in partial trust may not be aware of a demand further down the chain. Code containing asserts without the actual permission will allow permission checking to continue up the call stack.

  • SecurityAction.Deny – Callers cannot access a protected resource specified by the permission, even if the caller has permission to access the resource. So if a method in the call stack specifies a deny action and a method further down the chain attempts to access the resource, regardless of whether they have the permission, the method lower in the call stack will fail access.

  • SecurityAction.PermitOnly – Link a deny action only a permit only action specifies that the caller is denied access to all resources except for those defined in the current permission object. Further definition of this action is beyond the scope of this post.

  • SecurityAction.RequestMinimum – Only used within the scope of an assembly, this action defines the set of minimum permissions required for the assembly to execute.

  • SecurityAction.RequestOptional – Only used within the scope of an assembly, this action defines the set of permissions optional to execute (not required).

  • SecurityAction.RequestRefuse – Only used within the scope of an assembly, this action defines a set of permissions that may be requested and misused, and should therefore never be granted, even if the current security policy allows it. Further definition of this action is beyond the scope of this post.

Asserts deserve special consideration because they prevent permission demands from reaching callers higher in the call stack. Asserts are useful when a method is required to call some code that demands higher permission and the caller of the method is in partial trust. For example, a trusted custom assembly with elevated trust could call out to the file system using one of the framework API calls; the framework will demand a FileIOPermission, which must not propagate beyond the level of the custom assembly. Placing assert code around the call to the file system API will ensure that that demand never leaves the scope of the method containing the assert code. The custom assembly must have the FileIOPermission, otherwise the assert code is ignored and demands will continue up the stack to partial trusted code. The following is an example of an assertion code around a call to a method, which demands security permission. Notice the revert call at the end of the code, this revert will cancel the assert code. It is important to limit the scope of assertion so to avoid creating a security vulnerability, place only the code that requires the security permission between the assert call and the revert call.

new FileIOPermission(PermissionState.Unrestricted).Assert();

// Do something that causes a FileIOPermission



Transparent Assemblies

Transparent assemblies are .NET assemblies that are free from security critical code. The .NET Framework 2.0 enables developers to define assemblies as transparent so that security audits can rule out these assemblies as potentially security vulnerable. Transparent assemblies voluntarily give up the ability to elevate the permissions of the call stack, and the following rules apply:

  • Transparent code cannot asset for permissions to stop a stack walk from continuing
  • Transparent code cannot satisfy a link demand
  • Unverifiable code is forbidden in transparent assemblies
  • Calls to P/Invoke or unmanaged code will cause a security permission demand

Security transparent assemblies run either at the permission level granted, or at the permission level of the caller, whichever is less.

By default, all assemblies are security critical – the opposite of security transparent – but made into a transparent assembly by adding the following attribute at the assembly level:


The CLR throws a security exception if a transparent assembly attempts to elevate permissions. In cases where the developer wants to make the entire assembly as transparent, except for a few methods, use the following attribute:


The attribute named above is a little misleading in that it marks the entire assembly as transparent but allows security critical code. Decorate methods that require elevated as follows:


public void foo()


new FileIOPermission(PermissionState.Unrestricted).Demand();




Allowing Partially Trusted Callers

By default, strongly named, trusted assemblies obtain an implicit link demand for full trust on every public method of every publicly available class within the assembly. The CLR performs this insertion to protect fully trusted assemblies from misused by attackers. For example, a trusted assembly may have full access to loading a disk file. An attacker realizes that the assembly has not been security audited, and can manipulate the file loaded. The implicit link demand ensures that the attacker cannot execute the method if not running in full trust.

Assuming developers have security audited their code and want to allow partially trusted callers to call a full trusted assembly – the “Allow Partially Trusted Callers Attribute” (APTCA) enables developers to suppress the implicit link demand:

[assembly: AllowPartiallyTrustedCallers]

Developers should take the utmost care when enabling partially trusted callers to call trusted assemblies.

Some APTCA assemblies may still demand or link demand explicit permissions, in which case the addition of the APTCA does not remove the explicit demands, and a security exception generated in partially trusted code.

Right-Click ListBox – Select Item

Useful to know – to select items in a ListBox with a right mouse click wire up the following code to the MouseDown event:

private void LB_MouseDown(object sender, MouseEventArgs e)
// Select item if right click.
if (MouseButtons.Right == e.Button)
Point pt = new Point(e.X, e.Y);
LB.SelectedIndex = LB.IndexFromPoint(pt);

Access modifiers on property get/set

To some I may be stating the obvious, but today I was happy to find out that C# lets you set a different access level on the get and set for a property. The example below will help to illustrate what I’m talking about:

public DateTime UpdateDate
object data = ViewState[“UpdateDate”];
return (null == data ? DateTime.Now : (DateTime)data);
private set
ViewState[“UpdateDate”] = value;

Why on Earth would you want to do this? Well, I found a perfect situation where I needed the above code. I wanted to expose a property that is essentially read only to any callers that use it, but writable to the encapsulating class. In the above case, I do not use a private field to store the property value, but the ViewState instead (property is part of a server control class), the private set allows the class to write a value to the ViewState for the property.  Now, I could have written to the ViewState directly from my class and done away with the property set altogether, but this would have resulted in many statements throughout my class code.  This way, if I want to change the logic in how my property value is persisted I can make the necessary changes in one spot.  The alternative is to use a private set function, but a private property set is so much nicer. 🙂

HTTP SOAP Remoting Problem

I am developing a simple .NET remoting server using an HTTP channel and SOAP formatter, and ran into a problem earlier with invalid SOAP actions.  When invoking a method on a remoted object I was getting the following error message:

Unhandled Exception: System.Runtime.Remoting.RemotingException:
 Invalid SOAPAction specified: blah blah blah

After trawling the web for an hour I established that many other developers are running into the same problem.  Now that I’ve resolved the issue I wanted to share the solution with everyone else.

My simple remoting server is a MarshalByRef class, called MyAgent,
hosted in a Windows service.  The HTTP channel, SOAP formatter, and
exposed remoted class are configured in the service application
configuration file as follows.

        <application name=”RPCServer”>
                <wellknown mode=”SingleCall” type=”MyNamespace.MyAgent, MyAgentLib” objectUri=”MyAgent” />
                <channel port=”8050″ ref=”http”>
                        <formatter ref=”soap”/>

In my client application, I configure the HTTP channel, SOAP formatter, and remote service class as follows:

        <application name=”RPCClient”>
            <client url=”http://localhost:8050/RPCServer”>
                <wellknown type=”MyNamespace.MyAgent, MyAgentLib” url=”MyAgent”/>
                <channel ref=”http” port=”0″>
                        <formatter ref=”soap”/>

Originally, the MyAgent class
was a shared C# code file, compiled into both client and server
projects (in remoting, both client and server require the remoted class
type) – this worked fine in another remoting project I wrote, which
used IPC and TCP channels.  When using the HTTP channel and SOAP
provider this approach does not work (using HTTP and binary formatter
gave me a different cryptic error).  For some reason, the remoting
proxy (generated by the .NET remoting infrastructure) gets confused and
sees the client version of MyAgent class to be different to that of the MyAgent class hosted in the remote server.  To fix the problem I created a shared class library, called MyAgentLib, and included the MyAgent class. I then pointed both client and server projects to the shared class library.     Tada!

NOAA Weather Service and .NET

I have been fighting with the national weather web service, provided by the National Oceanic and Atmospheric Administration, today.  Like a lot of developers, who like to make their web sites fancy with the current weather forecast, I have been developing a component for the web site I am working on.

NOAA seems to be the norm for providing weather data in XML via the SOAP web service protocol.  Up until a couple of weeks ago, the C# code that I had to connect to the NOAA web service and pull weather data, was working  nicely….then it stopped – bah.  The proxy code (generated from the service WSDL by .NET) kept throwing an HTTP protocol violation exception:

Unhandled Exception: System.Net.WebException: Error getting response
stream (Rea dDone2): ReceiveFailure ---> System.Exception:
at System.Net.WebConnection.HandleError ()
at System.Net.WebConnection.ReadDone ()
at System.MulticastDelegate.invoke_void_IAsyncResult ()
at System.Net.Sockets.Socket+SocketAsyncResult.Complete ()
at System.Net.Sockets.Socket+Worker.Receive ()
at System.MulticastDelegate.invoke_void ()
in <0x000ad> System.Net.WebConnection:HandleError (WebExceptionStatus
st, System.Exception e, System.String where)--- End of inner exception
stack trace ---
in <0x00158> System.Net.HttpWebRequest:EndGetResponse (IAsyncResult
asyncResult)in <0x00047> System.Net.HttpWebRequest:GetResponse ()
in <0x0004d>
System.Web.Services.Protocols.WebClientProtocol:GetWebResponse (Sys
tem.Net.WebRequest request)

It seems that NOAA changed something involving their service protocol, because the response to a SOAP request is now being returned in separate chunked HTTP responses, which causes the .NET SOAP client to puke.

After some digging on the Internet (lots of digging in fact), I came across a post on a Mono newsgroup, which gave me a work around to the problem.  The trick is to change the web request in the SOAP proxy to use HTTP version 1.0 instead of 1.1.  Since HTTP 1.0 does not support chunked response, the NOAA server sends the response data as one block, which keeps the .NET SOAP client happy. 

Below is the code for my web service proxy, drop it into your project (assuming you use C#) and instantiate the WeatherProxy class from your code.  You’ll not need to add a web reference to your project because this proxy class is attributed with the correct SOAP envelope information.

/// Soap Format Type.
[SoapTypeAttribute(“formatType”, “http://weather.gov/forecasts/xml/DWMLgen/schema/ndfdXML.xsd”)]
public enum formatType
/// 24 Hour
[SoapEnumAttribute(“24 hourly”)]

/// 12 Hour
[SoapEnumAttribute(“12 hourly”)]

/// Proxy class for weather service.
/// Uses the NOAA web service, this proxy derived from an example found on the .NET. The proxy that
/// VS2005 generates causes a protocol error/HTTP 502 Bad Gateway.
[WebServiceBindingAttribute(Name = “ndfdXMLBinding”, Namespace = “http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl”)]
public class WeatherProxy : System.Web.Services.Protocols.SoapHttpClientProtocol
#region Construction

/// Constructor.
public WeatherProxy()
this.Url = “http://www.weather.gov/forecasts/xml/SOAP_server/ndfdXMLserver.php”;

#endregion Construction

#region Methods

/// Get the weather data by day (synchronously).
/// Latitude coord.
/// Longitude coord.
/// Start Date.
/// Number of days.
/// Time format.
/// Soap XML
[SoapRpcMethodAttribute(“http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgenByDay”, RequestNamespace = “http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl”, ResponseNamespace = “http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl”)]
[return: SoapElementAttribute(“dwmlByDayOut”)]
public string NDFDgenByDay(
Decimal latitude, Decimal longitude,
[SoapElementAttribute(DataType = “date”)] DateTime startDate,
int numDays, formatType format)
object[] results = this.Invoke(“NDFDgenByDay”, new object[] {
return ((string)(results[0]));

/// Creates a for the specified uri.
/// The .
/// The to use when creating the .
/// The uri parameter is null.
protected override WebRequest GetWebRequest(Uri uri)
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
request.ProtocolVersion = HttpVersion.Version10;
return request;

#endregion Methods