Inheritance: ISecurityEncodable, ICollection, IStackWalk, IDeserializationCallback
 public PermissionSet(PermissionSet permSet) : this()
 {
     if (permSet == null)
     {
         this.Reset();
     }
     else
     {
         this.m_Unrestricted = permSet.m_Unrestricted;
         this.m_CheckedForNonCas = permSet.m_CheckedForNonCas;
         this.m_ContainsCas = permSet.m_ContainsCas;
         this.m_ContainsNonCas = permSet.m_ContainsNonCas;
         this.m_ignoreTypeLoadFailures = permSet.m_ignoreTypeLoadFailures;
         if (permSet.m_permSet != null)
         {
             this.m_permSet = new TokenBasedSet(permSet.m_permSet);
             for (int i = this.m_permSet.GetStartingIndex(); i <= this.m_permSet.GetMaxUsedIndex(); i++)
             {
                 object item = this.m_permSet.GetItem(i);
                 IPermission permission = item as IPermission;
                 ISecurityElementFactory factory = item as ISecurityElementFactory;
                 if (permission != null)
                 {
                     this.m_permSet.SetItem(i, permission.Copy());
                 }
                 else if (factory != null)
                 {
                     this.m_permSet.SetItem(i, factory.Copy());
                 }
             }
         }
     }
 }
Esempio n. 2
0
        // This method is called from unmanaged code in a temporary AppDomain, just to be able to call
        // the right AppDomain.CreateDomain overload.
        public static AppDomain CreateFullTrustSandbox()
        {
            try
            {
                Debug.Print("CreateSandboxAndInitialize - in loader AppDomain with Id: " + AppDomain.CurrentDomain.Id);

                PermissionSet pset = new PermissionSet(PermissionState.Unrestricted);
                AppDomainSetup loaderAppDomainSetup = AppDomain.CurrentDomain.SetupInformation;
                AppDomainSetup sandboxAppDomainSetup = new AppDomainSetup();
                sandboxAppDomainSetup.ApplicationName = loaderAppDomainSetup.ApplicationName;
                sandboxAppDomainSetup.ConfigurationFile = loaderAppDomainSetup.ConfigurationFile;
                sandboxAppDomainSetup.ApplicationBase = loaderAppDomainSetup.ApplicationBase;
                sandboxAppDomainSetup.ShadowCopyFiles = loaderAppDomainSetup.ShadowCopyFiles;
                sandboxAppDomainSetup.ShadowCopyDirectories = loaderAppDomainSetup.ShadowCopyDirectories;

                // create the sandboxed domain
                AppDomain sandbox = AppDomain.CreateDomain(
                    "FullTrustSandbox(" + AppDomain.CurrentDomain.FriendlyName + ")",
                    null,
                    sandboxAppDomainSetup,
                    pset);

                Debug.Print("CreateFullTrustSandbox - sandbox AppDomain created. Id: " + sandbox.Id);

                return sandbox;
            }
            catch (Exception ex)
            {
                Debug.Print("Error during CreateFullTrustSandbox: " + ex.ToString());
                return AppDomain.CurrentDomain;
            }

        }
Esempio n. 3
0
        public JintEngine(Options options) {
            Visitor = new ExecutionVisitor(options);
            permissionSet = new PermissionSet(PermissionState.None);
            Visitor.AllowClr = allowClr;
            MaxRecursions = 400;
	        MaxSteps = 100 * 1000;

            var global = Visitor.Global as JsObject;

            global["ToBoolean"] = Visitor.Global.FunctionClass.New(new Func<object, Boolean>(Convert.ToBoolean));
            global["ToByte"] = Visitor.Global.FunctionClass.New(new Func<object, Byte>(Convert.ToByte));
            global["ToChar"] = Visitor.Global.FunctionClass.New(new Func<object, Char>(Convert.ToChar));
            global["ToDateTime"] = Visitor.Global.FunctionClass.New(new Func<object, DateTime>(Convert.ToDateTime));
            global["ToDecimal"] = Visitor.Global.FunctionClass.New(new Func<object, Decimal>(Convert.ToDecimal));
            global["ToDouble"] = Visitor.Global.FunctionClass.New(new Func<object, Double>(Convert.ToDouble));
            global["ToInt16"] = Visitor.Global.FunctionClass.New(new Func<object, Int16>(Convert.ToInt16));
            global["ToInt32"] = Visitor.Global.FunctionClass.New(new Func<object, Int32>(Convert.ToInt32));
            global["ToInt64"] = Visitor.Global.FunctionClass.New(new Func<object, Int64>(Convert.ToInt64));
            global["ToSByte"] = Visitor.Global.FunctionClass.New(new Func<object, SByte>(Convert.ToSByte));
            global["ToSingle"] = Visitor.Global.FunctionClass.New(new Func<object, Single>(Convert.ToSingle));
            global["ToString"] = Visitor.Global.FunctionClass.New(new Func<object, String>(Convert.ToString));
            global["ToUInt16"] = Visitor.Global.FunctionClass.New(new Func<object, UInt16>(Convert.ToUInt16));
            global["ToUInt32"] = Visitor.Global.FunctionClass.New(new Func<object, UInt32>(Convert.ToUInt32));
            global["ToUInt64"] = Visitor.Global.FunctionClass.New(new Func<object, UInt64>(Convert.ToUInt64));

            BreakPoints = new List<BreakPoint>();
        }
