Tip #22 – DynamicMethods in Partial Trust

The DynamicMethod class is in a part of the .NET Framework that not many people touch, even less so in partial trust. You may ask, then, why I bother to cover it. I have two reasons: it is a lower-level abstraction on which LINQ expression compilation is built (and therefore a building block for a future post), and enabling light-weight code generation in partial trust can be somewhat tricky.

DynamicMethods, as their name implies, are methods created at runtime that are associated with an existing module or type, or a transparent assembly provided by the framework (aka an anonymously hosted DynamicMethod). There are different considerations for each, so we’ll tackle them one at a time.

Existing Module or Type

DynamicMethods can be associated with existing .NET modules and types by using the appropriate constructor overload of DynamicMethod that accepts either a Module or a Type as an owner. Using one of these constructors allows you to create a method that is logically associated with that owner, which means it has access to any non-public members within that same scope. The MSDN documentation has a great example of how to use this functionality.

Unfortunately, this example fails in medium trust because of one of the many security checks that DynamicMethods do in the case when there is an existing owner:

  1. If the DynamicMethod is associated with a Type, then if it is invoked from a Type that does not match the owner, then ReflectionPermission/MemberAccess is demanded.
  2. If the DynamicMethod is associated with a Module, then if it invoked from an Assembly that does not match the owner Module’s Assembly, then ReflectionPermission/MemberAccess is demanded.
  3. If the skipVisibility constructor parameter is set to true, then ReflectionPermission/MemberAccess is demanded.

These restrictions make associating DynamicMethods with existing modules or types almost impossible in partial trust. But if you find that you still want to do this, you should find out about additional restrictions from Shawn’s blog on the topic. (For example, what stops me from associating methods with modules and types from .NET Framework assemblies?

Anonymously Hosted

The solution to the problems above is to place your DynamicMethods in an anonymously hosted security-transparent assembly provided by the .NET Framework. Doing this simply requires you not to specify an owner Module or Type in the constructor for the DynamicMethod.

This narrows down your constructor choice from eight to two; the only difference between them is a very interesting parameter called restrictedSkipVisibility.

When this parameter is set to false, the JIT compiler treats the DynamicMethod like any other method in your code; that is, it can access all public members in other assemblies. If the parameter is true, that means the DynamicMethod can access non-public members in other assemblies without using reflection. This feature is subject to the restriction that the accessed assemblies must have a trust level that is equal to or less than the trust level of the call stack that emits the dynamic method. This check is done only at JIT compilation time and not during subsequent invocations of the method.

If you’re familiar with ReflectionPermission/RestrictedMemberAccess this pattern of demand probably sounds familiar to you. In fact, the mechanism is largely the same with the interesting difference that the demand for the appropriate permission is done against the call stack that was present when the DynamicMethod was created. Let’s look at a couple of examples.

First, let’s look at the power of restrictedSkipVisibility. Below, I have declared an interface, ICalculator, with an internal implementation named PrivateCalculator.

[sourcecode language="csharp"]
public interface ICalculator
{
    int Add(int left, int right);
}

internal class PrivateCalculator : ICalculator
{
    public int Add(int left, int right)
    {
        Console.WriteLine("Inside PrivateCalculator.Add.");
        return left + right;
    }
}
[/sourcecode]

So far, so good. Now let’s create a dynamic method that manufactures ICalculator instances.

[sourcecode language="csharp"]
public class Program : MarshalByRefObject
{
    static void Main(string[] args)
    {
        var ps = new PermissionSet(PermissionState.None);
        ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.Infrastructure));
        ps.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

        AppDomain d = AppDomain.CreateDomain("Sandbox", null, new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory }, ps);

        var x = (Program)d.CreateInstanceAndUnwrap(typeof(Program).Assembly.FullName, typeof(Program).FullName);
        x.PartialTrustMain();
    }

    public void PartialTrustMain()
    {
        var dm = new DynamicMethod("CreatePrivateCalculator", typeof(ICalculator), Type.EmptyTypes, restrictedSkipVisibility: true);
        var ilGenerator = dm.GetILGenerator();

        ilGenerator.Emit(OpCodes.Newobj, typeof(PrivateCalculator).GetConstructor(Type.EmptyTypes));
        ilGenerator.Emit(OpCodes.Ret);

        var createCalculator = (Func<ICalculator>)dm.CreateDelegate(typeof(Func<ICalculator>));
        Console.WriteLine(createCalculator().Add(5, 7));
    }
}

