public SecurityElement ToXml(PolicyLevel level)
			{
				SecurityElement element;
				element = new SecurityElement("IMembershipCondition");
				element.AddAttribute
					("class",
					 SecurityElement.Escape(typeof(AllMembershipCondition).
					 						AssemblyQualifiedName));
				element.AddAttribute("version", "1");
				return element;
			}
	// Implement the ISecurityPolicyEncodable interface.
	public void FromXml(SecurityElement et, PolicyLevel level)
			{
				if(et == null)
				{
					throw new ArgumentNullException("et");
				}
				if(et.Tag != "IMembershipCondition")
				{
					throw new ArgumentException
						(_("Security_PolicyName"));
				}
				if(et.Attribute("version") != "1")
				{
					throw new ArgumentException
						(_("Security_PolicyVersion"));
				}
			}
Esempio n. 3
0
        /// <summary>
        /// Adds full trust assemblies to a policy level
        /// </summary>
        /// <param name="policyLevel">The policy level to add full trust assemblies</param>
        /// <param name="fullTrustAssembliesPath">The file containing the public key blob</param>
        private void AddFullTrustAssemblies(PolicyLevel policyLevel, string fullTrustAssembliesPath)
        {
            // create the query to get the membership conditions
            XmlQuery membershipConditions = new XmlQuery();

            membershipConditions.Load(fullTrustAssembliesPath);
            membershipConditions.Select("/FullTrustAssemblies/PublicKeyBlob");

            // for each mc found...
            while (membershipConditions.Iterator.MoveNext())
            {
                // create a mc object
                StrongNameMembershipCondition fullTrustedMC = StrongNameMembershipConditionBuilder.StrongNameMembershipConditionFromPublicKeyBlob(membershipConditions.Iterator.Current.ToString());

                // add the full trust mc
                //error CS0618: 'System.Security.Policy.PolicyLevel.AddFullTrustAssembly(System.Security.Policy.StrongNameMembershipCondition)' is obsolete: 'Because all GAC assemblies always get full trust, the full trust list is no longer meaningful. You should install any assemblies that are used in security policy in the GAC to ensure they are trusted.'
                //policyLevel.AddFullTrustAssembly(fullTrustedMC);
            }
        }
Esempio n. 4
0
        public static IEnumerator ResolvePolicyGroups(Evidence evidence)
        {
            if (evidence == null)
            {
                throw new ArgumentNullException("evidence");
            }

            ArrayList al = new ArrayList();
            // Note: can't call PolicyHierarchy since ControlPolicy isn't required to resolve policies
            IEnumerator ple = Hierarchy;

            while (ple.MoveNext())
            {
                PolicyLevel pl = (PolicyLevel)ple.Current;
                CodeGroup   cg = pl.ResolveMatchingCodeGroups(evidence);
                al.Add(cg);
            }
            return(al.GetEnumerator());
        }
Esempio n. 5
0
        }// CreateCodegroup

        private CSingleCodeGroup FindExistingCodegroup(PolicyLevel pl, IMembershipCondition mc)
        {
            // If we have an existing one, it should be right under the root node
            CSingleCodeGroup scgParent = Security.GetRootCodeGroupNode(pl);

            for (int i = 0; i < scgParent.NumChildren; i++)
            {
                CSingleCodeGroup scg = (CSingleCodeGroup)CNodeManager.GetNode(scgParent.Child[i]);

                // See if we have a matching membership condition and the description
                // says it's one the wizard created
                if (scg.MyCodeGroup.MembershipCondition.ToString().Equals(mc.ToString()) && scg.MyCodeGroup.Description.Equals(CResourceStore.GetString("GeneratedCodegroup")))
                {
                    return(scg);
                }
            }

            // We weren't able to find one
            return(null);
        }// FindExistingCodegroup
        private static void DeleteCustomCodeGroups()
        {
            // Delete the custom code groups that were created.
            IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();

            while (policyEnumerator.MoveNext())
            {
                PolicyLevel machineLevel    = (PolicyLevel)policyEnumerator.Current;
                IList       childCodeGroups = machineLevel.RootCodeGroup.Children;
                IEnumerator childGroups     = childCodeGroups.GetEnumerator();
                while (childGroups.MoveNext())
                {
                    CodeGroup thisCodeGroup = (CodeGroup)childGroups.Current;
                    if (thisCodeGroup.Name == "MyCompanyCodeGroup")
                    {
                        machineLevel.RootCodeGroup.RemoveChild(thisCodeGroup);
                    }
                }
            }
        }
        private static void DisplaySecurityPolicy()
        {
            IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();

            while (policyEnumerator.MoveNext())
            {
                PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;

                // Display the policy at the current level.
                Console.WriteLine("Policy Level {0}:", currentLevel.Label);
                // To display the policy detail, uncomment the following line:
                //Console.WriteLine(currentLevel.ToXml().ToString());
                IList       namedPermissions = currentLevel.NamedPermissionSets;
                IEnumerator namedPermission  = namedPermissions.GetEnumerator();
                while (namedPermission.MoveNext())
                {
                    Console.WriteLine("\t" + ((NamedPermissionSet)namedPermission.Current).Name);
                }
            }
        }