Esempio n. 4
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);
            }
        }
Esempio n. 5
0
 private System.Security.PermissionSet GetInputPermissionSet()
 {
     if (this._inputPermissionSet == null)
     {
         XmlElement inputPermissionSetElement = this.GetInputPermissionSetElement();
         if (this._preserveFullTrustPermissionSet)
         {
             XmlAttribute namedItem = (XmlAttribute)inputPermissionSetElement.Attributes.GetNamedItem(XmlUtil.TrimPrefix("asmv2:Unrestricted"));
             this._isFullTrust = (namedItem != null) && bool.Parse(namedItem.Value);
             if (this._isFullTrust)
             {
                 XmlDocument document = new XmlDocument();
                 document.AppendChild(document.ImportNode(inputPermissionSetElement, true));
                 document.DocumentElement.Attributes.RemoveNamedItem(XmlUtil.TrimPrefix("asmv2:Unrestricted"));
                 inputPermissionSetElement = document.DocumentElement;
             }
             this._inputPermissionSet = SecurityUtilities.XmlToPermissionSet(inputPermissionSetElement);
         }
         else
         {
             this._inputPermissionSet = SecurityUtilities.XmlToPermissionSet(inputPermissionSetElement);
             this._isFullTrust        = this._inputPermissionSet.IsUnrestricted();
         }
     }
     return(this._inputPermissionSet);
 }
 public void AddDeclarativeSecurity(SecurityAction action, PermissionSet pset)
 {
     lock (this.SyncRoot)
     {
         this.AddDeclarativeSecurityNoLock(action, pset);
     }
 }
        private static AppDomain CreatePartialTrustAppDomain()
        {
            PermissionSet permissions = new PermissionSet(PermissionState.None);
            permissions.AddPermission(new AspNetHostingPermission(AspNetHostingPermissionLevel.Medium));
            permissions.AddPermission(new DnsPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "TEMP;TMP;USERNAME;OS;COMPUTERNAME"));
            permissions.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, AppDomain.CurrentDomain.BaseDirectory));
            permissions.AddPermission(new IsolatedStorageFilePermission(PermissionState.None) { UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser, UserQuota = Int64.MaxValue });
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlThread));
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPrincipal));
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration));
            permissions.AddPermission(new SmtpPermission(SmtpAccess.Connect));
            permissions.AddPermission(new SqlClientPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new TypeDescriptorPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new WebPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

            AppDomainSetup setup = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory };

            setup.PartialTrustVisibleAssemblies = new string[]
            {
                "System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293",
                "System.Web.Extensions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9",
                "System.Web.Abstractions, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9",
                "System.Web.Routing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9",
                "System.ComponentModel.DataAnnotations, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9",
                "System.Web.DynamicData, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9",
                "System.Web.DataVisualization, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9",
                "System.Web.ApplicationServices, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9"
            };


            return AppDomain.CreateDomain("Partial Trust Sandbox", null, setup, permissions);
        }
 // Make an extremely restrictive permission set that allows only:
 // Execution Permission.
 private static PermissionSet MakeExecutionOnlyPermSet()
 {
     var pSet = new PermissionSet(PermissionState.None);
     var perm = new SecurityPermission(SecurityPermissionFlag.Execution);
     pSet.AddPermission(perm);
     return pSet;
 }
    /// <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);
    }
