AddPermission() public method

public AddPermission ( IPermission perm ) : IPermission
perm IPermission
return IPermission
        static void Main(string[] args)
        {
            // Pfad, muss absolut sein für FileIOPermission
            string path = @"C:\Users\philipp\Dropbox\Dokumente\Schule\PR\src\dot-net-security-and-encryption\AppDomainTest\Evil\bin\Debug";

            // PermissionSet ohne Berechtigungen Erstellen
            PermissionSet set = new PermissionSet(PermissionState.None);

            // Berechtigen zum Ausführen des Programmes hinzufügen
            set.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            // Berechtigungen zum Lesen des Pfades hinzufügen
            set.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read |
                                                   FileIOPermissionAccess.PathDiscovery,
                                                   path));

            // Info, wird benötigt um Domain zu erstellen
            var info = new AppDomainSetup { ApplicationBase = path };

            // Erstellen der Domain
            AppDomain domain = AppDomain.CreateDomain("Sandbox", null, info, set, null);

            // Laden der Instance
            Example evil = (Example) domain.CreateInstanceFromAndUnwrap(path + @"\Evil.dll", "Evil.Example");

            // Ausführen der (bösen) Methode
            evil.DoSomethingEvil();

            Console.ReadKey();
        }
Example #2
0
        private AppDomain CreateAnalyzerDomain()
        {
            AppDomainSetup ads = new AppDomainSetup();
            AppDomain result;
            PermissionSet perms;
            ads.ApplicationBase = Environment.CurrentDirectory;
            ads.ShadowCopyDirectories = "shadow";
            ads.ShadowCopyFiles = "shadow";
            ads.DisallowCodeDownload = true;

            perms = new PermissionSet(PermissionState.None);
            FileIOPermission fiop = new FileIOPermission(PermissionState.Unrestricted);
            perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            perms.AddPermission(new SecurityPermission(SecurityPermissionFlag.AllFlags));
            fiop.AddPathList(FileIOPermissionAccess.PathDiscovery, Environment.CurrentDirectory);
            fiop.AddPathList(FileIOPermissionAccess.Read, Environment.CurrentDirectory);
            fiop.AddPathList(FileIOPermissionAccess.PathDiscovery, Environment.CurrentDirectory + "Extensions\\");
            fiop.AddPathList(FileIOPermissionAccess.Read, Environment.CurrentDirectory + "Extensions\\");
            //fiop.AllLocalFiles = FileIOPermissionAccess.AllAccess
            //fiop.AllFiles = FileIOPermissionAccess.AllAccess
            perms.AddPermission(fiop);
            perms.AddPermission(new UIPermission(UIPermissionWindow.AllWindows, UIPermissionClipboard.OwnClipboard));
            perms.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));

            PolicyLevel policy = PolicyLevel.CreateAppDomainLevel();
            policy.RootCodeGroup.PolicyStatement = new PolicyStatement(perms);

            // create the Domain
            result = AppDomain.CreateDomain("analyzer", null, ads);
            result.SetAppDomainPolicy(policy);
            return result;
        }
Example #3
0
    /// <summary>
    ///   Initializes the permissions manager with the permissions required by an install script.
    /// </summary>
    internal static void Init()
    {
      permissions = new PermissionSet(PermissionState.None);
      //do the following paths need to add to this?
      // savesPath - fallout 3
      var fipFilePermission = new FileIOPermission(FileIOPermissionAccess.AllAccess, new[]
      {
        Program.tmpPath,
        Path.GetTempPath(),
        Program.GameMode.InstallInfoDirectory,
        Program.GameMode.PluginsPath
      });

      var lstPaths = new List<string>(Program.GameMode.SettingsFiles.Values);
      lstPaths.AddRange(Program.GameMode.AdditionalPaths.Values);
      fipFilePermission.AddPathList(FileIOPermissionAccess.AllAccess, lstPaths.ToArray());
      fipFilePermission.AddPathList(FileIOPermissionAccess.Read, Environment.CurrentDirectory);

      permissions.AddPermission(fipFilePermission);
      permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
      permissions.AddPermission(new UIPermission(UIPermissionWindow.AllWindows));

      // Not sure what permissions are needed for GetTempFileName() to work, so we add them all.
      permissions.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
    }
        private static AppDomain CreateRestrictedDomain(string domainName)
        {
            // Default to all code getting nothing
            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup policyRoot = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            // Grant all code the named permission set for the test
            PermissionSet partialTrustPermissionSet = new PermissionSet(PermissionState.None);
            partialTrustPermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.AllFlags));
            partialTrustPermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy));

            PolicyStatement permissions = new PolicyStatement(partialTrustPermissionSet);
            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

            // Create an AppDomain policy level for the policy tree
            PolicyLevel appDomainLevel = PolicyLevel.CreateAppDomainLevel();
            appDomainLevel.RootCodeGroup = policyRoot;

            // Set the Application Base correctly in order to find the test assembly
            AppDomainSetup ads = new AppDomainSetup();
            ads.ApplicationBase = Environment.CurrentDirectory;

            AppDomain restrictedDomain = AppDomain.CreateDomain(domainName, null, ads);
            restrictedDomain.SetAppDomainPolicy(appDomainLevel);

            return restrictedDomain;
        }