Esempio n. 8
0
        public static PolicyLevel LoadPolicyLevelFromString(string str, PolicyLevelType type)
        {
            if (null == str)
            {
                throw new ArgumentNullException("str");
            }

            PolicyLevel pl = null;

            try
            {
                pl = new PolicyLevel(type.ToString(), type);
                pl.LoadFromString(str);
            }
            catch (Exception e)
            {
                throw new ArgumentException(Locale.GetText("Invalid policy XML"), e);
            }
            return(pl);
        }
Esempio n. 9
0
        /// <summary>
        /// Creates a sandboxed app domain
        /// </summary>
        /// <param name="Permissions">The PermissionSet to apply to the new app domain</param>
        /// <param name="fullTrustAssembliesPath">Stream containing the full trust public key blobs</param>
        private void CreateSandboxedDomain(PermissionSet Permissions, string fullTrustAssembliesPath)
        {
            //create policy level
            PolicyLevel polLevel = PolicyLevel.CreateAppDomainLevel();

            //assign permission set to the policy level
            polLevel.RootCodeGroup.PolicyStatement = new PolicyStatement(Permissions);

            // add full trust assemblies to the policy level
            if (fullTrustAssembliesPath != null)
            {
                AddFullTrustAssemblies(polLevel, fullTrustAssembliesPath);
            }

            //create appdomain
            sandbox = AppDomain.CreateDomain("sandbox appDomain");

            //apply security policy
            sandbox.SetAppDomainPolicy(polLevel);
        }
Esempio n. 10
0
        public void SetAppDomainPolicy(PolicyLevel domainPolicy)
        {
            if (domainPolicy == null)
            {
                throw new ArgumentNullException("domainPolicy");
            }
            if (_granted != null)
            {
                throw new PolicyException(Locale.GetText(
                                              "An AppDomain policy is already specified."));
            }
            if (IsFinalizingForUnload())
            {
                throw new AppDomainUnloadedException();
            }

            PolicyStatement ps = domainPolicy.Resolve(_evidence);

            _granted = ps.PermissionSet;
        }
Esempio n. 11
0
        public static PolicyLevel LoadPolicyLevelFromFile(string path, PolicyLevelType type)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            PolicyLevel pl = null;

            try
            {
                pl = new PolicyLevel(type.ToString(), type);
                pl.LoadFromFile(path);
            }
            catch (Exception e)
            {
                throw new ArgumentException(Locale.GetText("Invalid policy XML"), e);
            }
            return(pl);
        }