[/sourcecode]

I include Main for completeness, but the real code of interest is inside PartialTrustMain, where I create an anonymously hosted DynamicMethod with restrictedSkipVisibility set to true. The method’s body simply creates a new instance of PrivateCalculator and returns it. Notice I am simply using the IL necessary to call the C# equivalent of "new PrivateCalculator()," and this compiles even though the method will not live in the same assembly as the PrivateCalculator class. If I removed the restrictedSkipVisibility parameter or set it to false, I would receive the following exception:

Unhandled Exception: System.MethodAccessException: Attempt by method ‘DynamicClass.CreatePrivateCalculator()’ to access method ‘CustomDynamicMethodSecurity.PrivateCalculator..ctor()’ failed.

   at CreatePrivateCalculator()

   at System.Func`1.Invoke()

   at CustomDynamicMethodSecurity.Program.PartialTrustMain()

   at CustomDynamicMethodSecurity.Program.PartialTrustMain()

   at CustomDynamicMethodSecurity.Program.Main(String[] args)

If we wanted to achieve the same thing without this parameter, we’d have to write the IL to generate calls against Activator.CreateInstance for the PrivateCalculator type, a verbose and error-prone set of lines to write by hand.

For the second example, let’s change the stakes a little bit. Let’s move ICalculator and PrivateCalculator to a separate assembly that is now fully trusted in the partial trust AppDomain. If we still try to create a PrivateCalculator using the DynamicMethod above, then we’ll encounter the same MethodAccessException that I pointed out earlier. Because PrivateCalculator is now in a fully trusted assembly, it requires full trust in order to create instances of PrivateCalculator from an anonymously hosted DynamicMethod. What else could we do?

Well it turns out we can move the creation of the DynamicMethod to a fully trusted assembly and then pass the delegate returned from DynamicMethod.CreateDelegate back to the console application to invoke. Let’s take a break here and look at the changes made to the code.

This is the console application:

[sourcecode language="csharp"]
public class Program : MarshalByRefObject
{
    static void Main(string[] args)
    {
        var ps = new PermissionSet(PermissionState.None);
        ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.Infrastructure));
        ps.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

        AppDomain d = AppDomain.CreateDomain(
            "Sandbox",
            null,
            new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory },
            ps,
            typeof(CalculatorUtils).Assembly.Evidence.GetHostEvidence<StrongName>());

        var x = (Program)d.CreateInstanceAndUnwrap(typeof(Program).Assembly.FullName, typeof(Program).FullName);
        x.PartialTrustMain();
    }

    public void PartialTrustMain()
    {
        var createCalculator = CalculatorUtils.CreatePrivateCalculatorFactory();
        Console.WriteLine(createCalculator().Add(5, 7));
    }
}

[/sourcecode]

And this is the fully trusted assembly:

[sourcecode language="csharp"]
public static class CalculatorUtils
{
    public static Func<ICalculator> CreatePrivateCalculatorFactory()
    {
        var dm = new DynamicMethod("CreatePrivateCalculator", typeof(ICalculator), Type.EmptyTypes, restrictedSkipVisibility: true);
        var ilGenerator = dm.GetILGenerator();

        ilGenerator.Emit(OpCodes.Newobj, typeof(PrivateCalculator).GetConstructor(Type.EmptyTypes));
        ilGenerator.Emit(OpCodes.Ret);

        return (Func<ICalculator>)dm.CreateDelegate(typeof(Func<ICalculator>));
    }
}

public interface ICalculator
{
    int Add(int left, int right);
}

internal class PrivateCalculator : ICalculator
{
    public int Add(int left, int right)
    {
        Console.WriteLine("Inside PrivateCalculator.Add.");
        return left + right;
    }
}

[/sourcecode]

But even with this code we have a problem. The call stack present when the DynamicMethod was created has some partially trusted code in it from the console application. So the last thing we need to do is apply an assert to CalculatorUtils.CreatePrivateCalculatorFactory that stops the stack walk from going into that partially trusted code. The final outcome:

[sourcecode language="csharp" padlinenumbers="true"]
public static class CalculatorUtils
{
    [SecuritySafeCritical]
    [ReflectionPermission(SecurityAction.Assert, MemberAccess = true)]
    public static Func<ICalculator> CreatePrivateCalculatorFactory()
    {
        var dm = new DynamicMethod("CreatePrivateCalculator", typeof(ICalculator), Type.EmptyTypes, restrictedSkipVisibility: true);
        var ilGenerator = dm.GetILGenerator();

        ilGenerator.Emit(OpCodes.Newobj, typeof(PrivateCalculator).GetConstructor(Type.EmptyTypes));
        ilGenerator.Emit(OpCodes.Ret);

        return (Func<ICalculator>)dm.CreateDelegate(typeof(Func<ICalculator>));
    }
}

[/sourcecode]

Now I should hope that it goes without saying but it’s very dangerous to pass around delegates created under an assert like this among class library boundaries. Treat them as radioactive if you must do this, and be sure to review your code for any possible exploitations where code might be able to invoke one of these delegates even though they should not be able to.

Next time, we’ll talk about expression compilation!

Tip #20 – Opting Out of Security Changes in .NET 4 in ASP.NET and Custom AppDomains

Legacy CAS Policy in ASP.NET

In a previous tip I discussed how you could re-enable CAS policy in applications running in .NET 4 by adding a switch to the application configuration file. However, Constantin Baciu brought up that even when using this configuration switch in a web.config, ASP.NET still threw the SecurityException:

This method explicitly uses CAS policy, which has been obsoleted by the .NET Framework. In order to enable CAS policy for compatibility reasons, please use the NetFx40_LegacySecurityPolicy configuration switch. Please see http://go.microsoft.com/fwlink/?LinkID=155570 for more information.

Definitely a confusing error message, since you already added the NetFx40_LegacySecurityPolicy configuration switch. The problem is that in order for this switch to actually work, it must be in the executable’s application configuration file. Putting in the web.config has no effect; the switch must be in the configuration file for the server executable, like IIS or Visual Studio’s local web server. Since just about all web hosts I know of won’t let you modify the configuration file for the server, we need a different option.

Fortunately, ASP.NET does support enabling CAS policy in .NET 4, but it’s with a different switch in the web.config. Enter the new legacyCasModel attribute of the trust element. This is the same element that allows you to configure the trust level of the application.

<trust legacyCasModel="true"/>

This enables you to get past the SecurityException above, but keep the following things in mind:

  • You will be using the legacy security configurations from .NET 3.5 when using ASP.NET. These permission sets are kept in the runtime directory’s Config folder and have names like legacy.web_mediumtrust.config and legacy.web_minimaltrust.config.
  • Security asserts are no longer required when only full trust code is on the call stack. This is because ASP.NET will still set up a fully trusted AppDomain, because it relies on CAS Policy to apply specific permissions to assemblies. In .NET 4 ASP.NET sets up a sandbox AppDomain by default, which means that even if only fully trusted code is on the call stack, as soon as a permission demand occurs, the stack walk will fail once it hits the AppDomain boundary.
  • Of course, CAS Policy is now enabled, which means the machine’s policy configuration affects what permissions an assembly has.

Legacy CAS Policy at the AppDomain Level

When you specify the legacyCasModel attribute in the web.config, ASP.NET uses that information to set up an AppDomain that has legacy CAS policy enabled. The good news is that by using some lower-level APIs, you can do the same thing.

You may ask "why would you want to do this?" One scenario I can think of is for an existing application that uses AppDomains to isolate other pieces of code (e.g. for add-ins), but some of these old pieces of code use the older security APIs that are obsolete in .NET 4.

The key API is AppDomainSetup.SetCompatibilitySwitches; remember that when setting up an AppDomain you can optionally use an instance of the AppDomainSetup class to initialize the AppDomain. The code example below shows how this is done.

C#

var setup = new AppDomainSetup

{

    ApplicationBase = Environment.CurrentDirectory

};

setup.SetCompatibilitySwitches(new[] { "NetFx40_LegacySecurityPolicy" });

 

AppDomain casPolicyEnabledDomain = AppDomain.CreateDomain("CAS Policy Enabled Domain", null, setup);

VB

Dim setup = New AppDomainSetup With {.ApplicationBase = Environment.CurrentDirectory}

setup.SetCompatibilitySwitches(New String() {"NetFx40_LegacySecurityPolicy"})

 

Dim casPolicyEnabledDomain As AppDomain = AppDomain.CreateDomain("CAS Policy Enabled Domain", Nothing, setup)

And that’s all there is to it. :)

CAS Policy on 64-bit Machines – #19

Well it’s been quite a while since my last post. I hope you all had a happy holiday season!

Today I’m going to talk about an issue I saw recently with a 64-bit machine and the partial trust tests for the Entity Framework. Even though .NET 4 disables CAS policy, it is more interesting for the Entity Framework to test with CAS policy enabled, because this allows us to configure security permissions on a per-assembly basis instead of per-AppDomain. The workflow for the tests is similar to the following:

  1. Enable CAS policy.
  2. Use the System.Security.Policy APIs to configure the correct set of permissions for the test assemblies. (Some have ReflectionPermission, some don’t, etc.) This is a separate EXE from the next step.
  3. Initialize the test harness and run the test cases.

When running in our lab recently, a few test cases failed for reasons I could not explain. Further analysis revealed that the tests were running in full trust, and so these negative test cases failed because the expected exceptions were not thrown. How did this happen?

Diagnosis

The first thing I did was to experiment with the command line switches of caspol.exe. I started a new command prompt and ran the following command. The –rsp switch stands for resolve permission set. System.Data.Test.PartialTrust.Caller.dll is the name of one of the assemblies that needs a custom permission set.

caspol.exe –rsp System.Data.Test.PartialTrust.Caller.dll

Microsoft (R) .NET Framework CasPol 4.0.21006.1
Copyright (c) Microsoft Corporation.  All rights reserved.

WARNING: The .NET Framework does not apply CAS policy by default. Any settings
shown or modified by CasPol will only affect applications that opt into using
CAS policy.

Please see http://go.microsoft.com/fwlink/?LinkId=131738 for more information.

Resolving permissions for level = Enterprise
Resolving permissions for level = Machine
Resolving permissions for level = User

Grant =
<PermissionSet class="System.Security.PermissionSet"
version="1"
Unrestricted="true"/>

Success

This had at least confirmed my suspicions that the tests were running in full trust. I looked back at the original executable code that configures the policy for the assemblies. It did not seem out of the ordinary, and besides, it had worked in many previous test runs.

C#

static void SetPermissions()

{

    // Find the machine policy level

    PolicyLevel machinePolicyLevel = null;

    IEnumerator ph = SecurityManager.PolicyHierarchy();

 

    while (ph.MoveNext())

    {

        PolicyLevel pl = (PolicyLevel)ph.Current;

        if (pl.Label == "Machine")

        {

            machinePolicyLevel = pl;

            break;

        }

    }

 

    NamedPermissionSet ps = new NamedPermissionSet("CallerPermSet", PermissionState.None);

 

    // Add permissions (omitted)

 

    StrongNamePublicKeyBlob key = typeof(Caller).Assembly.Evidence

      .OfType<StrongName>().First().PublicKey;

    IMembershipCondition mc = new StrongNameMembershipCondition(key, null, null);

 

    // Create the code group

    PolicyStatement policy = new PolicyStatement(ps, PolicyStatementAttribute.Exclusive);

 

    CodeGroup codeGroup = new UnionCodeGroup(mc, policy);

 

    codeGroup.Description = "Permissions for PT Caller";

    codeGroup.Name = "CallerGroup";

 

    // Add the code group

    machinePolicyLevel.RootCodeGroup.AddChild(codeGroup);

 

    // Save changes

    SecurityManager.SavePolicy();

}

VB

Sub SetPermissions()

    ‘ Find the machine policy level

    Dim machinePolicyLevel As PolicyLevel = Nothing

    Dim ph As IEnumerator = SecurityManager.PolicyHierarchy()

 

    While ph.MoveNext()

        Dim pl As PolicyLevel = DirectCast(ph.Current, PolicyLevel)

        If pl.Label = "Machine" Then

            machinePolicyLevel = pl

            Exit While

        End If

    End While

 

    Dim ps As NamedPermissionSet = New NamedPermissionSet("CallerPermSet", PermissionState.None)

 

    ‘ Add permissions (omitted)

    Dim key As StrongNamePublicKeyBlob = GetType(Caller).Assembly.Evidence _

        .OfType(Of StrongName)().First().PublicKey()

    Dim mc As IMembershipCondition = New StrongNameMembershipCondition(key, Nothing, Nothing)

 

    ‘ Create the code group

    Dim policy As PolicyStatement = New PolicyStatement(ps, PolicyStatementAttribute.Exclusive)

 

    Dim codeGroup As CodeGroup = New UnionCodeGroup(mc, policy)

 

    codeGroup.Description = "Permissions for PT Caller"

    codeGroup.Name = "CallerGroup"

 

    ‘ Add the code group

    machinePolicyLevel.RootCodeGroup.AddChild(codeGroup)

 

    ‘ Save changes

    SecurityManager.SavePolicy()

End Sub

My next plan of attack was to determine whether the changes to security policy were really being made. Even though no exceptions were thrown, I couldn’t understand why caspol –rsp would tell me that the framework would run our test assembly in full trust. i tried listing all the code groups from caspol under the Machine level:

caspol –m –lg

Microsoft (R) .NET Framework CasPol 4.0.21006.1
Copyright (c) Microsoft Corporation.  All rights reserved.

WARNING: The .NET Framework does not apply CAS policy by default. Any settings
shown or modified by CasPol will only affect applications that opt into using
CAS policy.

Please see http://go.microsoft.com/fwlink/?LinkId=131738 for more information.

Policy change prompt is ON

Level = Machine

Code Groups:

1.  All code: Nothing
   1.1.  Zone – MyComputer: FullTrust
      1.1.1.  StrongName – 00240000048000009400000006020000002400005253413100040
0000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE
79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E82
1C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8
A12436518206DC093344D5AD293: FullTrust
      1.1.2.  StrongName – 00000000000000000400000000000000: FullTrust
   1.2.  Zone – Intranet: LocalIntranet
      1.2.1.  All code: Same site Web
      1.2.2.  All code: Same directory FileIO – ‘Read, PathDiscovery’
   1.3.  Zone – Internet: Internet
      1.3.1.  All code: Same site Web
   1.4.  Zone – Untrusted: Nothing
   1.5.  Zone – Trusted: Internet
      1.5.1.  All code: Same site Web
Success

The custom code groups weren’t there! But if I inspected the code groups in code after running the setup executable, then they did appear.

Resolution

Eventually I just got frustrated and pulled out procmon to figure out what caspol.exe was doing under the covers. I saw it reading and writing from configuration files in the .NET Framework directory, and that’s when it hit me. The setup executable that writes to security policy was compiled as AnyCPU and thus any security policy edits were flushed to the configuration files in the %WINDIR%Microsoft.NETFramework64 directory. Our test harness was erroneously running as a 32-bit application on a 64-bit machine, which means the security policy it read was actually from the %WINDIR%Microsoft.NETFramework directory!

There are two versions of caspol.exe on 64-bit machines! One is for 32-bit applications, and the other is for 64-bit. As you can probably infer, I was incorrectly using the 32-bit one in my diagnosis above, which is why I never saw any of the custom code groups added to security policy.

It took a couple hours to figure this out, so I hope this post can help save you some time if you ever run into a similar situation!

Asserting for Permissions in .NET 4 – #18

Security asserts are a way to tell the CLR to stop checking for permissions past a certain point in the call stack. Of course, not all code is allowed to assert, or we’d have some big security problems to worry about. Specifically, partial trust code and security transparent code cannot assert for permissions. You may ask why asserting is useful, then, when only fully trusted code can do it.

One use case where asserts are beneficial is in testing products in partial trust. Say we have some test code that runs in partial trust and calls LINQ to SQL to test that a certain scenario still works in a medium trust environment. However, the test framework that the test uses requires permissions that are not granted in medium trust for some operations. Since the test framework knows that its callers won’t do anything malicious, it can assert for the permissions it needs to run these privileged operations. To do this, however, the test framework must be fully trusted.

Let’s say I have a test that runs in medium trust and calls some code in LINQ to SQL to verify that that code path works under medium trust. However, during some part of the test, the test framework itself needs to read an environment variable to determine which version of SQL Server to execute the test against (e.g. SQL Server 2000, SQL Server 2005, or SQL Server 2008).

Here’s the beginning of a test. (Keep in mind that this code is just an example. It doesn’t represent real types that we use in the LINQ to SQL test code, but it does demonstrate security assertions, which is something we do in the test framework.)

[Test]

public void TestMediumTrust()

{

    DataContext context = DataContextFactory.CreateDataContext();

 

    // …

}

And here’s the code in the test framework that the test above calls.

public static class DataContextFactory

{

    public static DataContext CreateDataContext()

    {

        string sqlVersion = ReadSqlVersion();

 

        // …

        // Return the correct data context.

    }

 

    [SecuritySafeCritical]

    [EnvironmentPermission(SecurityAction.Assert, Read = "SQLVERSION")]

    private static string ReadSqlVersion()

    {

        return Environment.GetEnvironmentVariable("SQLVERSION");

    }

}

The TestMediumTrust method resides in a test assembly, while the DataContextFactory resides in another assembly which is part of the test framework. When we set up the medium-trust sandbox in which to run the test, we tell the CLR to fully trust the test framework assembly. Full trust implies two things: (1) that SafeCritical and Critical annotations are respected and (2) we can assert for permissions. Remember that security transparent code cannot assert for permissions; this is why the ReadSqlVersion method above must be SafeCritical.

Medium trust code does not have permission to read the SQLVERSION environment variable, so under normal circumstances calling Environment.GetEnvironmentVariable would throw a SecurityException. This is because the .NET Framework itself will do a full Demand for the EnvironmentPermission to read the SQLVERSION variable. Permission Demands walk the entire call stack to ensure that every frame in the stack has the relevant permissions; since the test code runs in medium trust, the CLR will throw once it checks the TestMediumTrust method.

Asserts are a way to tell the CLR to stop checking for permissions past a particular stack frame. Thus with the assert in place on the ReadSqlVersion method, the EnvironmentPermission check stops prematurely and the permission Demand will succeed. To put that graphically…

image

So what changes in .NET 4? The recommended guidance is now to assert for full trust instead of for a specific permission. This advice seems to contradict the principle of least privilege, but in reality, if you layer your transparent and critical code appropriately, then security transparency can help you realize least privilege much more effectively. A second reason is that asserting for a specific permission causes a dependency on the underlying implementation. (This is a less convincing argument for me personally.) So the ReadSqlVersion method above now becomes…

[SecuritySafeCritical]

[PermissionSet(SecurityAction.Assert, Unrestricted = true)]

private static string ReadSqlVersion()

{

    return Environment.GetEnvironmentVariable("SQLVERSION");

}

How to Build APIs with Transparency in Mind – #17

In the .NET Framework there are a few types which expose both "safe" and "unsafe" equivalents of the same method. Both methods achieve the same goal e.g. BinaryFormatter.Deserialize and BinaryFormatter.UnsafeDeserialize will both deserialize a stream into a .NET object, but the safe variant will do a full Demand for the appropriate permissions. This ensures that callers without proper permissions will fail when trying to call the safe method. The unsafe variant, on the other hand, ensures only that the immediate caller has the necessary permissions. Previous versions of the .NET Framework enforce these invariants with Demands and LinkDemands, as shown in the example below. (Note that this isn’t exactly what you’ll see for these methods in the BinaryFormatter class if you examine them in Reflector, but the permission Demand and LinkDemand are present.)

[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]

public object Deserialize(Stream serializationStream)

{

   return this.UnsafeDeserialize(serializationStream);

}

 

[SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)]

public object UnsafeDeserialize(Stream serializationStream)

{

    // Method body

}

The reason for the two different versions is that a permission Demand is expensive because it has to check the permissions of every frame in the call stack. If you know that you aren’t introducing a security hole by calling an unsafe method, then you can skip the permission Demand and avoid the performance hit.

In .NET 4 under the Level 2 security rules, LinkDemands have been replaced by the SecurityCriticalAttribute, which means the UnsafeDeserialize will look similar to this.

[SecurityCritical]

public object UnsafeDeserialize(Stream serializationStream)

{

    // Method body

}

Methods annotated with LinkDemands should migrate to use the SecurityCriticalAttribute because the whole purpose of security transparency is to promote this kind of safe/unsafe API layering. When a method is decorated with the SecurityCriticalAttribute, the CLR ensures that no security transparent code can call that method. When you consider that all code running in partial trust is security transparent, the SecurityCriticalAttribute is effectively the same as a LinkDemand for full trust.

Be careful though! This API layering works for the .NET Framework because the assemblies are installed in the GAC and are therefore fully trusted, even in a partial trust sandbox. If the assembly you create is loaded into a partial trust sandbox but is not fully trusted, then the SecurityCriticalAttribute will not enforce anything. Remember, all partial trust code is security transparent, even code annotated with the SecurityCriticalAttribute.

Finally, if your assembly is not intended for partially trusted callers, then do you don’t need to worry about any of this. :)

Check out the .NET 4 documentation on Demands vs. LinkDemands for more information.

Mixing Level 1 and Level 2 Transparency Rules – #16

Today’s tip addresses how assemblies using different transparency rules (CLR v2 and CLR v4) interact with each other in the same AppDomain. Remember you can use the SecurityRulesAttribute to specify which level of security rules your assemblies adhere to. The default in .NET 4 is level 2.

There are only two cases here—a level 1 assembly calling a level 2 assembly, and a level 2 assembly calling a level 1 assembly. Let’s take them one at a time.

Level 2 Assembly Calls Level 1 Assembly

Transparency rules are not enforced across assembly boundaries under the level 1 rules, but they are under the level 2 rules. When a level 2 assembly calls a level 1 assembly, transparency violations are not enforced—that is, if level 2 transparent code calls a level 1 critical method in another assembly, the call succeeds.

Level 1 Assembly Calls Level 2 Assembly

You might think that transparency is enforced across the assembly boundary since the roles are now reversed, but the CLR acts a bit more interestingly than that. If partial-trust code from a level 1 assembly tries to call a critical method in a level 2 full-trust assembly, then the call fails. Level 1 assemblies, which use the CLR v2′s transparency semantics, have no way to interpret a public security critical method as it exists in level 2; such a concept didn’t exist back in the second version of the CLR. Because of this, the CLR goes to great lengths to make everything appear as level 1 to the calling assembly. To do this the CLR transforms the method marked SecurityCritical into a LinkDemand for FullTrust. Thus the call to a public critical method from partial trust code fails.

In the CLR v4, methods that were marked with LinkDemands for FullTrust are now marked SecurityCritical, which is a stronger enforcement mechanism because it prevents all partial-trust code and all transparent code from calling it. It is not a stretch to see that the CLR will transform the SecurityCritical annotation back into a LinkDemand for FullTrust to make everything appear as level 1 to the level 1 assembly.

This means that transparent code in a level 1 assembly can call public critical code in a level 2 assembly if the level 1 assembly is fully trusted. The rule states only that partial trust code in a level 1 assembly cannot call fully trusted security critical code in a level 2 assembly.

Furthermore, partial trust code is always security transparent and thus can never call security critical code.

The SecurityRulesAttribute – #15

The SecurityRulesAttribute is a new attribute class introduced in .NET 4.0 to specify which set of security rules a particular assembly adheres to. The attribute is specified on the assembly level, and allows you to specify two pieces of information.

The first and more important piece is the version of transparency that your assembly follows. If you want to use the .NET 2.0 interpretation of transparency, specify SecurityRuleSet.Level1 as the argument to the SecurityRulesAttribute constructor. If you want to use the .NET 4.0 interpretation of transparency, specify SecurityRuleSet.Level2. Level2 is also the default for assemblies built on the .NET 4.0 runtime.

For CLRv2 transparency semantics:

[assembly: SecurityRules(SecurityRuleSet.Level1)]

For CLRv4 transparency semantics:

[assembly: SecurityRules(SecurityRuleSet.Level2)]

The second piece allows to tell the CLR that you want to skip IL verification of your assembly when it is fully trusted and transparent. Remember, transparent code can’t contain unverifiable code or P/Invokes, so the CLR usually must check that the transparent code it loads does not violate these invariants. You can skip this verification to increase your performance slightly when the JIT compiler compiles your code, but remember that doing this will allow unverifiable code in your assembly. I’d recommend using this only if you don’t have unverifiable code in your transparent assembly.

That last scenario is slightly abstract, so I want to show an example of the difference.

SecurityDriver.exe

public class Program : MarshalByRefObject

{

    static void Main(string[] args)

    {

        PartialTrustSetup.CreatePartialTrustInstance<Program>().PartialTrustMain();

    }

 

    public void PartialTrustMain()

    {

        Utility u = new Utility();

        u.ExecuteUnsafeCode();

    }

}

SecurityLibrary.dll (Pardon the trivial example of unverifiable code.)

[assembly: SecurityTransparent]

public class Utility

{

    public unsafe void ExecuteUnsafeCode()

    {

        int i = 0;

        int* p = &i;

        *p = 2;

        Console.WriteLine(i);

    }

}

The Main method in SecurityDriver.exe sets up a partial-trust AppDomain and instantiates a new instance of the Program class in that AppDomain. The partial trust code only has permission to execute (SecurityPermission with SecurityPermissionFlag.Execution). When it calls Utility.ExecuteUnsafeCode, the JIT compiler throws a VerificationException because it can’t verify the IL in Utility.ExecuteUnsafeCode.

But if we add this attribute to the SecurityLibrary assembly and ensure that it is fully trusted (by using the StrongName[] parameter of the AppDomain.CreateDomain method), then the JIT compiler will skip IL verification, and "2" will be printed to the console.

[assembly: SecurityRules(SecurityRuleSet.Level2, SkipVerificationInFullTrust = true)]

Remember, this only works when your transparent assembly is fully trusted.

Determining the Security Rules for Your Assemblies – #14

If you’ve followed this tip series you’ll know about two different kinds of security transparency, one present in CLR 2.0 and one in CLR 4.0. And you know that in CLR 4.0, you can decide to use the legacy transparency rules in CLR 2.0. And you know about this attribute called APTCA. Maybe a bit about permissions, too.

It can be really hard to keep all this information straight, so I’ve put together a flowchart to help you determine which transparency rules a particular assembly is using. I hope it’s useful!

image

As you can see, while the number of rules is not totally unmanageable, it can be difficult to keep them straight. There are also a few situations where two different paths lead to the same outcome. For example, your assembly can be fully critical when it is a level 2 assembly marked with the SecurityCriticalAttribute or when it is a level 1 assembly marked with the SecurityCriticalAttribute with SecurityCriticalScope.Everything. Keep in mind that even though the assembly is fully critical in both cases, the meaning of critical depends on the current level, level 1 or level 2. If you need a review, consult my previous tips on CLR v2 transparency and CLR v4 transparency.

Transparency and Implicit Static Constructors – #13

When you create classes that have static fields, and you initialize those fields inline, the compiler will split the code into two parts: the field declaration and the field initialization. Field initialization occurs within a static constructor, whether it’s declared or not. Have a look at the following class as it appears in C#.

public class Wrapper

{

    private static IntPtr handle = InitializeHandle();

 

    private static IntPtr InitializeHandle()

    {

        // get handle

    }  

}

It’s almost the same as doing this.

public class Wrapper

{

    private static IntPtr handle;

 

    static Wrapper()

    {

        handle = InitializeHandle();

    }

 

    private static IntPtr InitializeHandle()

    {

        // get handle

    }

}

The difference between the implicit static constructor and explicit static constructor is that the implicit constructor performs much better than the explicit one. (You can read more about this difference here.)

What if I deem that the handle itself should be SecurityCritical? This is where things get interesting…

public class Wrapper

{

    [SecurityCritical]

    private static IntPtr handle = InitializeHandle();

 

    private static IntPtr InitializeHandle()

    {

        // get handle

    }

}

If I instantiate a new Wrapper instance, this code still runs correctly, but if I mark this assembly with APTCA, it fails. What’s happening here?

We get a FieldAccessException whose message is "ConsoleApplication2.Wrapper.handle" and whose stack trace is "at ConsoleApplication2.Wrapper..cctor()." The ".cctor" is the static constructor. From this we can deduce that the static constructor can’t initialize the field, and that’s because the static constructor generated by the compiler is transparent code when we mark the assembly with APTCA.

Unfortunately this is a case in which you must sacrifice performance for security. This might be changed before .NET 4 RTM, but for now, you’ll need to explicitly specify the static constructor and mark it as security safe critical or security critical. (You can mark it security critical because the runtime itself will call the static constructor from native code.)

public class Wrapper

{

    [SecurityCritical]

    private static IntPtr handle;

 

    [SecurityCritical]

    static Wrapper()

    {

        handle = InitializeHandle();

    }

 

    private static IntPtr InitializeHandle()

    {

        // get handle

    }

}

Partial Trust, APTCA, and Security Transparency – #12

We’ve talked about APTCA. We’ve talked about security transparency. Do they relate? Yes, at least in .NET 4.

Marking your assembly with APTCA means that your entire assembly becomes security transparent. However, you can still explicitly annotate portions of the code as SecuritySafeCritical or SecurityCritical.

You may wonder what happens if you don’t mark your assembly APTCA. Partial trust code obviously cannot call it, but for a different reason. If you remember back to my APTCA article, you’ll remember that partial trust code can’t call strong-named assemblies that aren’t marked APTCA. However, in .NET 4, by default, partial trust code can’t call any assembly. This is because partial trust code is always security transparent, and the default transparency level for .NET 4 code is security critical. Security transparent code can’t ever call security critical code unless it goes through security safe critical code first.