Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect trust level

Tags:

.net

c#-2.0

How can a .NET application detect the trust level in which it is running under?

Specifically, I'm wanting a way to do something like

  if (RUNNING IN GREATER THAN MEDIUM TRUST) { 
    // set private fields & properties using reflection
  }

My current solution is to use

public static class CodeAccessSecurityTool {
    private static volatile bool _unrestrictedFeatureSet = false;
    private static volatile bool _determinedUnrestrictedFeatureSet = false;
    private static readonly object _threadLock = new object();

    public static bool HasUnrestrictedFeatureSet {
        get {
            if (!_determinedUnrestrictedFeatureSet)
                lock (_threadLock) {
                    if (!_determinedUnrestrictedFeatureSet) {
                        try {
                            // See if we're running in full trust
                            new PermissionSet(PermissionState.Unrestricted).Demand();
                            _unrestrictedFeatureSet = true;
                        } catch (SecurityException) {
                            _unrestrictedFeatureSet = false;
                        }
                        _determinedUnrestrictedFeatureSet = true;
                    }
                }
            return _unrestrictedFeatureSet;
        }
    }
}

But, it's a bit of a hack.

like image 464
Herman Schoenfeld Avatar asked Feb 21 '13 11:02

Herman Schoenfeld


2 Answers

Maybe this is helpful:

ActivationContext ac = AppDomain.CurrentDomain.ActivationContext;
ApplicationIdentity ai = ac.Identity;
var applicationTrust = new System.Security.Policy.ApplicationTrust(ai);
var isUnrestricted = applicationTrust.DefaultGrantSet.PermissionSet.IsUnrestricted();

Or

AppDomain.CurrentDomain.ApplicationTrust
  .DefaultGrantSet.PermissionSet.IsUnrestricted();
like image 72
Alex Filipovici Avatar answered Sep 23 '22 10:09

Alex Filipovici


From .NET 4.0 onwards there is the AppDomain.IsFullyTrusted property which may be helpful.

If you wish to test this on the current app domain, use:

if (AppDomain.CurrentDomain.IsFullyTrusted)
{
    // ...
}
like image 22
Drew Noakes Avatar answered Sep 23 '22 10:09

Drew Noakes