Esempio n. 12
0
        private PolicyLevel DefineHostPolicy()
        {
            // Create the domain level policy
            PolicyLevel pl = PolicyLevel.CreateAppDomainLevel();

            //
            // include a code group that gives permissions only to assemblies that
            // that are strong named with s_somePublicKey
            //
            UnionCodeGroup snCG =
                new UnionCodeGroup(
                    new StrongNameMembershipCondition(new
                                                      StrongNamePublicKeyBlob(s_somePublicKey), null, null),
                    new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));

            pl.RootCodeGroup.AddChild(snCG);
            Console.WriteLine("Domain security policy successfully created...");

            return(pl);
        }
 internal void Init(string rule, byte[] il, byte[] pdb)
 {
     _assembly    = Assembly.Load(il, pdb);
     _grammarType = GetTypeForRule(_assembly, rule);
     if (_grammarType == null)
     {
         throw new FormatException(SR.Get(SRID.RecognizerRuleNotFoundStream, rule));
     }
     _rule = rule;
     try
     {
         _grammar = (Grammar)_assembly.CreateInstance(_grammarType.FullName);
     }
     catch (MissingMemberException)
     {
         throw new ArgumentException(SR.Get(SRID.RuleScriptInvalidParameters, _grammarType.FullName, rule), "rule");
     }
     _internetPermissionSet = PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet("Internet");
     _internetPermissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
 }
        // Token: 0x06001E18 RID: 7704 RVA: 0x0006907C File Offset: 0x0006727C
        private static PolicyLevel LoadPolicyLevelFromStringHelper(string str, string path, PolicyLevelType type)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }
            PolicyLevel     policyLevel = new PolicyLevel(type, path);
            Parser          parser      = new Parser(str);
            SecurityElement topElement  = parser.GetTopElement();

            if (topElement == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), "configuration"));
            }
            SecurityElement securityElement = topElement.SearchForChildByTag("mscorlib");

            if (securityElement == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), "mscorlib"));
            }
            SecurityElement securityElement2 = securityElement.SearchForChildByTag("security");

            if (securityElement2 == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), "security"));
            }
            SecurityElement securityElement3 = securityElement2.SearchForChildByTag("policy");

            if (securityElement3 == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), "policy"));
            }
            SecurityElement securityElement4 = securityElement3.SearchForChildByTag("PolicyLevel");

            if (securityElement4 != null)
            {
                policyLevel.FromXml(securityElement4);
                return(policyLevel);
            }
            throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), "PolicyLevel"));
        }
Esempio n. 15
0
    /// <summary>

    /// Gets the currently defined policylevel

    /// </summary>

    /// <returns></returns>

    private PolicyLevel GetPolicyLevel()

    {
        // Find the machine policy level

        PolicyLevel machinePolicyLevel = null;

        System.Collections.IEnumerator policyHierarchy = SecurityManager.PolicyHierarchy();



        while (policyHierarchy.MoveNext())

        {
            PolicyLevel level = (PolicyLevel)policyHierarchy.Current;

            if (level.Label.CompareTo(installPolicyLevel) == 0)

            {
                machinePolicyLevel = level;

                break;
            }
        }



        if (machinePolicyLevel == null)

        {
            throw new ApplicationException(

                      "Could not find Machine Policy level. Code Access Security " +

                      "is not configured for this application."

                      );
        }

        return(machinePolicyLevel);
    }
Esempio n. 16
0
        public PermissionSet CreatePermissionSet()
        {
            PermissionSet pset = null;

#if !NET_2_1
            if (this.Unrestricted)
            {
                pset = new PermissionSet(PermissionState.Unrestricted);
            }
            else
            {
                pset = new PermissionSet(PermissionState.None);
                if (name != null)
                {
                    return(PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet(name));
                }
                else if (file != null)
                {
                    Encoding e = ((isUnicodeEncoded) ? System.Text.Encoding.Unicode : System.Text.Encoding.ASCII);
                    using (StreamReader sr = new StreamReader(file, e)) {
                        pset = CreateFromXml(sr.ReadToEnd());
                    }
                }
                else if (xml != null)
                {
                    pset = CreateFromXml(xml);
                }
#if NET_2_0
                else if (hex != null)
                {
                    // Unicode isn't supported
                    //Encoding e = ((isUnicodeEncoded) ? System.Text.Encoding.Unicode : System.Text.Encoding.ASCII);
                    Encoding e   = System.Text.Encoding.ASCII;
                    byte[]   bin = CryptoConvert.FromHex(hex);
                    pset = CreateFromXml(e.GetString(bin, 0, bin.Length));
                }
#endif
            }
#endif
            return(pset);
        }