Esempio n. 10
0
        public static Task<GetManifestCompletedEventArgs> DownloadManifestAsync(this InPlaceHostingManager manager) {
            var tcs = new TaskCompletionSource<GetManifestCompletedEventArgs>();

            manager.GetManifestCompleted += (sender, e) => {
                if(e.Error != null) {
                    tcs.SetException(e.Error);
                    return;
                }

                var trust = new ApplicationTrust();
                var permissions = new PermissionSet(PermissionState.Unrestricted);
                var statement = new PolicyStatement(permissions);

                trust.DefaultGrantSet = statement;
                trust.ApplicationIdentity = e.ApplicationIdentity;
                trust.IsApplicationTrustedToRun = true;

                ApplicationSecurityManager.UserApplicationTrusts.Add(trust);

                tcs.SetResult(e);
            };

            manager.GetManifestAsync();

            return tcs.Task;
        }
Esempio n. 11
0
        /// <summary>
        /// Creates an AppDomain.
        /// </summary>
        /// <param name="applicationName">The application name for the new AppDomain, or null if none.</param>
        /// <param name="applicationBaseDirectory">The application base directory for the new AppDomain, or null to use the current one.</param>
        /// <param name="configurationFile">The configuration file for the new AppDomain, or null to use the current one.</param>
        /// <param name="enableShadowCopy">If true, enables shadow copying within the AppDomain.</param>
        /// <returns>The new AppDomain.</returns>
        public static AppDomain CreateAppDomain(string applicationName, string applicationBaseDirectory, string configurationFile, bool enableShadowCopy)
        {
            AppDomainSetup appDomainSetup = new AppDomainSetup();

            appDomainSetup.ApplicationName = applicationName ?? string.Empty;
            appDomainSetup.ApplicationBase = applicationBaseDirectory ?? AppDomain.CurrentDomain.BaseDirectory;

            if (configurationFile != null)
            {
                // NOTE: We can also use AppDomainSetup.SetConfigurationBytes but it only applies to
                //       CLR-internal configuration settings such as the assembly binding policy.
                //       In order for other configuration mechanisms to operate correctly, we must
                //       use a real configuration file on disk instead.
                appDomainSetup.ConfigurationFile = configurationFile;
            }

            if (enableShadowCopy)
            {
                appDomainSetup.ShadowCopyFiles = @"true";
                appDomainSetup.ShadowCopyDirectories = null;
            }

            // TODO: Might need to be more careful about how the Evidence is derived.
            Evidence evidence = AppDomain.CurrentDomain.Evidence;
            if (DotNetRuntimeSupport.IsUsingMono)
            {
                return AppDomain.CreateDomain(appDomainSetup.ApplicationName, evidence, appDomainSetup);
            }
            else
            {
                PermissionSet defaultPermissionSet = new PermissionSet(PermissionState.Unrestricted);
                StrongName[] fullTrustAssemblies = new StrongName[0];
                return AppDomain.CreateDomain(appDomainSetup.ApplicationName, evidence, appDomainSetup, defaultPermissionSet, fullTrustAssemblies);
            }
        }
 public PermissionRequestEvidence(PermissionSet request, PermissionSet optional, PermissionSet denied)
 {
     if (request == null)
     {
         this.m_request = null;
     }
     else
     {
         this.m_request = request.Copy();
     }
     if (optional == null)
     {
         this.m_optional = null;
     }
     else
     {
         this.m_optional = optional.Copy();
     }
     if (denied == null)
     {
         this.m_denied = null;
     }
     else
     {
         this.m_denied = denied.Copy();
     }
 }
Esempio n. 13
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;
        }
 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;
 }
Esempio n. 15
0
        /*!*/
        private static PermissionSet CreatePermissionSet()
        {
            #if CLR2
            string name = "Internet";
            bool foundName = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator e = SecurityManager.PolicyHierarchy();
            while (e.MoveNext()) {
                PolicyLevel level = (PolicyLevel)e.Current;
                PermissionSet levelSet = level.GetNamedPermissionSet(name);
                if (levelSet != null) {
                    foundName = true;
                    setIntersection = setIntersection.Intersect(levelSet);
                }
            }

            if (setIntersection == null || !foundName) {
                setIntersection = new PermissionSet(PermissionState.None);
            } else {
                setIntersection = new NamedPermissionSet(name, setIntersection);
            }

            return setIntersection;
            #else
            // this functionality is not available on Mono (AddHostEvidence is undefined), use dynamic to resolve it at runtime
            dynamic e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.Internet));
            return SecurityManager.GetStandardSandbox((Evidence)e);
            #endif
        }
Esempio n. 16
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);
 }