Example #5
0
      public void Open()
      {
         if(State != CommunicationState.Created)
         {
            return;
         }
         try
         {
            Opening(this,EventArgs.Empty);

            //Permission required to read the providers application name and access config
            PermissionSet permissions = new PermissionSet(PermissionState.None);
            permissions.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal));
            permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));

            permissions.Assert();

            m_ServiceHostActivator.MembershipApplicationName = Membership.ApplicationName;
            if(Roles.Enabled)
            {
               m_ServiceHostActivator.RolesApplicationName = Roles.ApplicationName;
            }
            PermissionSet.RevertAssert();

            m_ServiceHostActivator.Open();

            State = CommunicationState.Opened;

            Opened(this,EventArgs.Empty);
         }
         catch
         {
            State = CommunicationState.Faulted;
         }
      }
 public bool Build(X509Certificate2 certificate)
 {
     lock (this.m_syncRoot)
     {
         if ((certificate == null) || certificate.CertContext.IsInvalid)
         {
             throw new ArgumentException(SR.GetString("Cryptography_InvalidContextHandle"), "certificate");
         }
         new StorePermission(StorePermissionFlags.EnumerateCertificates | StorePermissionFlags.OpenStore).Demand();
         X509ChainPolicy chainPolicy = this.ChainPolicy;
         if ((chainPolicy.RevocationMode == X509RevocationMode.Online) && ((certificate.Extensions["2.5.29.31"] != null) || (certificate.Extensions["1.3.6.1.5.5.7.1.1"] != null)))
         {
             PermissionSet set = new PermissionSet(PermissionState.None);
             set.AddPermission(new WebPermission(PermissionState.Unrestricted));
             set.AddPermission(new StorePermission(StorePermissionFlags.AddToStore));
             set.Demand();
         }
         this.Reset();
         if (BuildChain(this.m_useMachineContext ? new IntPtr(1L) : new IntPtr(0L), certificate.CertContext, chainPolicy.ExtraStore, chainPolicy.ApplicationPolicy, chainPolicy.CertificatePolicy, chainPolicy.RevocationMode, chainPolicy.RevocationFlag, chainPolicy.VerificationTime, chainPolicy.UrlRetrievalTimeout, ref this.m_safeCertChainHandle) != 0)
         {
             return false;
         }
         this.Init();
         CAPIBase.CERT_CHAIN_POLICY_PARA pPolicyPara = new CAPIBase.CERT_CHAIN_POLICY_PARA(Marshal.SizeOf(typeof(CAPIBase.CERT_CHAIN_POLICY_PARA)));
         CAPIBase.CERT_CHAIN_POLICY_STATUS pPolicyStatus = new CAPIBase.CERT_CHAIN_POLICY_STATUS(Marshal.SizeOf(typeof(CAPIBase.CERT_CHAIN_POLICY_STATUS)));
         pPolicyPara.dwFlags = (uint) chainPolicy.VerificationFlags;
         if (!CAPISafe.CertVerifyCertificateChainPolicy(new IntPtr(1L), this.m_safeCertChainHandle, ref pPolicyPara, ref pPolicyStatus))
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
         CAPISafe.SetLastError(pPolicyStatus.dwError);
         return (pPolicyStatus.dwError == 0);
     }
 }
        public void GeneratedTypeForAdditionalInterfaceWithMethodsHavingSignaturesMatchingMethodsInTheBaseClassIsVerifiable()
        {
            PermissionSet grantSet = new PermissionSet(PermissionState.None);
            grantSet.AddPermission(
                new SecurityPermission(
                    SecurityPermissionFlag.Execution
                    | SecurityPermissionFlag.ControlEvidence
                    | SecurityPermissionFlag.ControlPolicy));
            grantSet.AddPermission(
                new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess
                    | ReflectionPermissionFlag.MemberAccess));
            grantSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted));

            AppDomain sandbox =
                AppDomain.CreateDomain(
                    "sandbox",
                    AppDomain.CurrentDomain.Evidence,
                    new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory },
                    grantSet);

            sandbox.DoCallBack(() =>
            {
                InterceptingClassGenerator generator =
                    new InterceptingClassGenerator(typeof(MainType), typeof(IDoSomething), typeof(IDoSomethingToo));
                Type generatedType = generator.GenerateType();
            });
        }
Example #8
0
        public static PluginHost CreateSandbox(string applicationBasePath)
        {
            var rand = Path.GetRandomFileName();

            var setup = new AppDomainSetup()
            {
                ApplicationBase = applicationBasePath,
                ApplicationName = rand,
                ConfigurationFile = "", // DO not set to empty string if we want to use the conf file from this domain
                DisallowBindingRedirects = true,
                DisallowCodeDownload = true,
                DisallowPublisherPolicy = true
            };

            var permissions = new PermissionSet(PermissionState.None);
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            permissions.AddPermission(
                new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.AllAccess,
                    applicationBasePath));

            // If we want to enable NLog (for example) to read our configuration file
            permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.PathDiscovery,
                @"C:\Dev\POC\Krang\src\Krang.App\bin\Debug\Krang.App.vshost.exe.Config"));

            var domain = AppDomain.CreateDomain(rand, null, setup, permissions,
                typeof(PluginHost).Assembly.Evidence.GetHostEvidence<StrongName>(),
                typeof(Plugin).Assembly.Evidence.GetHostEvidence<StrongName>());

            return (PluginHost)Activator.CreateInstanceFrom(domain, typeof(PluginHost).Assembly.ManifestModule.FullyQualifiedName, typeof(PluginHost).FullName).Unwrap();
        }
Example #9
0
        static XmlILModule() {
            AssemblyName asmName;
            AssemblyBuilder asmBldr;

            CreateModulePermissionSet = new PermissionSet(PermissionState.None);
            // CreateDelegate demands MemberAccess permission
            CreateModulePermissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            // DynamicMethod constructor demands ControlEvidence permissions. 
            // Emitting symbols in DefineDynamicModule (to allow to debug the stylesheet) requires UnmanagedCode permission. 
            CreateModulePermissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.UnmanagedCode));

            AssemblyId = 0;

            // 1. LRE assembly only needs to execute
            // 2. No temp files need be created
            // 3. Never allow assembly to Assert permissions
            asmName = CreateAssemblyName();
            asmBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);

            try {
                CreateModulePermissionSet.Assert();

                // Add custom attribute to assembly marking it as security transparent so that Assert will not be allowed
                // and link demands will be converted to full demands.
                asmBldr.SetCustomAttribute(new CustomAttributeBuilder(XmlILConstructors.Transparent, new object[] {}));

                // Store LREModule once.  If multiple threads are doing this, then some threads might get different
                // modules.  This is OK, since it's not mandatory to share, just preferable.
                LREModule = asmBldr.DefineDynamicModule("System.Xml.Xsl.CompiledQuery", false);
            }
            finally {
                CodeAccessPermission.RevertAssert();
            }
        }
        private static AppDomain CreateSandboxDomain()
        {
            // Normally from a security perspective we'd put the sandboxed app in its own
            // base directory, but to make things easier (so we don't have to copy the NUnit
            // assembly, etc.) we'll just mirror the current test domain settings.
            var info = new AppDomainSetup
            {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                PrivateBinPath = AppDomain.CurrentDomain.RelativeSearchPath
            };

            // Grant set is the same set of permissions as ASP.NET medium trust EXCEPT
            // it excludes the FileIOPermission, IsolatedStorageFilePermission, and PrintingPermission.
            var grantSet = new PermissionSet(null);
            grantSet.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium));
            grantSet.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            grantSet.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP;TMP;USERNAME;OS;COMPUTERNAME"));
            grantSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.ControlThread | SecurityPermissionFlag.ControlPrincipal | SecurityPermissionFlag.RemotingConfiguration));
            grantSet.AddPermission(new SmtpPermission(SmtpAccess.Connect));
            grantSet.AddPermission(new SqlClientPermission(PermissionState.Unrestricted));
            grantSet.AddPermission(new TypeDescriptorPermission(PermissionState.Unrestricted));
            grantSet.AddPermission(new WebPermission(PermissionState.Unrestricted));
            grantSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

            return AppDomain.CreateDomain("Sandbox", null, info, grantSet);
        }
 private static PermissionSet Create_permission_set_for_sandbox_AppDomain(string beitragspfad)
 {
     PermissionSet permissionSet = new PermissionSet(PermissionState.None);
     permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
     permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, beitragspfad));
     return permissionSet;
 }