Esempio n. 17
0
    private void UninstallCodeAccessSecurity()

    {
        PolicyLevel machinePolicyLevel = GetPolicyLevel();



        CodeGroup codeGroup = GetCodeGroup(machinePolicyLevel);

        if (codeGroup != null)

        {
            machinePolicyLevel.RootCodeGroup.RemoveChild(codeGroup);



            // Save changes

            SecurityManager.SavePolicy();
        }
    }
Esempio n. 18
0
        public void Reset()
        {
            PolicyLevel pl = PolicyLevel.CreateAppDomainLevel();

            int        n  = pl.FullTrustAssemblies.Count;
            StrongName sn = new StrongName(new StrongNamePublicKeyBlob(snPublicKey), "First", new Version(1, 2, 3, 4));

            pl.AddFullTrustAssembly(sn);
            Assert.AreEqual(n + 1, pl.FullTrustAssemblies.Count, "FullTrustAssemblies.Count+1");

            int m = pl.NamedPermissionSets.Count;

            NamedPermissionSet nps = new NamedPermissionSet("Mono");

            pl.AddNamedPermissionSet(nps);
            Assert.AreEqual(m + 1, pl.NamedPermissionSets.Count, "NamedPermissionSets.Count+1");

            pl.Reset();
            Assert.AreEqual(n, pl.FullTrustAssemblies.Count, "FullTrustAssemblies.Count");
            Assert.AreEqual(m, pl.NamedPermissionSets.Count, "NamedPermissionSets.Count");
        }
Esempio n. 19
0
        /// <summary>Determines what permissions to grant to code based on the specified evidence.</summary>
        /// <returns>The set of permissions that can be granted by the security system.</returns>
        /// <param name="evidence">The evidence set used to evaluate policy. </param>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlEvidence" />
        /// </PermissionSet>
        public static PermissionSet ResolvePolicy(Evidence evidence)
        {
            if (evidence == null)
            {
                return(new PermissionSet(PermissionState.None));
            }
            PermissionSet permissionSet = null;
            IEnumerator   hierarchy     = SecurityManager.Hierarchy;

            while (hierarchy.MoveNext())
            {
                object      obj = hierarchy.Current;
                PolicyLevel pl  = (PolicyLevel)obj;
                if (SecurityManager.ResolvePolicyLevel(ref permissionSet, pl, evidence))
                {
                    break;
                }
            }
            SecurityManager.ResolveIdentityPermissions(permissionSet, evidence);
            return(permissionSet);
        }
Esempio n. 20
0
        public void RemoveFullTrustAssembly()
        {
            PolicyLevel pl = Load(minimal, PolicyLevelType.Machine);
            int         n  = pl.FullTrustAssemblies.Count;

            StrongName sn = new StrongName(new StrongNamePublicKeyBlob(snPublicKey), "First", new Version(1, 2, 3, 4));

            pl.AddFullTrustAssembly(sn);
            Assert.AreEqual(n + 1, pl.FullTrustAssemblies.Count, "FullTrustAssemblies.Count+1");

            StrongNameMembershipCondition snmc = new StrongNameMembershipCondition(new StrongNamePublicKeyBlob(snPublicKey), "Second", new Version("0.1.2.3"));

            pl.AddFullTrustAssembly(snmc);
            Assert.AreEqual(n + 2, pl.FullTrustAssemblies.Count, "FullTrustAssemblies.Count+2");

            pl.RemoveFullTrustAssembly(sn);
            Assert.AreEqual(n + 1, pl.FullTrustAssemblies.Count, "FullTrustAssemblies.Count-1");

            pl.RemoveFullTrustAssembly(snmc);
            Assert.AreEqual(n, pl.FullTrustAssemblies.Count, "FullTrustAssemblies.Count-2");
        }
Esempio n. 21
0
        static string Policies(string prefix)
        {
            StringBuilder sb = new StringBuilder(prefix);
            PolicyLevel   pl = null;

            for (int i = 0; i < Levels.Count - 1; i++)
            {
                pl = (PolicyLevel)Levels [i];
                sb.AppendFormat("{0}, ", pl.Label);
            }
            pl = (PolicyLevel)Levels [Levels.Count - 1];
            sb.Append(pl.Label);

            sb.Append(" policy level");
            if (Levels.Count > 1)
            {
                sb.Append("s");
            }

            return(sb.ToString());
        }