Esempio n. 17
0
        public void AddTo(CodeGen code_gen, PEAPI.MetaDataElement elem)
        {
            System.Text.UnicodeEncoding ue = new System.Text.UnicodeEncoding();
            foreach (DictionaryEntry entry in permissionset_table)
            {
                PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction)entry.Key;
                SSPermissionSet      ps         = (SSPermissionSet)entry.Value;

                code_gen.PEFile.AddDeclSecurity(sec_action,
                                                ue.GetBytes(ps.ToXml().ToString()),
                                                elem);
            }

            if (permissionset20_table == null)
            {
                return;
            }

            foreach (DictionaryEntry entry in permissionset20_table)
            {
                PEAPI.SecurityAction sec_action = (PEAPI.SecurityAction)entry.Key;
                MIPermissionSet      ps         = (MIPermissionSet)entry.Value;

                code_gen.PEFile.AddDeclSecurity(sec_action,
                                                ps.Resolve(code_gen),
                                                elem);
            }
        }
 [System.Security.SecurityCritical]  // auto-generated
 private static bool FrameDescSetHelper(FrameSecurityDescriptor secDesc,
                                        PermissionSet demandSet,
                                        out PermissionSet alteredDemandSet,
                                        RuntimeMethodHandleInternal rmh)
 {
     return secDesc.CheckSetDemand(demandSet, out alteredDemandSet, rmh);
 }
Esempio n. 19
0
		static bool TryProcessPermissionSetAttribute (SecurityDeclaration declaration, out PermissionSet set)
		{
			set = null;

			if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1)
				return false;

			var security_attribute = declaration.SecurityAttributes [0];
			if (!security_attribute.AttributeType.IsTypeOf ("System.Security.Permissions", "PermissionSetAttribute"))
				return false;

			var attribute = new SSP.PermissionSetAttribute ((SSP.SecurityAction) declaration.Action);

			var named_argument = security_attribute.Properties [0];
			string value = (string) named_argument.Argument.Value;
			switch (named_argument.Name) {
			case "XML":
				attribute.XML = value;
				break;
			case "Name":
				attribute.Name = value;
				break;
			default:
				throw new NotImplementedException (named_argument.Name);
			}

			set = attribute.CreatePermissionSet ();
			return true;
		}
        //Create a SandBox to load Assemblies with "Full Trust"
        public static ServiceBridge Sandbox(string assemblyFilename, string configPath, ResolveEventHandler handler)
        {
            var trustedLoadGrantSet = new PermissionSet(PermissionState.Unrestricted);
            var trustedLoadSetup = new AppDomainSetup();
            trustedLoadSetup.ApplicationBase = Path.GetDirectoryName(assemblyFilename);
            trustedLoadSetup.PrivateBinPath = Path.GetDirectoryName(assemblyFilename);
            //trustedLoadSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            trustedLoadSetup.ConfigurationFile = configPath;

            AppDomain.CurrentDomain.AssemblyResolve += handler;
            AppDomain appDomain = AppDomain.CreateDomain("ServiceBridge SandBox", null, trustedLoadSetup, trustedLoadGrantSet);
            appDomain.SetData("DataDirectory", configPath.Replace("Web.config", "App_Data"));

            ServiceBridge loader = appDomain.CreateInstanceAndUnwrap(
                typeof(ServiceBridge).Assembly.GetName().FullName,
                typeof(ServiceBridge).FullName,
                false,
                BindingFlags.Default,
                null,
                new object[] { assemblyFilename },
                CultureInfo.InvariantCulture,
                null) as ServiceBridge;

            return loader;
        }
Esempio n. 21
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();
        }
