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.
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();
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)
{
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With