Esempio n. 22
0
        /// <summary>
        /// Loads a policy from a file (<see cref="SecurityManager.LoadPolicyLevelFromFile"/>),
        /// replacing placeholders
        /// <list>
        ///   <item>$AppDir$, $AppDirUrl$ => <paramref name="appDirectory"/></item>
        ///   <item>$CodeGen$ => (TODO)</item>
        ///   <item>$OriginHost$ => <paramref name="originUrl"/></item>
        ///   <item>$Gac$ => the current machine's GAC path</item>
        /// </list>
        /// </summary>
        /// <param name="policyFileLocation"></param>
        /// <param name="originUrl"></param>
        /// <param name="appDirectory"></param>
        /// <returns></returns>
        public static PolicyLevel LoadDomainPolicyFromUri(Uri policyFileLocation, string appDirectory, string originUrl)
        {
            bool        foundGacToken = false;
            PolicyLevel domainPolicy  = CreatePolicyLevel(policyFileLocation, appDirectory, appDirectory, originUrl, out foundGacToken);

            if (foundGacToken)
            {
                CodeGroup rootCodeGroup             = domainPolicy.RootCodeGroup;
                bool      hasGacMembershipCondition = false;
                foreach (CodeGroup childCodeGroup in rootCodeGroup.Children)
                {
                    if (childCodeGroup.MembershipCondition is GacMembershipCondition)
                    {
                        hasGacMembershipCondition = true;
                        break;
                    }
                }
                if (!hasGacMembershipCondition && (rootCodeGroup is FirstMatchCodeGroup))
                {
                    FirstMatchCodeGroup firstMatchCodeGroup = (FirstMatchCodeGroup)rootCodeGroup;
                    if ((firstMatchCodeGroup.MembershipCondition is AllMembershipCondition) && (firstMatchCodeGroup.PermissionSetName == PERMISSIONSET_NOTHING))
                    {
                        PermissionSet unrestrictedPermissionSet = new PermissionSet(PermissionState.Unrestricted);
                        CodeGroup     gacGroup  = new UnionCodeGroup(new GacMembershipCondition(), new PolicyStatement(unrestrictedPermissionSet));
                        CodeGroup     rootGroup = new FirstMatchCodeGroup(rootCodeGroup.MembershipCondition, rootCodeGroup.PolicyStatement);
                        foreach (CodeGroup childGroup in rootCodeGroup.Children)
                        {
                            if (((childGroup is UnionCodeGroup) && (childGroup.MembershipCondition is UrlMembershipCondition)) && (childGroup.PolicyStatement.PermissionSet.IsUnrestricted() && (gacGroup != null)))
                            {
                                rootGroup.AddChild(gacGroup);
                                gacGroup = null;
                            }
                            rootGroup.AddChild(childGroup);
                        }
                        domainPolicy.RootCodeGroup = rootGroup;
                    }
                }
            }
            return(domainPolicy);
        }
Esempio n. 23
0
        private static PolicyLevel LoadPolicyLevelFromStringHelper(string str, string path, PolicyLevelType type)
        {
            if (str == null)
            {
                throw new ArgumentNullException("str");
            }
            PolicyLevel     level      = new PolicyLevel(type, path);
            SecurityElement topElement = new Parser(str).GetTopElement();

            if (topElement == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), new object[] { "configuration" }));
            }
            SecurityElement element2 = topElement.SearchForChildByTag("mscorlib");

            if (element2 == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), new object[] { "mscorlib" }));
            }
            SecurityElement element3 = element2.SearchForChildByTag("security");

            if (element3 == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), new object[] { "security" }));
            }
            SecurityElement element4 = element3.SearchForChildByTag("policy");

            if (element4 == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), new object[] { "policy" }));
            }
            SecurityElement e = element4.SearchForChildByTag("PolicyLevel");

            if (e == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Policy_BadXml"), new object[] { "PolicyLevel" }));
            }
            level.FromXml(e);
            return(level);
        }
Esempio n. 24
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);
        }