Example #12
0
        public int Fill(DataSet dataSet, object ADODBRecordSet, string srcTable)
        {
            System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);
            permissionSet.AddPermission(OleDbConnection.ExecutePermission); // MDAC 77737
            permissionSet.AddPermission(new System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode));
            permissionSet.Demand();

            IntPtr hscp;

            Bid.ScopeEnter(out hscp, "<oledb.OleDbDataAdapter.Fill|API> %d#, dataSet, ADODBRecordSet, srcTable='%ls'\n", ObjectID, srcTable);
            try {
                if (null == dataSet)
                {
                    throw ADP.ArgumentNull("dataSet");
                }
                if (null == ADODBRecordSet)
                {
                    throw ADP.ArgumentNull("adodb");
                }
                if (ADP.IsEmpty(srcTable))
                {
                    throw ADP.FillRequiresSourceTableName("srcTable");
                }
                // user was required to have UnmanagedCode Permission just to create ADODB
                // (new SecurityPermission(SecurityPermissionFlag.UnmanagedCode)).Demand();
                return(FillFromADODB((object)dataSet, ADODBRecordSet, srcTable, true));
            }
            finally {
                Bid.ScopeLeave(ref hscp);
            }
        }
Example #13
0
        public static PermissionSet GetDefaultScriptPermissionSet()
        {
            PermissionSet internalDefScriptPermSet = new PermissionSet(PermissionState.None);

            internalDefScriptPermSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            internalDefScriptPermSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));

            return internalDefScriptPermSet;
        }
Example #14
0
        public static PluginHost Create(string pluginId, IDictionary<string, object> config)
        {
            var currentDirectory = Directory.GetCurrentDirectory();

            var setup = new AppDomainSetup
            {
                ApplicationBase = currentDirectory,
                ApplicationName = pluginId,
                ConfigurationFile = "", // DO not set to empty string if we want to use the conf file from this domain
                DisallowBindingRedirects = true,
                DisallowCodeDownload = true,
                DisallowPublisherPolicy = true
            };

            var permissions = new PermissionSet(PermissionState.None);

            if (config.ContainsKey("Permissions") && config["Permissions"] != null)
            {
                var securityElement = SecurityElement.FromString(config["Permissions"].ToString());

                if (securityElement != null)
                {
                    permissions.FromXml(securityElement);
                }
            }

            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence // To get nice exceptions with permission demands.
                | SecurityPermissionFlag.ControlPolicy   // See ^
                | SecurityPermissionFlag.Execution       // To allow the plugin to execute
                ));

            // WCF hosting for JSONRPC
            permissions.AddPermission(new WebPermission(NetworkAccess.Connect | NetworkAccess.Accept,
                new Regex(@"http://localhost:31337/hadouken\.plugins.*")));

            // Isolated storage
            permissions.AddPermission(new IsolatedStorageFilePermission(PermissionState.Unrestricted));

            var ev = new Evidence(new EvidenceBase[] {new Url(config["Url"].ToString())}, null);

            var fxAsm = Assembly.LoadFile(Path.Combine(currentDirectory, FxAssembly));
            var domain = AppDomain.CreateDomain(pluginId, ev, setup, permissions,
                typeof (PluginHost).Assembly.Evidence.GetHostEvidence<StrongName>(),
                fxAsm.Evidence.GetHostEvidence<StrongName>());

            return (PluginHost) Activator.CreateInstanceFrom(
                domain,
                typeof (PluginHost).Assembly.ManifestModule.FullyQualifiedName,
                typeof (PluginHost).FullName,
                false,
                BindingFlags.Default,
                null,
                new object[] {pluginId, config},
                null,
                null).Unwrap();
        }
Example #15
0
        public static AppDomain CreatePartialTrustDomain()
        {
            AppDomainSetup setup = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory, PrivateBinPath = AppDomain.CurrentDomain.RelativeSearchPath };
            PermissionSet permissions = new PermissionSet(null);
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            permissions.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new SocketPermission(PermissionState.Unrestricted));

            return AppDomain.CreateDomain("Partial Trust Sandbox", AppDomain.CurrentDomain.Evidence, setup, permissions);
        }
Example #16
0
 public static AppDomain CreateSandbox()
 {
     var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase };
     var permissionSet = new PermissionSet(PermissionState.None);
     permissionSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.NoFlags));
     permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
     permissionSet.AddPermission(new FileIOPermission(PermissionState.Unrestricted)); // TODO: !!!
     var appDomain = AppDomain.CreateDomain("Sandbox", null, setup, permissionSet);
     return appDomain;
 }
        public void SetMethod()
        {
            ReflectionPermission          rp  = new ReflectionPermission(ReflectionPermissionFlag.AllFlags);
            IsolatedStorageFilePermission isp = new IsolatedStorageFilePermission(PermissionState.Unrestricted);

            System.Security.PermissionSet ps = new System.Security.PermissionSet(PermissionState.None);
            ps.AddPermission(rp);
            ps.AddPermission(isp);
            ps.Demand();
        }
