Lost Password? No account yet? Register
Member Area

Software Installation Technologies

May 17th

Home arrow Community arrow External Blogs arrow ClickOnce

ClickOnce
.NET Security Blog


  • Strong Name Bypass

    Many managed applications start up slower than they really need to because of time spent verifying their strong name signatures.  For most of these applications, the strong name verification isn't buying the application anything - especially fully trusted desktop applications that are using C# as a better C++.

    Since these applications were paying the cost of verifying their assemblies at load time, but were not receiving any benefit from that cost, we've made a change in .NET 3.5 SP1 which lets these applications bypass strong name signature verification.

    Specifically, for any assembly which is:

    1. Fully signed (delay signed assemblies still require a skip verification entry)
    2. Fully trusted (without considering its strong name evidence)
    3. Loaded into a Fully trusted AppDomain
    4. Loaded from a location under the AppDomain's ApplicationBase

    The CLR will no longer verify the assembly's strong name when it is loaded.

    This provides an assembly load performance win for most full trust applications, however not all applications will want to have their fully trusted assemblies skip strong name verification.  If your application wants to re-enable strong name verification, it can add a .exe.config file with the following setting:

    <configuration>
        <runtime>
            <bypassTrustedAppStrongNames enabled="false"/>
        </runtime>
    </configuration>

    Also, if a machine administrator wants to disable strong name bypass for all assemblies loaded on a particular computer, they can set the DWORD registry value named AllowStrongNameBypass to 0 under the HKLM\Software\Microsoft\.NETFramework key:

    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
    "AllowStrongNameBypass"=dword:00000000

    (The usual disclaimers apply about modifying the registry only if you know what you're doing)

    As with other strong name configuration, on a 64 bit machine this registry setting will need to be set in both the 32 and 64 bit HKLM\Software keys.

    For users who have the SDK installed, SN.exe also adds an option to query and update this key for you.  You can run SN -Pb [y|n] to allow or disable assemblies from bypassing strong name verification on your machine. (Again, using both a 32 and 64 bit SN.exe on 64 bit machines).  SN -Pb with no argument will display the current value of the setting.



  • FullTrust on the LocalIntranet

    We released the first beta of .NET 3.5 SP 1 this morning, and it includes a change to the default grant set for applications launched from the LocalIntranet zone.  The quick summary is that as of .NET 3.5 SP1, applications run from a network share will receive a grant set of FullTrust by default, making them act the same as if they were launched off of your computer directly.  Since this is an issue that I know a lot of people run into, I hope that this change makes it easier to use and deploy managed applications.  For people who want to keep their machines working the same as they did for previous .NET Framework releases, you can set the DWORD registry value LegacyMyComputerZone to 1 in the HKLM\Software\Microsoft\.NETFramework registry key.

    With the high-level summary out of the way, let's take a look under the hood to see what changed to make this possible :-)

    The core of this change is a modification in how we assign evidence to network launched applications.  When we see an .exe launched directly off a network share, rather than giving that .exe Zone evidence of LocalInranet, we instead give the .exe Zone evidence of MyComputer.  This causes the .exe to match the default MyComputer code group rather than the LocalIntranet group, and in default CAS policy that code group grants FullTrust.   (This also explains why the opt-out registry value is named LegacyMyComputerZone)

    In addition to the entry point .exe of the application, we'll also extend this MyComputer evidence to any assembly loaded from the same directory as the .exe.  So, if you place any managed .dll's immediately next to your .exe, those will also all be given FullTrust by default in .NET 3.5 SP1.

    Since we're only including assemblies loaded from the same directory as the entry point application, things will just work for most applications, however more complicated programs that need to load assemblies from different subdirectories or other network shares may not see all of their assemblies get fully trusted by default.  For these more types of applications, ClickOnce deployment is the recommended way to elevate to FullTrust.

    We've specifically disabled this change for any hosted applications.  So this means that if your program uses the CorBindToRuntime API to host the CLR, we won't start trusting assemblies it loads from a share.  Similarly, hosts like Internet Explorer will not start trusting controls that it loads into the browser.

    To summarize the under the hood changes, assemblies which will now receive Zone evidence of MyComputer and therefore be fully trusted by default are:

    1. Any managed .exe which is launched directly from a network share
    2. Any assembly in that .exe's process which is loaded from the same directory as the .exe itself was.

    Assemblies which will not see this change include:

    1. Assemblies loaded from a subdirectory of the share where the .exe was launched from
    2. Assemblies loaded from shares other than the one where the main .exe was launched
    3. Any assembly loaded on a machine with the LegacyMyComputer registry value set to 1
    4. Any assembly loaded into a CLR host, including assemblies loaded into Internet Explorer as controls.
    5. Any assembly loaded from shares by an application that was launched from the "real" MyComputer zone.


  • Disabling the FIPS Algorithm Check

    .NET 2.0 introduced a check for FIPS certified algorithms if your local security policy was configured to require them.  This resulted in algorithms which are not FIPS compliant (or implementations which were not FIPS certified) throwing an InvalidOperationException from their constructors.

    In some cases this isn't a desirable behavior.  For instance, some applications need to use the MD5 hashing algorithm for compatibility with an older communication protocol or file format.  Prior to .NET 3.5, the AES algorithm was only available in an implementation which was not FIPS certified, and if you needed to use that algorithm the FIPS check could also block you.

    To help these cases, we added a configuration file switch to .NET 2.0 SP 1 (and therefore .NET 3.5) which allows an application to say "I know what I'm doing, please don't enforce FIPS for me".  For these applications, they can setup a configuration file similar to:

    <configuration>
        <runtime>
            <enforceFIPSPolicy enabled="false"/>
        </runtime>
    </configuration>

    Which will prevent the CLR from throwing InvalidOperationExceptions from the constructor of uncertified algorithms and implementations.



  • CAS and Native Code

    CAS is complicated enough to understand when all of the moving parts are written in managed code (and therefore have all the associated managed meta-information like grant sets, etc).  However, once native code comes into play things can get even more confusing.  Let's take a look at how CAS works when there's native code on the call stack.

    For this discussion, lets assume we have a call stack (growing down) like so:

    Managed code: M1
    Managed code: M2
    Native code: N1
    Managed code: M3
    Managed code: M4
    AppDomain: AD

    So in this example, M1 calls M2, which calls N1, which calls back to managed code M3 and M4.  All of the managed objects live in AppDomain AD.

    Full Demands

    Now lets consider what happens when M4 triggers a full stack walk for a demand.  In this case, the CLR essentially ignores the native code on the stack, and does a stack walk looking at M3, M2, M1, and AD.  Intuitively, this is done because the native code doesn't have a grant set associated with it, and therefore including it on a CAS stack walk wouldn't make much sense.

    It's important to note however that the stack walk proceeds through N1, rather than stopping at it.  So in this case if M3 and M2 are fully trusted, but M1 is partial trust and M4 triggered a FullTrust demand, that demand would fail.

    Stack walk modifiers like Assert continue to work just as you would expect as well, so it's perfectly legal for M2 to Assert FullTrust, which would make M4's demand succeed.

    Link Demands

    Link demands are much more interesting when native code gets involved.  In our example, imagine that managed method M3 has a LinkDemand for FullTrust on it.  Normally, LinkDemands are evaluated at JIT time against the caller of the method with the demand.  But in this case, the caller of M3 is native code which is not JITed (and doesn't have a grant set to evaluate against in any event).

    The obvious solution then is to evaluate the LinkDemand against the last managed frame on the call stack before we transitioned to native code.  At the time we're JITing this method however, we only know that it's calling a native method -- we don't know what managed code that native code is going to turn around and call later on.  In this example, when M2 is being JITed we know that it may call N1, however we don't know that N1 will turn around and call M3 and therefore don't know that M3 has as a LinkDemand to evaluate against M2.

    However, it turns out that we don't need to know what M3 is going to LinkDemand of M2.  Since M2 is calling N1, it must have UnmanagedCode permission, and since UnmanagedCode permission is never handed out without FullTrust, we can reason that M2 must be fully trusted.  If M2 is fully trusted, then it will satisfy any LinkDemand that M3 will require.

    With this analysis, we could say that LinkDemands are implicitly satisfied by native code callers.  However, that may not be the effect that we want in all cases.  For instance, one common scenario might be to expose a managed object via COM Interop to a script.  (For instance, make a managed object available via COM to some JavaScript in a web page).

    From the CLR's perspective, this script is just native code, so our reasoning would lead to any link demands on methods the script calls being satisfied.  However, we may not want the script to satisfy all link demands.  In order to solve this problem, the CLR treats calls to managed code from native via COM Interop differently.

    If native code uses a COM interface to call a managed method protected with a LinkDemand, then that LinkDemand is evaluated against the AppDomain which the managed object lives in.

    Let's go back to our example again, and see how these rules apply.  Let's suppose that N1 calls M3 through COM Interop, M3 has a LinkDemand for FullTrust, and the AppDomain AD is also fully trusted.  In this case, the call succeeds because the AppDomain's grant set satisfies M3's LinkDemand.

    Now let's consider the case where this AppDomain is hosted by Internet Explorer, and therefore has only the Internet grant set.  When N1 calls into M3, we'll see that the object M3 is being called on lives in AppDomain AD, and that causes us to look up the grant set of that domain.  We then check M3's LinkDemand for FullTrust against the AppDomain's grant set of Internet.  Since the AppDomain's grant set does not satisfy the LinkDemand, we throw a SecurityException.  Note that this is true even if the last managed frame on the stack (M2) is fully trusted.

    If we make one more change to the scenario, and have N1 call M3 via reverse P/Invoke we a different result.  Even though the AppDomain is partially trusted, since M3 was not invoked from COM Interop, we allow the call to succeed.

    3 Rules for Native Code CAS Evaluation

    That's a ton of complexity, but thankfully we can boil it down to three rules depending upon your scenario:

    1. If a full demand is done, native stack frames are ignored and the stack walk proceeds exactly as if there were only managed frames on the stack.
    2. If a link demand is done via COM Interop, the link demand is evaluated against the grant set of the AppDomain that the managed object lives in.
    3. If a link demand is done via reverse P/Invoke, the link demand is satisfied and the call succeeds.


  • Which Groups Does WindowsIdentity.Groups Return?

    WindowsIdentity exposes a Groups property which returns a collection of IdentityReferences for the groups that a particular user is a member of.  However, if you look closely, you'll find that these returned groups won't necessarily include all of the groups that the user is a member of.

    Under the covers, WindowsIdentity populates the groups collection by querying Windows for information on the groups that the user token is a member of.  However, before returning this list, the Groups property filters out some of the returned groups.

    Specifically, any groups which were on the token for deny-only will not be returned in the Groups collection.  Similarly, a group which is the SE_GROUP_LOGON_ID will not be returned.

    Generally, this is exactly the behavior you want.  For instance, if your application is going allow a specific action because the user is a member of a group, you don't want to allow it if the user is a member of the group for deny-only.

    If you want to retrieve all of the groups however, there's not an easy built-in way for you to do this.  Instead, you'll have to P/Invoke to the GetTokenInformation API to retrieve the groups yourself.

    It can be interesting to dump out the groups that specific users are part of -- here's a simple little snippet of code that does just that.  (And uses some of those fancy new C# 3.0 features to display them grouped by domain):

        public static void Main()

        {

            using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent())

            {               

                var groups = // Get all of the groups from our account, and translate them from IdentityReferences to NTAccounts  

                            from groupIdentity in currentIdentity.Groups

                            where groupIdentity.IsValidTargetType(typeof(NTAccount))

                            select groupIdentity.Translate(typeof(NTAccount)) as NTAccount into ntAccounts

     

                            // Sort the NTAccounts by their account name

                            let domainName = ntAccounts.GetDomainName()

                            let groupName = ntAccounts.GetAccountName()

                            orderby domainName

     

                            // Group the sorted accounts by the domain they belong to, and sort the grouped groups by domain name

                            group ntAccounts by domainName into domainGroups

                            orderby domainGroups.Key

                            select domainGroups;

     

                foreach (var domainGroups in groups)

                {

                    Console.WriteLine("Groups from domain: {0}", domainGroups.Key);

     

                    foreach (var group in domainGroups)

                    {

                        Console.WriteLine("    {0}", group.GetAccountName());

                    }

                }

            }

        }

     

        private static string GetDomainName(this NTAccount account)

        {

            string[] split = account.Value.Split('\\');

            return split.Length == 1 ? String.Empty : split[0];

        }

     

        private static string GetAccountName(this NTAccount account)

        {

            string[] split = account.Value.Split('\\');

            return split[split.Length - 1];

        }



  • Manifested Controls Redux

    Last year, I made a series of posts about a new feature available in the betas of .NET 3.5 which enabled you to specify declaratively the set of permissions that IE hosted managed controls should run with.  Since the betas there have been a couple of tweaks to the manifest control model, so those posts need a refresh.

    Most notably, the Low Safety (Unrestricted) setting for the Permissions for Components with Manifests URL action is not a part of the final shipping Orcas bits.  Instead, the two options are:

    • High Safety - manifested controls can run with the permissions it requests, but only if those permissions are a subset of the permissions it would have been granted by CAS policy or if the manifests are signed by a trusted publisher.
    • Disabled - manifested controls may not run at all.

    If you're using a machine that had one of the .NET 3.5 betas on it, the Low Safety option will still appear in your Internet Explorer dialog box, however the CLR will treat a value of Low Safety as if it were Disabled.

    A lot of times when people look at this feature, they would like a full end-to-end sample of a control in a web page taking advantage of a manifest to elevate its permissions.  I've attached a ZIP file containing a sample control to this post.

    In order to use this sample:

    1. Create a ManifestControl subdirectory in your wwwroot.
    2. Copy ManifestControl.control, ManifestControl.dll, ManifestControl.dll.manifest, and ManifestControl.html to the ManifestControl directory created in step 1.
    3. Ensure that your web server is setup to allow downloading of .dll, .control, and .dll.manifest files.
    4. Install ManifestControl.cer in your Trusted Publishers certificate store.
    5. Install ManifestControl.cer in your Trusted Root Certification Authorities certificate store. (Once you are done with the sample, the test certificate should be removed from both of these certificate stores)
    6. Navigate Internet Explorer to http://localhost/ManifestControl/ManifestControl.html


  • Transparency as Least Privilege

    In my last post I mentioned that there is a better alternative to RequestRefuse for achieving least privilege. The tool I like to use for least privilege is actually the security transparency model available in v2.0+ of the CLR (and which became the basis of the Silverlight security model).

    On the desktop CLR, transparent code cannot elevate the privileges of the call stack in any way.  Let's take a quick look at how this is enforced:

    Uverifiable code - if a transparent method contains unverifiable code, the CLR injects a demand for SecurityPermission/UnmanagedCode.

    Satisfy a LinkDemand - LinkDemands satisfied by a transparent method are converted into full demands

    Use the SuppressUnmanagedCodeAttribute - this is really an extension of the LinkDemand rule.  the SuppressUnmanagedCodeAttribute converts the full demand for SecurityPermission/UnmanagedCode into a LinkDemand for the same permission.  However, since link demands satisfied by transparent code are converted into full demands, the net effect is that SuppressUnmanagedCodeAttribute becomes a no-op.

    Assert permissions - Asserts are an explicit attempt to elevate the permissions of the call stack, and are therefore disallowed in transparent code.  They are not converted into full demands

    Call critical code without going through a TreatAsSafe layer - the treat as safe layer is responsible for validating inputs and outputs of critical code, and transparent code must access critical code via this layer.  Attempts to call critical code or access critical data directly are disallowed.

    This effectively means that fully trusted transparent code runs "as caller".  It won't cause any security demands to fail, however it won't cause them to succeed either. If the caller of the transparent code is allowed to do the security operation it will succeed, otherwise it fails.

    What's interesting is that if we take this principal to the extreme, and have the entire call stack be transparent (such as in Silverlight), transparency transitions from running "as caller" to running "as application".  This is because each level in the transparency call chain passes the security demand up to its caller, until we hit the top of the stack -- and find the AppDomain.  Since all security demands end up going against the AppDomain's permission set, that permission set alone controls what may happen within the domain.

    In this way, my fully trusted code will be fully trusted if it is run within a FullTrust domain.  However, that same code run within an AppDomain with the Internet permission set (perhaps if it's being used by a control in the browser), will effectively be running with Internet permissions.  Any demand for a permission outside of the Internet permission set will be passed along until it hits the AppDomain and fail.

    Let's say that you're writing an application that you know will never need to interact with native code.  You'd normally do a RequestRefuse for UnmanagedCode permission on your application's assemblies to ensure that it's never accidentally satisfying an UnmanagedCode demand.  Instead of doing that, you can make sure that your application assemblies are entirely transparent and that they are run in a domain without UnmanagedCode permission -- perhaps via ClickOnce deployment.

    This way you can use ClickOnce to explicitly control the grant set of the applicaiton, and transparency to ensure that you're not accidentally causing an elevation outside of that call stack, even if some of your application is installed in the GAC and fully trusted.



  • Avoiding Assembly Level Declarative Security

    I've written in the past about the three assembly level declarative security actions: RequestMinimum, RequestOptional, and RequestRefuse.  Although the CLR has supported these since v1.0, I tend to stay away from using them as much as I possibly can, and also recommend that others avoid them as well.  Let me go through each one individually:

    RequestMinimum

    RequestMinimum is the most common of the three, and in fact is mentioned by a FxCop rule and automatically inserted by the C# compiler in some cases.  There are several reasons I don't like to use this security action.

    The first problem I have with RequestMinimum is a usability problem stemming from the fact that if your assembly is not granted its RequestMinimum permission set, the CLR will refuse to load it by throwing an exception.  If the assembly in question happens to be the entry point of my application, that means the user of my app ends up staring down an unhandled exception dialog (since my code never got loaded, and therefore never had a chance to handle this error more gracefully).  If my mother runs an app I give her and it throws a FileLoadException due to insufficient permissions, she's not going to have any idea what to do with that.

    Even if the assembly is not the entry point assembly, gracefully handling failure to load due to RequestMinimum means that an application needs a try ... catch around every code path which could potentially lead to loading the assembly in question; that's not something that a lot of applications are setup to do.

    The other problem I find with RequestMinimum is that in the case of writing a shared library it's very difficult to figure out what the correct grant set to request is.  Unless all of the APIs being exposed require the same set of permissions, having only a single RequestMinimum set doesn't help much.  For instance, an assembly like System.dll exposes hundreds of classes each with indivdual permission requirements varying from SecurityPermission/Execution to FullTrust.  If we decided to use the minimum grant set of any API in the assembly as the ReuqestMinimum, we've somewhat defeated the purpose of the security action; now I cannot be assured that the assembly loading means that it has the required permissions to work in all cases.  On the other hand, if I use the maximum grant set required, the assembly won't load even if an application was only intending to use APIs that would work in the grant set that the assembly is loaded into.

    Finally, since security demands go against the entire call stack, even if the assembly in question has all the permissions that it needs to run doesn't mean that all assemblies and AppDomains on the call stack will have those permissions.  So even if an assembly does have its minimum grant set met, it doesn't have any guarantee that its APIs will all work without throwing a SecurityException.

    RequestOptional

    RequestOptional is probably the least commonly used assembly level security action, and with good reason.  This security action is somewhat poorly named, and people who use it for the first time often don't realize that it will actually remove permissions from your grant set.  In fact, I run across RequestOptional most commonly when helping someone debug a SecurityException that they can't figure out.  ("Why does this exception occur? All assemblies should be fully trusted!")

    Even once you do understand the full effect of RequestOptional, the fact that it is confusingly named and that most people do not understand it is argument enough for me to stay away.  Code readability is extremely important, and if I can expect that the next person to read through my code will be confused by that RequestOptional I stuck on my assembly, that's not a good thing -- especially when it comes to security.

    RequestRefuse

    I expect this is the most controversial security action to take a stance against.  A good number of people probably use RequestRefuse as a least-privilege mechanism.  My problem with that is that you're stating "I don't want permissions A and B", however when someone comes along and introduces permission C you haven't refused it, and therefore you still get it.  Personally, I believe the CLR has other, much better, least-privilege mechanisms available -- and I prefer to use those whenever possible.  (Sounds like the topic of a future blog post :-) ).

    Finally, and this should come as no surprise to any regular visitors, I'm a huge fan of the model where every sandboxed AppDomain has exactly two permission sets -- FullTrust and one sandbox grant set.  RequestRefuse (and RequestOptional) both detract from this model by creating multiple permission sets within an otherwise homogenous AppDomain.  By keeping AppDomains entirely homogenous, it's much easier to reason about security within the domain.  And, in my opinion, keeping the security model as simple as possible can only be goodness -- complexity can lead to mistakes in reasoning, which leads to security holes. 

    So What Instead?

    Some of the abilities promised by the assembly level declarative security actions seem to be very useful at first glance.  Notably the ability to specify a grant set that the code was tested to run in (which is what RequestMinimum seems to promise) and the ability to run with least privilege (via RequestRefuse).

    For RequestMinimum, I think that ClickOnce is a far superior alternative for a variety of reasons.  Most importantly, ClickOnce gives the user of the application a nicer experience when the application does not by default meet the minimum grant set.  Rather than throwing an exception in the face of a non-developer, a friendly user interface is displayed which may even offer the ability to grant the application the ability to run.

    Also, the grant set specified for a ClickOnce application applies to all of the assemblies in the application as well as the AppDomain  (hey -- it's my favorite homogenous model again!).  This means that you don't have to worry about the scenario where your assembly meets its minimum grant set, but some APIs still fail with SecurityExceptions because another assembly further up the call stack did not meet the minimum grant set.

    That covers RequestMinimum -- but what about the least privilege promise of RequestRefuse?  As AB might say -- that's another show.



  • CLR Inside Out: Digging into IDisposable

    My third MSDN magazine article, Digging into IDisposable, appeared in this month's issue in the CLR Inside Out Column.  It's a bit of a departure from my usual security fare; this time looking at how to best handle writing class libraries that must manage resources.

    Also in this month's issue, Kenny Kerr provides a good introduction to the new CNG APIs available on Vista.  Especially interesting is the code snippets he provides translating from CNG RSA keys to RSAParameters for use with RSACryptoServiceProvider.  (And for a quick rundown of the managed CNG classes Kenny mentions in the v3.5 framework, you can see the posts in my CNG category).



  • Silverlight Security Cheat Sheet

    Over the last week we took a look at the new Silverlight security model.  When you're writing a Silverlight application though, there's a lot of information there that you may not want to wade through to get yourself unblocked.  Here's a quick cheat sheet highlighting the important points that you'll need to know when working with the Silverlight security model:

    • All applications written for Silverlight are security transparent.  This means that they cannot: [details]
      • Contain unverifiable code
      • Call native code directly
    • Silverlight applications can access public methods exposed by platform assemblies which are either: [details]
      • Security transparent (neither the defining type nor the method has any security attributes)
      • Security safe critical (the method has a SecuritySafeCriticalAttribute)
    • Silverlight applications may contain types which derive from: [details]
      • Other types defined in the application
      • Unsealed, public, security transparent types and interfaces defined by the platform
    • Silverlight applications may contain types which override virtual methods and implements interface methods which are: [details]
      • Defined in the application itself
      • Defined by the platform and are transparent or safe critical



Visitors: 501155

Extended Menu