Esempio n. 22
0
		static AppDomain NewDomain () {
			PolicyStatement statement = new PolicyStatement(new PermissionSet(PermissionState.None),PolicyStatementAttribute.Nothing);
			PermissionSet ps = new PermissionSet(PermissionState.None);
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Assertion));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlAppDomain));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlDomainPolicy));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPolicy));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlPrincipal));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlThread));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Infrastructure));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.RemotingConfiguration));
			ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
			ps.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
			ps.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted));
			ps.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
			ps.AddPermission(new RegistryPermission(PermissionState.Unrestricted));
			ps.AddPermission(new IsolatedStorageFilePermission(PermissionState.Unrestricted));
			ps.AddPermission(new EventLogPermission(PermissionState.Unrestricted));
			ps.AddPermission(new PerformanceCounterPermission(PermissionState.Unrestricted));
			ps.AddPermission(new DnsPermission(PermissionState.Unrestricted));
			ps.AddPermission(new UIPermission(PermissionState.Unrestricted));
   			PolicyStatement statement1 = new PolicyStatement(ps,PolicyStatementAttribute.Exclusive);
			CodeGroup group;
			group = new UnionCodeGroup(new AllMembershipCondition(),statement);
			group.AddChild(new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.MyComputer),statement1));
			PolicyLevel level = PolicyLevel.CreateAppDomainLevel();
			level.RootCodeGroup = group;

			AppDomain domain = AppDomain.CreateDomain ("test");
			domain.SetAppDomainPolicy(level);
			return domain;
		}
 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);
     }
 }
 internal void InplaceUnion(PolicyStatement childPolicy)
 {
     if (((this.Attributes & childPolicy.Attributes) & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive)
     {
         throw new PolicyException(Environment.GetResourceString("Policy_MultipleExclusive"));
     }
     if (childPolicy.HasDependentEvidence)
     {
         bool flag = this.m_permSet.IsSubsetOf(childPolicy.GetPermissionSetNoCopy()) && !childPolicy.GetPermissionSetNoCopy().IsSubsetOf(this.m_permSet);
         if (this.HasDependentEvidence || flag)
         {
             if (this.m_dependentEvidence == null)
             {
                 this.m_dependentEvidence = new List <IDelayEvaluatedEvidence>();
             }
             this.m_dependentEvidence.AddRange(childPolicy.DependentEvidence);
         }
     }
     if ((childPolicy.Attributes & PolicyStatementAttribute.Exclusive) == PolicyStatementAttribute.Exclusive)
     {
         this.m_permSet  = childPolicy.GetPermissionSetNoCopy();
         this.Attributes = childPolicy.Attributes;
     }
     else
     {
         this.m_permSet.InplaceUnion(childPolicy.GetPermissionSetNoCopy());
         this.Attributes |= childPolicy.Attributes;
     }
 }
Esempio n. 25
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;
        }
Esempio n. 27
0
        private void AddPermission(PEAPI.SecurityAction sec_action, object perm, DeclSecurity decl_sec)
        {
            SSPermissionSet ps = perm as SSPermissionSet;

            if (ps != null)
            {
                decl_sec.AddPermissionSet(sec_action, ps);
                return;
            }

            IPermission iper = perm as IPermission;

            if (iper != null)
            {
                decl_sec.AddPermission(sec_action, iper);
                return;
            }

            MIPermissionSet ps20 = perm as MIPermissionSet;

            if (ps20 != null)
            {
                decl_sec.AddPermissionSet(sec_action, ps20);
                return;
            }
        }
Esempio n. 28
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 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();
            });
        }
 private PermissionSet ParsePermissionSet(Parser parser)
 {
     SecurityElement topElement = parser.GetTopElement();
     PermissionSet set = new PermissionSet(PermissionState.None);
     set.FromXml(topElement);
     return set;
 }
Esempio n. 31
0
 public void Clear()
 {
     this._inputPermissionSet     = null;
     this._inputTrustInfoDocument = null;
     this._isFullTrust            = true;
     this._outputPermissionSet    = null;
 }
Esempio n. 32
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();
            }
        }
Esempio n. 33
0
        public AppDomain createAppDomain(string appDomainName, AppDomainSetup appDomainSetup)
        {
            try
            {
                if (DI.appDomainsControledByO2Kernel.ContainsKey(appDomainName))
                    DI.log.error("in createAppDomain, appDomainName provided has already been used, appDomainNames must be unique: {0}", appDomainName);
                else
                {


                    DI.log.info("Creating AppDomain {0} with Base Directory {1}", appDomainName,
                                appDomainSetup.ApplicationBase);
                    // ensure target directory exits
                    O2Kernel_Files.checkIfDirectoryExistsAndCreateIfNot(appDomainSetup.ApplicationBase);

                    // give our appDomain full trust :)
                    var permissionSet = new PermissionSet(PermissionState.Unrestricted);

                    DI.appDomainsControledByO2Kernel.Add(appDomainName,this);
                    
                    //Create domain
                    appDomain = AppDomain.CreateDomain(appDomainName, null, appDomainSetup, permissionSet);
            //        appDomain.AssemblyResolve += new ResolveEventHandler(assemblyResolve);
                    BaseDirectory = appDomain.BaseDirectory;
                    return appDomain;
                }
            }
            catch (Exception ex)
            {
                DI.log.ex(ex, "could not load createAppDomain: " + appDomainName);
            }
            return null;
        }
 public void Clear()
 {
     this._inputPermissionSet = null;
     this._inputTrustInfoDocument = null;
     this._isFullTrust = true;
     this._outputPermissionSet = null;
 }