Example #18
0
        private static PermissionSet CreateInternetSet() {
            PermissionSet permSet = new PermissionSet(PermissionState.None);
            permSet.AddPermission(new FileDialogPermission(FileDialogPermissionAccess.Open));
#pragma warning disable 618
            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
#pragma warning restore 618
            permSet.AddPermission(new UIPermission(UIPermissionWindow.SafeTopLevelWindows, UIPermissionClipboard.OwnClipboard));
            return permSet;
            

        }
 internal static PermissionSet _UnsafeGetAssertPermSet()
 {
     PermissionSet set = new PermissionSet(PermissionState.None);
     RegistryPermission perm = new RegistryPermission(PermissionState.Unrestricted);
     set.AddPermission(perm);
     EnvironmentPermission permission2 = new EnvironmentPermission(PermissionState.Unrestricted);
     set.AddPermission(permission2);
     SecurityPermission permission3 = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
     set.AddPermission(permission3);
     return set;
 }
    public static PermissionSet CreatePermissionSet(bool includeReflectionPermission)
    {
      PermissionSet permissionsSet = new PermissionSet(null);
      permissionsSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
      permissionsSet.AddPermission(new SocketPermission(PermissionState.Unrestricted));
      permissionsSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
      permissionsSet.AddPermission(new DnsPermission(PermissionState.Unrestricted));

      if (includeReflectionPermission) permissionsSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));

      return permissionsSet;
    }
Example #21
0
		private static string GetApplicationInstanceId(this Assembly entry)
		{
			var set = new PermissionSet(PermissionState.None);
			set.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
			set.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
			set.Assert();

			var typeLibGuidForAssembly = Marshal.GetTypeLibGuidForAssembly(entry);
			var strArray = entry.GetName().Version.ToString().Split(".".ToCharArray());
			PermissionSet.RevertAssert();

			return typeLibGuidForAssembly + strArray[0] + "." + strArray[1];
		}
		public void CanReflectOnSecurityExceptionWithoutPermission()
		{
			SecurityPermission denyPermission
				= new SecurityPermission(SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence);
			PermissionSet permissions = new PermissionSet(PermissionState.None);
			permissions.AddPermission(denyPermission);
			permissions.Deny();

			SecurityException exception = null;
			try
			{
				DemandException(denyPermission);
			}
			catch (SecurityException e)
			{
				exception = e;
			}
			
			ExceptionFormatter formatter = new ExceptionFormatter();

			String message = formatter.GetMessage(exception);
			Match demandedMatch = DemandedEntryRegex.Match(message);
			Assert.IsNotNull(demandedMatch);
			Assert.AreEqual(Resources.PropertyAccessFailed, demandedMatch.Groups[1].Value);

			CodeAccessPermission.RevertDeny();

			message = formatter.GetMessage(exception);
			demandedMatch = DemandedEntryRegex.Match(message);
			Assert.IsNotNull(demandedMatch);
			Assert.AreNotEqual(Resources.PropertyAccessFailed, demandedMatch.Groups[1].Value);
		}
 /// <summary>
 /// Checks to see if DNS information is available to the caller
 /// 
 /// </summary>
 /// 
 /// <returns/>
 public bool GetIsDnsAvailable()
 {
   PermissionSet permissionSet = new PermissionSet(PermissionState.None);
   DnsPermission dnsPermission = new DnsPermission(PermissionState.Unrestricted);
   permissionSet.AddPermission((IPermission) dnsPermission);
   return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
 }
Example #24
0
 private static bool CanWriteToFolder(string folder)
 {
     var permission = new FileIOPermission(FileIOPermissionAccess.Write, folder);
     var permissionSet = new PermissionSet(PermissionState.None);
     permissionSet.AddPermission(permission);
     return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
 }
 /// <summary>
 /// Checks to see if Registry access is available to the caller
 /// 
 /// </summary>
 /// 
 /// <returns/>
 public bool GetIsRegistryAvailable()
 {
   PermissionSet permissionSet = new PermissionSet(PermissionState.None);
   RegistryPermission registryPermission = new RegistryPermission(PermissionState.Unrestricted);
   permissionSet.AddPermission((IPermission) registryPermission);
   return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
 }
        static void Main(string[] args)
        {
            //Setting the AppDomainSetup. It is very important to set the ApplicationBase to a folder 
            //other than the one in which the sandboxer resides.
            AppDomainSetup adSetup = new AppDomainSetup();
            adSetup.ApplicationBase = Path.GetFullPath(pathToUntrusted);

            //Setting the permissions for the AppDomain. We give the permission to execute and to 
            //read/discover the location where the untrusted code is loaded.
            PermissionSet permSet = new PermissionSet(PermissionState.None);
            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            //We want the sandboxer assembly's strong name, so that we can add it to the full trust list.
            StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>();

            //Now we have everything we need to create the AppDomain, so let's create it.
            AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);

            //Use CreateInstanceFrom to load an instance of the Sandboxer class into the
            //new AppDomain. 
            ObjectHandle handle = Activator.CreateInstanceFrom(
                newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName,
                typeof(Sandboxer).FullName
                );
            //Unwrap the new domain instance into a reference in this domain and use it to execute the 
            //untrusted code.
            Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();
            newDomainInstance.ExecuteUntrustedCode(untrustedAssembly, untrustedClass, entryPoint, parameters);
        }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="args"></param>
    public static void Main (string [] args) {
      if (args.Length < 4 || args.Length > 5) {
        Console.WriteLine ("Usage: GlPostProcess.exe in.dll out.dll Tao.OpenGl.snk Tao.OpenGl.Gl [Tao.OpenGl.ContextGl]");
        return;
      }

      string inName = args[0];
      string outName = args[1];
      string typeName = args[3];
      string snkFile = null;
      if (args[2] != "")
        snkFile = args[2];
      string instanceTypeName = null;

      if (args.Length == 5)
        instanceTypeName = args[4];

      string outDir = System.IO.Path.GetDirectoryName(outName);
      string outDll = System.IO.Path.GetFileName(outName);
      string outNameBase = System.IO.Path.GetFileNameWithoutExtension(outName);

      // The MS runtime doesn't support a bunch of queries on
      // dynamic modules, so we have to track this stuff ourselves
      field_hash = new Hashtable();

      // load the input DLL as an Assembly
      Assembly inputAssembly = Assembly.LoadFrom(inName);

      // the calli instructions are unverifiable
      PermissionSet reqPermSet = new PermissionSet(PermissionState.None);
      reqPermSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SkipVerification));

      AssemblyName outAsName = new AssemblyName();
      outAsName.Name = outNameBase;
      if (snkFile != null)
        outAsName.KeyPair = new StrongNameKeyPair(File.Open(snkFile, FileMode.Open, FileAccess.Read));

      // create a dynamic assembly
      AssemblyBuilder abuilder = AppDomain.CurrentDomain.DefineDynamicAssembly
        (outAsName, AssemblyBuilderAccess.Save, outDir != null && outDir.Length > 0 ? outDir : null,
        reqPermSet, null, null);
      abuilder.SetCustomAttribute (GetCLSCompliantCAB (true));

      // go through and copy over custom attributes
      //object [] assemblyAttrs = inputAssembly.GetCustomAttributes (false);
      // copy over references
      //AssemblyName [] assemblyRefs = inputAssembly.GetReferencedAssemblies ();

      // create a dynamic module
      ModuleBuilder mbuilder = abuilder.DefineDynamicModule(outAsName.Name, outDll);
      mbuilder.SetCustomAttribute (GetCLSCompliantCAB (true));
      mbuilder.SetCustomAttribute (GetUnverifiableCodeCAB ());

      ProcessType (mbuilder, inputAssembly, typeName, false);
      if (instanceTypeName != null)
        ProcessType (mbuilder, inputAssembly, instanceTypeName, false);

      mbuilder.CreateGlobalFunctions();
      abuilder.Save(outDll);
    }