Esempio n. 25
0
        /// <summary>
        /// 设置程序域的权限
        /// </summary>
        /// <param name="pAppDomain">指定的程序域</param>
        private void SetAppDomainPolicy(AppDomain pAppDomain)
        {
            PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();

            PermissionSet pPermission = new PermissionSet(PermissionState.None);

            pPermission.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            UnionCodeGroup pRootGroup = new UnionCodeGroup(new AllMembershipCondition(),
                                                           new PolicyStatement(pPermission, PolicyStatementAttribute.Nothing));

            NamedPermissionSet pPermissionSet = FindNamedPermissionSet("Machine", "Everything");

            UnionCodeGroup pChileGroup = new UnionCodeGroup(
                new ZoneMembershipCondition(SecurityZone.MyComputer),
                new PolicyStatement(pPermissionSet, PolicyStatementAttribute.Nothing));

            pChileGroup.Name = "Virtual Intranet";
            pRootGroup.AddChild(pChileGroup);
            pLevel.RootCodeGroup = pRootGroup;
            pAppDomain.SetAppDomainPolicy(pLevel);
        }
Esempio n. 26
0
        public SecurityElement ToXml(PolicyLevel level)
        {
            SecurityElement element;

            element = new SecurityElement("PolicyStatement");
            element.AddAttribute
                ("class",
                SecurityElement.Escape(typeof(PolicyStatement).
                                       AssemblyQualifiedName));
            element.AddAttribute("version", "1");
            if (attributes != PolicyStatementAttribute.Nothing)
            {
                element.AddAttribute("Attributes", attributes.ToString());
            }
            if (permSet != null)
            {
                NamedPermissionSet namedSet;
                namedSet = (permSet as NamedPermissionSet);
                if (namedSet != null)
                {
                    if (level != null &&
                        level.GetNamedPermissionSet(namedSet.Name) != null)
                    {
                        element.AddAttribute
                            ("PermissionSetName",
                            SecurityElement.Escape(namedSet.Name));
                    }
                    else
                    {
                        element.AddChild(permSet.ToXml());
                    }
                }
                else
                {
                    element.AddChild(permSet.ToXml());
                }
            }
            return(element);
        }
        private static QuickCacheEntryType GenerateQuickCache(PolicyLevel level)
        {
            if (FullTrustMap == null)
            {
                FullTrustMap = new QuickCacheEntryType[] { QuickCacheEntryType.FullTrustZoneMyComputer, QuickCacheEntryType.FullTrustZoneIntranet, QuickCacheEntryType.FullTrustZoneTrusted, QuickCacheEntryType.FullTrustZoneInternet, QuickCacheEntryType.FullTrustZoneUntrusted };
            }
            QuickCacheEntryType type     = 0;
            Evidence            evidence = new Evidence();

            try
            {
                if (level.Resolve(evidence).PermissionSet.IsUnrestricted())
                {
                    type |= QuickCacheEntryType.FullTrustAll;
                }
            }
            catch (PolicyException)
            {
            }
            foreach (SecurityZone zone in Enum.GetValues(typeof(SecurityZone)))
            {
                if (zone != SecurityZone.NoZone)
                {
                    Evidence evidence2 = new Evidence();
                    evidence2.AddHostEvidence <Zone>(new Zone(zone));
                    try
                    {
                        if (level.Resolve(evidence2).PermissionSet.IsUnrestricted())
                        {
                            type |= FullTrustMap[(int)zone];
                        }
                    }
                    catch (PolicyException)
                    {
                    }
                }
            }
            return(type);
        }
Esempio n. 28
0
        public static void PolicyLevelCallMethods()
        {
            PolicyLevel        pl  = (PolicyLevel)Activator.CreateInstance(typeof(PolicyLevel), true);
            NamedPermissionSet nps = new NamedPermissionSet("test");

            pl.AddNamedPermissionSet(nps);
            nps = pl.ChangeNamedPermissionSet("test", new PermissionSet(new Permissions.PermissionState()));
            PolicyLevel.CreateAppDomainLevel();
            nps = pl.GetNamedPermissionSet("test");
            pl.Recover();
            NamedPermissionSet nps2 = pl.RemoveNamedPermissionSet(nps);

            nps2 = pl.RemoveNamedPermissionSet("test");
            pl.Reset();
            Evidence        evidence = new Evidence();
            PolicyStatement ps       = pl.Resolve(evidence);
            CodeGroup       cg       = pl.ResolveMatchingCodeGroups(evidence);
            SecurityElement se       = new SecurityElement("");

            pl.FromXml(se);
            se = pl.ToXml();
        }