Esempio n. 35
0
        public JintEngine()
        {
            PermissionSet = new PermissionSet(PermissionState.None);
            TypeSystem = new TypeSystem();

            _runtime = new JintRuntime(this);
        }
		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);
		}
Esempio n. 37
0
 internal void GetGrantSet(out System.Security.PermissionSet newGrant, out System.Security.PermissionSet newDenied)
 {
     System.Security.PermissionSet o    = null;
     System.Security.PermissionSet set2 = null;
     GetGrantSet(this.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack <System.Security.PermissionSet>(ref o), JitHelpers.GetObjectHandleOnStack <System.Security.PermissionSet>(ref set2));
     newGrant  = o;
     newDenied = set2;
 }
Esempio n. 38
0
 private System.Security.PermissionSet GetOutputPermissionSet()
 {
     if (this._outputPermissionSet == null)
     {
         this._outputPermissionSet = this.GetInputPermissionSet();
     }
     return(this._outputPermissionSet);
 }
        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();
        }
 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;
 }
        private void NominaTelecentroForm_Load(object sender, EventArgs e)
        {
            ReporteNominaTelecentro_ResultBindingSource.DataSource = new EmpleadosManager().ReporteNominaTLC(FechaFin);

            System.Security.PermissionSet sec = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
            this.reportViewer1.LocalReport.SetBasePermissionsForSandboxAppDomain(sec);



            this.reportViewer1.RefreshReport();
        }
Esempio n. 42
0
        public void AddPermission(PEAPI.SecurityAction sec_action, IPermission perm)
        {
            SSPermissionSet ps = (SSPermissionSet)permissionset_table [sec_action];

            if (ps == null)
            {
                ps = new SSPermissionSet(PermissionState.None);
                permissionset_table [sec_action] = ps;
            }

            ps.AddPermission(perm);
        }
Esempio n. 43
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);
 }
 public PolicyStatement(System.Security.PermissionSet permSet, PolicyStatementAttribute attributes)
 {
     if (permSet == null)
     {
         this.m_permSet = new System.Security.PermissionSet(false);
     }
     else
     {
         this.m_permSet = permSet.Copy();
     }
     if (ValidProperties(attributes))
     {
         this.m_attributes = attributes;
     }
 }
Esempio n. 45
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);
            }
        }
        private static bool IsDataObjectFromLessPriviligedApplicationDomain(IDataObject dataObjectToApply)
        {
            bool   retVal           = false;
            object applicationTrust = null;
            // Extract the permission set in case of xaml cut and paste
            // extract permission set if it exists if not data came from full trust app and we do not care
            bool isApplicationTrustFormatPresent = false;

            isApplicationTrustFormatPresent = dataObjectToApply.GetDataPresent(DataFormats.ApplicationTrust, /*autoConvert:*/ false);
            if (isApplicationTrustFormatPresent)
            {
                applicationTrust = dataObjectToApply.GetData(DataFormats.ApplicationTrust, /*autoConvert:*/ false);
            }

            if (applicationTrust != null)
            {
                string applicationTrustText = null;
                // convert to string
                applicationTrustText = applicationTrust.ToString();


                // Convert string to permission set for getting permission set of source
                PermissionSet permissionSetSource;
                try
                {
                    SecurityElement securityElement = SecurityElement.FromString(applicationTrustText);
                    permissionSetSource = new System.Security.PermissionSet(PermissionState.None);
                    permissionSetSource.FromXml(securityElement);
                }
                catch (XmlSyntaxException)
                {
                    // This is the condition where we have Malformed XML in the clipboard for application trust
                    // here we will fail silently since we do not want to break arbitrary applications
                    // but since we cannot establish the validity of the application trust content we will fall back to
                    // whatever is more secure
                    return(true);
                }

                //extract permission set for the current appdomain which is target
                PermissionSet permissionSetDestination = SecurityHelper.ExtractAppDomainPermissionSetMinusSiteOfOrigin();
                //Compare permissions sets
                if (!permissionSetDestination.IsSubsetOf(permissionSetSource))
                {
                    retVal = true; // in case target is not subset of source revert to unicode or text
                }
            }
            return(retVal);
        }
 private PolicyStatement(System.Security.PermissionSet permSet, PolicyStatementAttribute attributes, bool copy)
 {
     if (permSet != null)
     {
         if (copy)
         {
             this.m_permSet = permSet.Copy();
         }
         else
         {
             this.m_permSet = permSet;
         }
     }
     else
     {
         this.m_permSet = new System.Security.PermissionSet(false);
     }
     this.m_attributes = attributes;
 }