Example #28
0
        private static PermissionSet CreateSkipVerificationSet() {
            PermissionSet permSet = new PermissionSet(PermissionState.None);
#pragma warning disable 618
            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.SkipVerification));
#pragma warning restore 618
            return permSet;
        }
        public void ReflectionFormatterReadSecurityExceptionPropertiesWithoutPermissionTest()
        {
            SecurityPermission denyPermission
                = new SecurityPermission(SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.ControlEvidence);
            PermissionSet permissions = new PermissionSet(PermissionState.None);
            permissions.AddPermission(denyPermission);
            permissions.Deny();

            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);

            SecurityException exception = null;
            try
            {
                DemandException(denyPermission);
            }
            catch (SecurityException e)
            {
                exception = e;
            }

            MockTextExceptionFormatter formatter = new MockTextExceptionFormatter(writer, exception, Guid.Empty);
            formatter.Format();

            CodeAccessPermission.RevertDeny();

            formatter = new MockTextExceptionFormatter(writer, exception, Guid.Empty);
            formatter.Format();
            Assert.AreEqual(exception.Demanded.ToString(), formatter.properties["Demanded"]);
        }
	// Determine if a specific permission has been granted.
	public static bool IsGranted(IPermission perm)
			{
				// Bail out if the requested permission is null.
				if(perm == null)
				{
					return true;
				}

				// Get the current permission state.
				ClrPermissions current = ClrSecurity.GetPermissionsFrom(1);
				if(current == null)
				{
					// Null is equivalent to "unrestricted".
					return true;
				}

				// Build a permission set with just this permission.
				PermissionSet set = new PermissionSet(PermissionState.None);
				set.AddPermission(perm);

				// If "PermitOnly" is set, then only check that set.
				if(current.permitOnly != null)
				{
					return set.IsSubsetOf(current.permitOnly);
				}

				// The permission must be granted, but not denied.
				if(!set.IsSubsetOf(current.granted) ||
				   set.IsSubsetOf(current.denied))
				{
					return false;
				}
				return true;
			}
Example #31
0
        public static void Socket()
        {
            var set = new PermissionSet(PermissionState.None);
            set.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            set.AddPermission(new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "173.194.32.38", 80));
            set.Assert();

            var client = new TcpClient();
            client.Connect("173.194.32.38", 80);

            Console.WriteLine("Connected to google: {0}", client.Connected);

            client.Close();

            CodeAccessPermission.RevertAssert();
        }
Example #32
0
        public static bool NeedsAdministratorRights()
        {
            var permissionSet = new PermissionSet(PermissionState.None);
            var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, HostsFileManager.Filename);
            permissionSet.AddPermission(writePermission);

            return permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet);
        }
 protected internal override System.Security.PermissionSet CreatePermissionSet() {
     System.Security.PermissionSet permissionSet;
     if (PossiblePrompt) {
         permissionSet = new NamedPermissionSet("FullTrust");
     }
     else {
         permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);
         permissionSet.AddPermission(new OleDbPermission(this));
     }
     return permissionSet;
 }
Example #34
0
 protected internal override System.Security.PermissionSet CreatePermissionSet()
 {
     System.Security.PermissionSet permissionSet;
     if (ContainsKey(KEY.SaveFile))
     {
         permissionSet = new NamedPermissionSet("FullTrust");
     }
     else
     {
         permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);
         permissionSet.AddPermission(new OdbcPermission(this));
     }
     return(permissionSet);
 }
Example #35
0
        public void AddPermissionSet(PEAPI.SecurityAction sec_action, SSPermissionSet perm_set)
        {
            SSPermissionSet ps = (SSPermissionSet)permissionset_table [sec_action];

            if (ps == null)
            {
                permissionset_table [sec_action] = perm_set;
                return;
            }

            foreach (IPermission iper in perm_set)
            {
                ps.AddPermission(iper);
            }
        }
Example #36
0
        internal static void ResolveIdentityPermissions(PermissionSet ps, Evidence evidence)
        {
            // in 2.0 identity permissions can now be unrestricted
            if (ps.IsUnrestricted())
            {
                return;
            }

            // Only host evidence are used for policy resolution
            IEnumerator ee = evidence.GetHostEnumerator();

            while (ee.MoveNext())
            {
                IIdentityPermissionFactory ipf = (ee.Current as IIdentityPermissionFactory);
                if (ipf != null)
                {
                    IPermission p = ipf.CreateIdentityPermission(evidence);
                    ps.AddPermission(p);
                }
            }
        }
Example #37
0
        // Permit only the permissions in this set.
        public virtual void PermitOnly()
        {
            // Demand the permission first, because we cannot permit it
            // for exclusive access if we are not allowed have it at all.
            Demand();

            // Create a permission set and copy all CA objects into it.
            PermissionSet        set = new PermissionSet(PermissionState.None);
            int                  posn;
            CodeAccessPermission perm;

            for (posn = 0; posn < permissions.Count; ++posn)
            {
                perm = (permissions[posn] as CodeAccessPermission);
                if (perm != null)
                {
                    set.AddPermission(perm.Copy());
                }
            }

            // Set the current "PermitOnly" context on the call stack.
            CodeAccessPermission.PermitOnly(set, 2);
        }