Esempio n. 29
0
        public static void PolicyLevelCallMethods()
        {
            PolicyLevel        pl  = (PolicyLevel)FormatterServices.GetUninitializedObject(typeof(PolicyLevel));
            NamedPermissionSet nps = new NamedPermissionSet("test");

            pl.AddNamedPermissionSet(nps);
            nps = pl.ChangeNamedPermissionSet("test", new PermissionSet(new Permissions.PermissionState()));
#pragma warning disable 618
            PolicyLevel.CreateAppDomainLevel();
#pragma warning restore 618
            nps = pl.GetNamedPermissionSet("test");
            pl.Recover();
            NamedPermissionSet nps2 = pl.RemoveNamedPermissionSet(nps);
            nps2 = pl.RemoveNamedPermissionSet("test");
            pl.Reset();
            Evidence        evidence = new Evidence();
            PolicyStatement ps       = pl.Resolve(evidence);
            CodeGroup       cg       = pl.ResolveMatchingCodeGroups(evidence);
            SecurityElement se       = new SecurityElement("");
            pl.FromXml(se);
            se = pl.ToXml();
        }
Esempio n. 30
0
        // -rg label|name
        // -remgroup label|name
        static bool RemoveCodeGroup(string name)
        {
            PolicyLevel pl     = null;
            CodeGroup   parent = null;
            CodeGroup   cg     = FindCodeGroup(name, ref parent, ref pl);

            if ((pl == null) || (parent == null) || (cg == null))
            {
                return(false);
            }

            if (!Confirm())
            {
                return(false);
            }

            parent.RemoveChild(cg);
            SecurityManager.SavePolicyLevel(pl);
            Console.WriteLine("CodeGroup '{0}' removed from {1} policy level.",
                              cg.Name, pl.Label);
            return(true);
        }
Esempio n. 31
0
        private void Resolve_Zone(PolicyLevel level, SecurityZone z, PolicyStatementAttribute attr, bool unrestricted, int count)
        {
            string   prefix = z.ToString() + "-" + attr.ToString() + "-";
            Evidence e      = new Evidence();

            e.AddHost(new Zone(z));
            PolicyStatement result = level.Resolve(e);

            if (unrestricted)
            {
                Assert.AreEqual(attr, result.Attributes, prefix + "Attributes");
                switch (attr)
                {
                case PolicyStatementAttribute.Nothing:
                    Assert.AreEqual(String.Empty, result.AttributeString, prefix + "AttributeString");
                    break;

                case PolicyStatementAttribute.Exclusive:
                    Assert.AreEqual("Exclusive", result.AttributeString, prefix + "AttributeString");
                    break;

                case PolicyStatementAttribute.LevelFinal:
                    Assert.AreEqual("LevelFinal", result.AttributeString, prefix + "AttributeString");
                    break;

                case PolicyStatementAttribute.All:
                    Assert.AreEqual("Exclusive LevelFinal", result.AttributeString, prefix + "AttributeString");
                    break;
                }
            }
            else
            {
                Assert.AreEqual(PolicyStatementAttribute.Nothing, result.Attributes, prefix + "Attributes");
                Assert.AreEqual(String.Empty, result.AttributeString, prefix + "AttributeString");
            }
            Assert.AreEqual(unrestricted, result.PermissionSet.IsUnrestricted(), prefix + "IsUnrestricted");
            Assert.AreEqual(count, result.PermissionSet.Count, prefix + "Count");
        }