Esempio n. 48
0
        public void Create_PartialTrust()
        {
            // basic check of running a host in partial trust
            AppDomainSetup info = new AppDomainSetup();

            info.ApplicationBase = TestHelpers.BinDirectory;
            info.ApplicationName = "Test";
            Evidence evidence = new Evidence();

            evidence.AddHost(new Zone(SecurityZone.Internet));
            System.Security.PermissionSet permSet = SecurityManager.GetStandardSandbox(evidence);
            AppDomain newDomain = AppDomain.CreateDomain("test", evidence, info, permSet, null);

            ScriptRuntime runtime = CreateRemoteRuntime(newDomain);
            ScriptScope   scope   = runtime.CreateScope();

            scope.SetVariable("test", "value");

            AppDomain.Unload(newDomain);
        }
        internal void FromXml(SecurityElement et, PolicyLevel level, bool allowInternalOnly)
        {
            if (et == null)
            {
                throw new ArgumentNullException("et");
            }
            if (!et.Tag.Equals("PolicyStatement"))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_InvalidXMLElement"), new object[] { "PolicyStatement", base.GetType().FullName }));
            }
            this.m_attributes = PolicyStatementAttribute.Nothing;
            string str = et.Attribute("Attributes");

            if (str != null)
            {
                this.m_attributes = (PolicyStatementAttribute)Enum.Parse(typeof(PolicyStatementAttribute), str);
            }
            lock (this)
            {
                this.m_permSet = null;
                if (level != null)
                {
                    string name = et.Attribute("PermissionSetName");
                    if (name != null)
                    {
                        this.m_permSet = level.GetNamedPermissionSetInternal(name);
                        if (this.m_permSet == null)
                        {
                            this.m_permSet = new System.Security.PermissionSet(PermissionState.None);
                        }
                    }
                }
                if (this.m_permSet == null)
                {
                    SecurityElement element = et.SearchForChildByTag("PermissionSet");
                    if (element == null)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
                    }
                    string str3 = element.Attribute("class");
                    if ((str3 != null) && (str3.Equals("NamedPermissionSet") || str3.Equals("System.Security.NamedPermissionSet")))
                    {
                        this.m_permSet = new NamedPermissionSet("DefaultName", PermissionState.None);
                    }
                    else
                    {
                        this.m_permSet = new System.Security.PermissionSet(PermissionState.None);
                    }
                    try
                    {
                        this.m_permSet.FromXml(element, allowInternalOnly, true);
                    }
                    catch
                    {
                    }
                }
                if (this.m_permSet == null)
                {
                    this.m_permSet = new System.Security.PermissionSet(PermissionState.None);
                }
            }
        }
Esempio n. 50
0
        // internal - get called by JIT generated code

        private static void InternalDemand(IntPtr permissions, int length)
        {
            PermissionSet ps = Decode(permissions, length);

            ps.Demand();
        }
        internal PermissionSet CodeGroupResolve(Evidence evidence, bool systemPolicy)
        {
            PermissionSet permissionSet = null;
            PolicyLevel   current       = null;
            IEnumerator   enumerator    = this.PolicyLevels.GetEnumerator();

            evidence.GetHostEvidence <Zone>();
            evidence.GetHostEvidence <StrongName>();
            evidence.GetHostEvidence <Url>();
            byte[] serializedEvidence = evidence.RawSerialize();
            int    rawCount           = evidence.RawCount;
            bool   flag  = AppDomain.CurrentDomain.GetData("IgnoreSystemPolicy") != null;
            bool   flag2 = false;

            while (enumerator.MoveNext())
            {
                PolicyStatement statement;
                current = (PolicyLevel)enumerator.Current;
                if (systemPolicy)
                {
                    if (current.Type != PolicyLevelType.AppDomain)
                    {
                        goto Label_0078;
                    }
                    continue;
                }
                if (flag && (current.Type != PolicyLevelType.AppDomain))
                {
                    continue;
                }
Label_0078:
                statement = current.Resolve(evidence, rawCount, serializedEvidence);
                if (permissionSet == null)
                {
                    permissionSet = statement.PermissionSet;
                }
                else
                {
                    permissionSet.InplaceIntersect(statement.GetPermissionSetNoCopy());
                }
                if ((permissionSet == null) || permissionSet.FastIsEmpty())
                {
                    break;
                }
                if ((statement.Attributes & PolicyStatementAttribute.LevelFinal) == PolicyStatementAttribute.LevelFinal)
                {
                    if (current.Type != PolicyLevelType.AppDomain)
                    {
                        flag2 = true;
                    }
                    break;
                }
            }
            if ((permissionSet != null) && flag2)
            {
                PolicyLevel level2 = null;
                for (int i = this.PolicyLevels.Count - 1; i >= 0; i--)
                {
                    current = (PolicyLevel)this.PolicyLevels[i];
                    if (current.Type == PolicyLevelType.AppDomain)
                    {
                        level2 = current;
                        break;
                    }
                }
                if (level2 != null)
                {
                    permissionSet.InplaceIntersect(level2.Resolve(evidence, rawCount, serializedEvidence).GetPermissionSetNoCopy());
                }
            }
            if (permissionSet == null)
            {
                permissionSet = new PermissionSet(PermissionState.None);
            }
            if (!permissionSet.IsUnrestricted())
            {
                IEnumerator hostEnumerator = evidence.GetHostEnumerator();
                while (hostEnumerator.MoveNext())
                {
                    object obj2 = hostEnumerator.Current;
                    IIdentityPermissionFactory factory = obj2 as IIdentityPermissionFactory;
                    if (factory != null)
                    {
                        IPermission perm = factory.CreateIdentityPermission(evidence);
                        if (perm != null)
                        {
                            permissionSet.AddPermission(perm);
                        }
                    }
                }
            }
            permissionSet.IgnoreTypeLoadFailures = true;
            return(permissionSet);
        }
 internal PermissionSetEnumerator(PermissionSet permSet)
     : base(permSet.m_unrestrictedPermSet)
 {
     m_first   = true;
     m_permSet = permSet;
 }
 internal void SetPermissionSetNoCopy(System.Security.PermissionSet permSet)
 {
     this.m_permSet = permSet;
 }
        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);
        }