Example #38
0
        // Deny permissions to the caller.
        internal void Deny(int skipFrames)
        {
            // Add the permission to the denied permissions set.
            ClrPermissions current;

            current = ClrSecurity.GetPermissionsFrom(skipFrames);
            PermissionSet set = new PermissionSet(PermissionState.None);

            set.AddPermission(this.Copy());
            if (current == null)
            {
                // Initialize the permissions context to "allow
                // everything except this permission object".
                current = new ClrPermissions
                              (new PermissionSet(PermissionState.Unrestricted),
                              set, null);
            }
            else
            {
                current = current.SetDenied(set.Union(current.denied));
            }
            ClrSecurity.SetPermissions(current, skipFrames);
        }
Example #39
0
        // 2.0 metadata format

        internal static PermissionSet CreateFromBinaryFormat(byte[] data)
        {
            if ((data == null) || (data [0] != 0x2E) || (data.Length < 2))
            {
                string msg = Locale.GetText("Invalid data in 2.0 metadata format.");
                throw new SecurityException(msg);
            }

            int           pos     = 1;
            int           numattr = ReadEncodedInt(data, ref pos);
            PermissionSet ps      = new PermissionSet(PermissionState.None);

            for (int i = 0; i < numattr; i++)
            {
                IPermission p = ProcessAttribute(data, ref pos);
                if (p == null)
                {
                    string msg = Locale.GetText("Unsupported data found in 2.0 metadata format.");
                    throw new SecurityException(msg);
                }
                ps.AddPermission(p);
            }
            return(ps);
        }
Example #40
0
        // Determine if a specific permission has been granted.
        public static bool IsGranted(IPermission perm)
        {
            // Bail out if the requested permission is null.
            if (perm == null)
            {
                return(true);
            }

            // Get the current permission state.
            ClrPermissions current = ClrSecurity.GetPermissionsFrom(1);

            if (current == null)
            {
                // Null is equivalent to "unrestricted".
                return(true);
            }

            // Build a permission set with just this permission.
            PermissionSet set = new PermissionSet(PermissionState.None);

            set.AddPermission(perm);

            // If "PermitOnly" is set, then only check that set.
            if (current.permitOnly != null)
            {
                return(set.IsSubsetOf(current.permitOnly));
            }

            // The permission must be granted, but not denied.
            if (!set.IsSubsetOf(current.granted) ||
                set.IsSubsetOf(current.denied))
            {
                return(false);
            }
            return(true);
        }
Example #41
0
        public PermissionSet Resolve(Evidence evidence, PermissionSet request)
        {
#if _DEBUG
            if (debug)
            {
                DEBUG_OUT("PolicyManager::Resolve");
                IEnumerator evidenceEnumerator = evidence.GetEnumerator();
                DEBUG_OUT("Evidence:");
                while (evidenceEnumerator.MoveNext())
                {
                    Object obj = evidenceEnumerator.Current;
                    if (obj is Site)
                    {
                        DEBUG_OUT(((Site)obj).ToXml().ToString());
                    }
                    else if (obj is Zone)
                    {
                        DEBUG_OUT(((Zone)obj).ToXml().ToString());
                    }
                    else if (obj is Url)
                    {
                        DEBUG_OUT(((Url)obj).ToXml().ToString());
                    }
                    else if (obj is StrongName)
                    {
                        DEBUG_OUT(((StrongName)obj).ToXml().ToString());
                    }
                    else if (obj is PermissionRequestEvidence)
                    {
                        DEBUG_OUT(((PermissionRequestEvidence)obj).ToXml().ToString());
                    }
                }
            }
#endif

            // We set grant to null to represent "AllPossible"

            PermissionSet   grant = null;
            PolicyStatement policy;
            PolicyLevel     currentLevel = null;

            IEnumerator levelEnumerator = m_levels.GetEnumerator();

            char[] serializedEvidence = MakeEvidenceArray(evidence, false);
            int    count = evidence.Count;

            bool testApplicationLevels = false;

            while (levelEnumerator.MoveNext())
            {
                currentLevel = (PolicyLevel)levelEnumerator.Current;
                policy       = currentLevel.Resolve(evidence, count, serializedEvidence);

                // If the grant is "AllPossible", the intersection is just the other permission set.
                // Otherwise, do an inplace intersection (since we know we can alter the grant set since
                // it is a copy of the first policy statement's permission set).

                if (grant == null)
                {
                    grant = policy.PermissionSet;
                }
                else
                {
                    // An exception somewhere in here means that a permission
                    // failed some operation.  This simply means that it will be
                    // dropped from the grant set which is safe operation that
                    // can be ignored.

                    try
                    {
                        grant.InplaceIntersect(policy.GetPermissionSetNoCopy());
                    }
                    catch (Exception)
                    {
                    }
                }

    #if _DEBUG
                if (debug)
                {
                    DEBUG_OUT("Level = " + currentLevel.Label);
                    DEBUG_OUT("policy =\n" + policy.ToXml().ToString());
                    DEBUG_OUT("grant so far =\n" + grant.ToXml().ToString());
                }
    #endif

                if (grant.IsEmpty())
                {
                    break;
                }
                else if ((policy.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal)
                {
                    if (!currentLevel.Label.Equals("AppDomain"))
                    {
                        testApplicationLevels = true;
                    }

                    break;
                }
            }

            if (testApplicationLevels)
            {
                PolicyLevel appDomainLevel = null;

                for (int i = m_levels.Count - 1; i >= 0; --i)
                {
                    currentLevel = (PolicyLevel)m_levels[i];

                    if (currentLevel.Label.Equals("AppDomain"))
                    {
                        appDomainLevel = currentLevel;
                        break;
                    }
                }

                if (appDomainLevel != null)
                {
                    policy = appDomainLevel.Resolve(evidence, count, serializedEvidence);

                    grant.InplaceIntersect(policy.GetPermissionSetNoCopy());
                }
            }


    #if _DEBUG
            if (debug)
            {
                DEBUG_OUT("granted =\n" + grant.ToString());
                DEBUG_OUT("request =\n" + (request != null ? request.ToString() : "<null>"));
                DEBUG_OUT("awarded =\n" + (request != null ? grant.Intersect(request).ToString() : grant.ToString()));
            }
    #endif

            try
            {
                if (request != null)
                {
                    grant.InplaceIntersect(request);
                }
            }
            catch (Exception)
            {
            }

    #if _DEBUG
            if (debug)
            {
                DEBUG_OUT("granted after intersect w/ request =\n" + grant.ToString());
            }
    #endif

            // Each piece of evidence can possibly create an identity permission that we
            // need to add to our grant set.  Therefore, for all pieces of evidence that
            // implement the IIdentityPermissionFactory interface, ask it for its
            // adjoining identity permission and add it to the grant.

            IEnumerator enumerator = evidence.GetHostEnumerator();
            while (enumerator.MoveNext())
            {
                try
                {
                    Object obj = enumerator.Current;
                    IIdentityPermissionFactory factory = obj as IIdentityPermissionFactory;
                    if (factory != null)
                    {
                        IPermission perm = factory.CreateIdentityPermission(evidence);

                        if (perm != null)
                        {
                            grant.AddPermission(perm);
                        }
                    }
                }
                catch (Exception)
                {
                }
            }

    #if _DEBUG
            if (debug)
            {
                DEBUG_OUT("awarded with identity =\n" + grant.ToString());
            }
    #endif
            return(grant);
        }
Example #42
0
        [System.Security.SecurityCritical]  // auto-generated
        static private PermissionSet ResolvePolicy(Evidence evidence,
                                                   PermissionSet reqdPset,
                                                   PermissionSet optPset,
                                                   PermissionSet denyPset,
                                                   out PermissionSet denied,
                                                   bool checkExecutionPermission)
        {
            Contract.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled);

            if (executionSecurityPermission == null)
            {
                executionSecurityPermission = new SecurityPermission(SecurityPermissionFlag.Execution);
            }

            PermissionSet requested = null;
            PermissionSet optional;
            PermissionSet allowed;

            Exception savedException = null;

            // We don't want to recurse back into here as a result of a
            // stackwalk during resolution. So simply assert full trust (this
            // implies that custom permissions cannot use any permissions that
            // don't implement IUnrestrictedPermission.
            // PermissionSet.s_fullTrust.Assert();

            // The requested set is the union of the minimal request and the
            // optional request. Minimal request defaults to empty, optional
            // is "AllPossible" (includes any permission that can be defined)
            // which is symbolized by null.
            optional = optPset;

            if (reqdPset == null)
            {
                requested = optional;
            }
            else
            {
                // If optional is null, the requested set becomes null/"AllPossible".
                requested = optional == null ? null : reqdPset.Union(optional);
            }

            // Make sure that the right to execute is requested (if this feature is
            // enabled).

            if (requested != null && !requested.IsUnrestricted())
            {
                requested.AddPermission(executionSecurityPermission);
            }

            // If we aren't passed any evidence, just make an empty object
            if (evidence == null)
            {
                evidence = new Evidence();
            }

            allowed = polmgr.Resolve(evidence);
            // Intersect the grant with the RequestOptional
            if (requested != null)
            {
                allowed.InplaceIntersect(requested);
            }

            // Check that we were granted the right to execute.
            if (checkExecutionPermission)
            {
                if (!allowed.Contains(executionSecurityPermission) ||
                    (denyPset != null && denyPset.Contains(executionSecurityPermission)))
                {
                    throw new PolicyException(Environment.GetResourceString("Policy_NoExecutionPermission"),
                                              System.__HResults.CORSEC_E_NO_EXEC_PERM,
                                              savedException);
                }
            }

            // Check that we were granted at least the minimal set we asked for. Do
            // this before pruning away any overlap with the refused set so that
            // users have the flexability of defining minimal permissions that are
            // only expressable as set differences (e.g. allow access to "C:\" but
            // disallow "C:\Windows").
            if (reqdPset != null && !reqdPset.IsSubsetOf(allowed))
            {
                BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled");
                throw new PolicyException(Environment.GetResourceString("Policy_NoRequiredPermission"),
                                          System.__HResults.CORSEC_E_MIN_GRANT_FAIL,
                                          savedException);
            }

            // Remove any granted permissions that are safe subsets of some denied
            // permission. The remaining denied permissions (if any) are returned
            // along with the modified grant set for use in checks.
            if (denyPset != null)
            {
                BCLDebug.Assert(AppDomain.CurrentDomain.IsLegacyCasPolicyEnabled, "Evaluating assembly level declarative security without legacy CAS policy enabled");
                denied = denyPset.Copy();
                allowed.MergeDeniedSet(denied);
                if (denied.IsEmpty())
                {
                    denied = null;
                }
            }
            else
            {
                denied = null;
            }

            allowed.IgnoreTypeLoadFailures = true;

            return(allowed);
        }