Esempio n. 32
0
        static CodeGroup FindCodeGroup(string name, ref CodeGroup parent, ref PolicyLevel pl)
        {
            if (name.Length < 1)
            {
                return(null);
            }

            // Notes:
            // - labels starts with numbers (e.g. 1.2.1)
            // - names cannot start with numbers (A-Z, 0-9 and _)
            bool label = Char.IsDigit(name, 0);

            // More notes
            // - we can't remove the root code group
            // - we remove only one group (e.g. name)
            for (int i = 0; i < Levels.Count; i++)
            {
                pl     = (PolicyLevel)Levels [i];
                parent = pl.RootCodeGroup;
                CodeGroup cg = null;
                if (label)
                {
                    cg = FindCodeGroupByLabel(name, "1", ref parent);
                }
                else
                {
                    cg = FindCodeGroupByName(name, ref parent);
                }

                if (cg != null)
                {
                    return(cg);
                }
            }
            Console.WriteLine("CodeGroup with {0} '{1}' was not found!",
                              label ? "label" : "name", name);
            return(null);
        }
Esempio n. 33
0
 public SecurityElement ToXml(PolicyLevel level) { return default(SecurityElement); }
Esempio n. 34
0
 public void FromXml(SecurityElement et, PolicyLevel level) { }
	// Implement the ISecurityPolicyEncodable interface.
	public void FromXml(SecurityElement et, PolicyLevel level)
			{
				if(et == null)
				{
					throw new ArgumentNullException("et");
				}
				if(et.Tag != "PolicyStatement")
				{
					throw new ArgumentException
						(_("Security_PolicyName"));
				}
				if(et.Attribute("version") != "1")
				{
					throw new ArgumentException
						(_("Security_PolicyVersion"));
				}
				String value = et.Attribute("Attributes");
				if(value != null)
				{
					attributes = (PolicyStatementAttribute)
						Enum.Parse(typeof(PolicyStatementAttribute), value);
				}
				else
				{
					attributes = PolicyStatementAttribute.Nothing;
				}
				permSet = null;
				if(level != null)
				{
					String name = et.Attribute("PermissionSetName");
					if(name != null)
					{
						permSet = level.GetNamedPermissionSet(value);
						if(permSet == null)
						{
							permSet = new PermissionSet(PermissionState.None);
						}
					}
				}
				if(permSet == null)
				{
					SecurityElement child;
					child = et.SearchForChildByTag("PermissionSet");
					if(child != null)
					{
						String permClass;
						permClass = child.Attribute("class");
						if(permClass != null &&
						   permClass.IndexOf("NamedPermissionSet") != -1)
						{
							permSet = new NamedPermissionSet
								("DefaultName", PermissionState.None);
						}
						else
						{
							permSet = new PermissionSet(PermissionState.None);
						}
						try
						{
							permSet.FromXml(child);
						}
						catch(Exception)
						{
							// Ignore errors during set loading.
						}
					}
				}
				if(permSet == null)
				{
					permSet = new PermissionSet(PermissionState.None);
				}
			}
	public SecurityElement ToXml(PolicyLevel level)
			{
				SecurityElement element;
				element = new SecurityElement("PolicyStatement");
				element.AddAttribute
					("class",
					 SecurityElement.Escape(typeof(PolicyStatement).
					 						AssemblyQualifiedName));
				element.AddAttribute("version", "1");
				if(attributes != PolicyStatementAttribute.Nothing)
				{
					element.AddAttribute("Attributes", attributes.ToString());
				}
				if(permSet != null)
				{
					NamedPermissionSet namedSet;
					namedSet = (permSet as NamedPermissionSet);
					if(namedSet != null)
					{
						if(level != null &&
						   level.GetNamedPermissionSet(namedSet.Name) != null)
						{
							element.AddAttribute
								("PermissionSetName",
								 SecurityElement.Escape(namedSet.Name));
						}
						else
						{
							element.AddChild(permSet.ToXml());
						}
					}
					else
					{
						element.AddChild(permSet.ToXml());
					}
				}
				return element;
			}
Esempio n. 37
0
 protected override void CreateXml(SecurityElement element, PolicyLevel level) { }
Esempio n. 38
0
 protected override void ParseXml(SecurityElement e, PolicyLevel level) { }
	public virtual System.Security.SecurityElement ToXml(PolicyLevel level) {}
	public virtual void FromXml(System.Security.SecurityElement e, PolicyLevel level) {}