Esempio n. 55
0
        //
        // API for PermissionSets
        //

        internal static void Assert(PermissionSet permSet, ref StackCrawlMark stackMark)
        {
        }
 public PolicyStatement(System.Security.PermissionSet permSet) : this(permSet, PolicyStatementAttribute.Nothing)
 {
 }
 internal PolicyStatement()
 {
     this.m_permSet    = null;
     this.m_attributes = PolicyStatementAttribute.Nothing;
 }
        internal void FromXml(SecurityDocument doc, int position, PolicyLevel level, bool allowInternalOnly)
        {
            if (doc == null)
            {
                throw new ArgumentNullException("doc");
            }
            if (!doc.GetTagForElement(position).Equals("PolicyStatement"))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_InvalidXMLElement"), new object[] { "PolicyStatement", base.GetType().FullName }));
            }
            this.m_attributes = PolicyStatementAttribute.Nothing;
            string attributeForElement = doc.GetAttributeForElement(position, "Attributes");

            if (attributeForElement != null)
            {
                this.m_attributes = (PolicyStatementAttribute)Enum.Parse(typeof(PolicyStatementAttribute), attributeForElement);
            }
            lock (this)
            {
                this.m_permSet = null;
                if (level != null)
                {
                    string name = doc.GetAttributeForElement(position, "PermissionSetName");
                    if (name != null)
                    {
                        this.m_permSet = level.GetNamedPermissionSetInternal(name);
                        if (this.m_permSet == null)
                        {
                            this.m_permSet = new System.Security.PermissionSet(PermissionState.None);
                        }
                    }
                }
                if (this.m_permSet == null)
                {
                    ArrayList childrenPositionForElement = doc.GetChildrenPositionForElement(position);
                    int       num = -1;
                    for (int i = 0; i < childrenPositionForElement.Count; i++)
                    {
                        if (doc.GetTagForElement((int)childrenPositionForElement[i]).Equals("PermissionSet"))
                        {
                            num = (int)childrenPositionForElement[i];
                        }
                    }
                    if (num == -1)
                    {
                        throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML"));
                    }
                    string str3 = doc.GetAttributeForElement(num, "class");
                    if ((str3 != null) && (str3.Equals("NamedPermissionSet") || str3.Equals("System.Security.NamedPermissionSet")))
                    {
                        this.m_permSet = new NamedPermissionSet("DefaultName", PermissionState.None);
                    }
                    else
                    {
                        this.m_permSet = new System.Security.PermissionSet(PermissionState.None);
                    }
                    this.m_permSet.FromXml(doc, num, allowInternalOnly);
                }
                if (this.m_permSet == null)
                {
                    this.m_permSet = new System.Security.PermissionSet(PermissionState.None);
                }
            }
        }
 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);
 }
Esempio n. 60
0
 internal static void PermitOnly(PermissionSet permSet, ref StackCrawlMark stackMark)
 {
 }