Example #43
0
        internal static QuickCacheEntryType GenerateQuickCache(PolicyLevel level)
        {
            QuickCacheEntryType[] ExecutionMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.ExecutionZoneMyComputer,
              QuickCacheEntryType.ExecutionZoneIntranet,
              QuickCacheEntryType.ExecutionZoneInternet,
              QuickCacheEntryType.ExecutionZoneTrusted,
              QuickCacheEntryType.ExecutionZoneUntrusted };

            QuickCacheEntryType[] UnmanagedMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.UnmanagedZoneMyComputer,
              QuickCacheEntryType.UnmanagedZoneIntranet,
              QuickCacheEntryType.UnmanagedZoneInternet,
              QuickCacheEntryType.UnmanagedZoneTrusted,
              QuickCacheEntryType.UnmanagedZoneUntrusted };

            QuickCacheEntryType[] RequestSkipVerificationMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.RequestSkipVerificationZoneMyComputer,
              QuickCacheEntryType.RequestSkipVerificationZoneIntranet,
              QuickCacheEntryType.RequestSkipVerificationZoneInternet,
              QuickCacheEntryType.RequestSkipVerificationZoneTrusted,
              QuickCacheEntryType.RequestSkipVerificationZoneUntrusted };

            QuickCacheEntryType[] SkipVerificationMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.SkipVerificationZoneMyComputer,
              QuickCacheEntryType.SkipVerificationZoneIntranet,
              QuickCacheEntryType.SkipVerificationZoneInternet,
              QuickCacheEntryType.SkipVerificationZoneTrusted,
              QuickCacheEntryType.SkipVerificationZoneUntrusted };

            QuickCacheEntryType[] FullTrustMap = new QuickCacheEntryType[]
            { QuickCacheEntryType.FullTrustZoneMyComputer,
              QuickCacheEntryType.FullTrustZoneIntranet,
              QuickCacheEntryType.FullTrustZoneInternet,
              QuickCacheEntryType.FullTrustZoneTrusted,
              QuickCacheEntryType.FullTrustZoneUntrusted };

            QuickCacheEntryType accumulator = (QuickCacheEntryType)0;

            SecurityPermission execPerm      = new SecurityPermission(SecurityPermissionFlag.Execution);
            SecurityPermission unmanagedPerm = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
            SecurityPermission skipVerifPerm = new SecurityPermission(SecurityPermissionFlag.SkipVerification);

            Evidence noEvidence = new Evidence();

            PermissionSet policy = null;

            try
            {
                policy = level.Resolve(noEvidence).PermissionSet;

                if (policy.Contains(execPerm))
                {
                    accumulator |= QuickCacheEntryType.ExecutionAll;
                }

                if (policy.Contains(unmanagedPerm))
                {
                    accumulator |= QuickCacheEntryType.UnmanagedAll;
                }

                if (policy.Contains(skipVerifPerm))
                {
                    accumulator |= QuickCacheEntryType.SkipVerificationAll;
                }

                if (policy.IsUnrestricted())
                {
                    accumulator |= QuickCacheEntryType.FullTrustAll;
                }
            }
            catch (PolicyException)
            {
            }

            PermissionSet permSet = new PermissionSet(PermissionState.None);

            permSet.AddPermission(skipVerifPerm);
            PermissionRequestEvidence permRequest = new PermissionRequestEvidence(permSet, null, null);

            try
            {
                noEvidence.AddHost(permRequest);

                policy = level.Resolve(noEvidence).PermissionSet;

                if (policy.Contains(skipVerifPerm))
                {
                    accumulator |= QuickCacheEntryType.RequestSkipVerificationAll;
                }
            }
            catch (PolicyException)
            {
            }

            Array zones = Enum.GetValues(typeof(SecurityZone));

            for (int i = 0; i < zones.Length; ++i)
            {
                if (((SecurityZone)zones.GetValue(i)) == SecurityZone.NoZone)
                {
                    continue;
                }

                Evidence zoneEvidence = new Evidence();
                zoneEvidence.AddHost(new Zone((SecurityZone)zones.GetValue(i)));

                PermissionSet zonePolicy = null;

                try
                {
                    zonePolicy = level.Resolve(zoneEvidence).PermissionSet;

                    if (zonePolicy.Contains(execPerm))
                    {
                        accumulator |= ExecutionMap[i];
                    }

                    if (zonePolicy.Contains(unmanagedPerm))
                    {
                        accumulator |= UnmanagedMap[i];
                    }

                    if (zonePolicy.Contains(skipVerifPerm))
                    {
                        accumulator |= SkipVerificationMap[i];
                    }

                    if (zonePolicy.IsUnrestricted())
                    {
                        accumulator |= FullTrustMap[i];
                    }
                }
                catch (PolicyException)
                {
                }

                zoneEvidence.AddHost(permRequest);

                try
                {
                    zonePolicy = level.Resolve(zoneEvidence).PermissionSet;

                    if (zonePolicy.Contains(skipVerifPerm))
                    {
                        accumulator |= RequestSkipVerificationMap[i];
                    }
                }
                catch (PolicyException)
                {
                }
            }

            return(accumulator);
        }
        public static AppDomain GetMediumTrustDomain()
        {
            if (mediumTrustDomain == null)
            {
                var setup = new AppDomainSetup {
                    ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
                };
                var permissions = new System.Security.PermissionSet(null);
                // MEDIUM TRUST PERMISSION SET:
                //<IPermission
                //        class="DnsPermission"
                //        version="1"
                //        Unrestricted="true"
                // />
                permissions.AddPermission(new System.Net.DnsPermission(System.Security.Permissions.PermissionState.Unrestricted));
                //<IPermission
                //        class="EnvironmentPermission"
                //        version="1"
                //        Read="TEMP;TMP;USERNAME;OS;COMPUTERNAME"
                // />
                permissions.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP;TMP;USERNAME;OS;COMPUTERNAME"));
                //<IPermission
                //        class="FileIOPermission"
                //        version="1"
                //        Read="$AppDir$"
                //        Write="$AppDir$"
                //        Append="$AppDir$"
                //        PathDiscovery="$AppDir$"
                // />
                string appDir = Directory.GetCurrentDirectory();
                permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, appDir));
                permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write, appDir));
                permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.Append, appDir));
                permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.PathDiscovery, appDir));
                //<IPermission
                //        class="IsolatedStorageFilePermission"
                //        version="1"
                //        Allowed="AssemblyIsolationByUser"
                //        UserQuota="9223372036854775807"
                // />
                permissions.AddPermission(new IsolatedStorageFilePermission(PermissionState.Unrestricted)
                {
                    UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser, UserQuota = 9223372036854775807
                });
                //<IPermission
                //        class="PrintingPermission"
                //        version="1"
                //        Level="DefaultPrinting"
                // />
                // DEVNOTE(pqian): System.Drawing.Printing.PrintingPermission - not astoria related
                //<IPermission
                //        class="SecurityPermission"
                //        version="1"
                //        Flags="Execution, ControlThread, ControlPrincipal, RemotingConfiguration"
                ///>
                permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution | SecurityPermissionFlag.ControlThread | SecurityPermissionFlag.ControlPrincipal | SecurityPermissionFlag.RemotingConfiguration | SecurityPermissionFlag.SerializationFormatter));
                //<IPermission
                //        class="SmtpPermission"
                //        version="1"
                //        Access="Connect"
                // />
                permissions.AddPermission(new System.Net.Mail.SmtpPermission(System.Net.Mail.SmtpAccess.Connect));
                //<IPermission
                //        class="SqlClientPermission"
                //        version="1"
                //        Unrestricted="true"
                ///>
                permissions.AddPermission(new System.Data.SqlClient.SqlClientPermission(PermissionState.Unrestricted));
                //<IPermission
                //        class="TypeDescriptorPermission"
                //        version="1"
                //        Unrestricted="true"
                // />
                permissions.AddPermission(new TypeDescriptorPermission(PermissionState.Unrestricted));
                //<IPermission
                //        class="WebPermission"
                //        version="1"
                //        Unrestricted="true"
                // />
                permissions.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted));
                //<IPermission
                //        class="ReflectionPermission"
                //        version="1"
                //        Flags="RestrictedMemberAccess"/>
                permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

                mediumTrustDomain = AppDomain.CreateDomain("Partial Trust AppDomain: " + DateTime.Now.Ticks, null, setup, permissions);
            }

            return(mediumTrustDomain);
        }
 protected internal override System.Security.PermissionSet CreatePermissionSet()
 {
     System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None);
     permissionSet.AddPermission(new SqlClientPermission(this));
     return(permissionSet);
 }