Example #1
0
        protected void SetupCompilerParams()
        {
            var p = new CompilerParameters();

            p.ReferencedAssemblies.AddRange(CommonAssemblies);
            p.CompilerOptions         = "";
            p.GenerateExecutable      = false;
            p.GenerateInMemory        = true;
            p.IncludeDebugInformation = true;

            PolicyLevel   policyLevel = PolicyLevel.CreateAppDomainLevel();
            PermissionSet perms       = new PermissionSet(PermissionState.None);
            const SecurityPermissionFlag permissionFlags = SecurityPermissionFlag.ControlThread | SecurityPermissionFlag.RemotingConfiguration |
                                                           SecurityPermissionFlag.SerializationFormatter | SecurityPermissionFlag.SkipVerification |
                                                           SecurityPermissionFlag.UnmanagedCode | SecurityPermissionFlag.Execution;

            perms.AddPermission(new SecurityPermission(permissionFlags));

            perms.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.AllFlags));

            PolicyStatement policy = new PolicyStatement(perms, PolicyStatementAttribute.Exclusive);
            CodeGroup       group  = new UnionCodeGroup(new AllMembershipCondition(), policy);

            policyLevel.RootCodeGroup = group;
            AppDomain.CurrentDomain.SetAppDomainPolicy(policyLevel);

            // All that work, and now we finally set the value =)
            compilerParams = p;
        }
        private void ConfigureSecurityPolicy()
        {
            // Find the machine policy level
            PolicyLevel machinePolicyLevel = GetMachinePolicyLevel();

            // Get the install directory of the current installer
            string assemblyPath     = this.Context.Parameters["assemblypath"];
            string installDirectory =
                assemblyPath.Substring(0, assemblyPath.LastIndexOf("\\"));

            if (!installDirectory.EndsWith(@"\"))
            {
                installDirectory += @"\";
            }

            installDirectory += "*";

            // Create the code group
            CodeGroup codeGroup = new UnionCodeGroup(
                new UrlMembershipCondition(installDirectory),
                new PolicyStatement(new NamedPermissionSet("FullTrust")));

            codeGroup.Description = Properties.Resources.CasPolicyDescription;
            codeGroup.Name        = Properties.Resources.CasPolicyName;

            // Add the code group
            machinePolicyLevel.RootCodeGroup.AddChild(codeGroup);

            // Save changes
            SecurityManager.SavePolicy();
        }
Example #3
0
        private static void RemovePolicy(string path, string name)
        {
            //Get a reference to the User level "All Code" group.
            PolicyLevel polLevel = GetPolicy(_user);

            if (polLevel != null)
            {
                UnionCodeGroup allCodeCG =
                    (UnionCodeGroup)polLevel.RootCodeGroup;

                //Determine the resolved membership condition for the
                //specified path.
                string resolvedPath =
                    new UrlMembershipCondition(path).ToString();

                //Locate a code group with the same name, the same resolved
                //path, and FullTrust; if found, remove the child group.
                IEnumerator cgs = allCodeCG.Children.GetEnumerator();
                while (cgs.MoveNext())
                {
                    CodeGroup cg = (CodeGroup)cgs.Current;
                    if (cg.Name == name)
                    {
                        if (cg.MembershipCondition.ToString() == resolvedPath &&
                            allCodeCG.PermissionSetName == _fullTrust)
                        {
                            allCodeCG.RemoveChild(cg);
                            SecurityManager.SavePolicy();
                            break;
                        }
                    }
                }
            }
        }
Example #4
0
    // source: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
    static AppDomain CreateRestrictedDomain(string filename)
    {
        PermissionSet   emptySet    = new PermissionSet(PermissionState.None);
        PolicyStatement emptyPolicy = new PolicyStatement(emptySet);
        UnionCodeGroup  root        = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

        PermissionSet userSet = null;

        if (filename [0] == '@')
        {
            userSet = GetNamedPermissionSet(filename.Substring(1));
        }
        else
        {
            userSet = LoadFromFile(filename);
        }

        PolicyStatement userPolicy = new PolicyStatement(userSet);

        root.AddChild(new UnionCodeGroup(new AllMembershipCondition(), userPolicy));

        PolicyLevel pl = PolicyLevel.CreateAppDomainLevel();

        pl.RootCodeGroup = root;

        AppDomain ad = AppDomain.CreateDomain("Restricted");

        ad.SetAppDomainPolicy(pl);
        return(ad);
    }
        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));

            PolicyStatement permissions = new PolicyStatement(partialTrustPermissionSet);

            policyRoot.AddChild(new UnionCodeGroup(new AllMembershipCondition(), permissions));

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

            appDomainLevel.RootCodeGroup = policyRoot;

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

            ads.ApplicationBase = Environment.CurrentDirectory;

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

            restrictedDomain.SetAppDomainPolicy(appDomainLevel);

            return(restrictedDomain);
        }
Example #6
0
        private void SetSandBoxPolicy()
        {
            if (!this.SandBox)
            {
                throw new InvalidOperationException("SandBox property is not set to true");
            }
            // http://www.dotnetthis.com/Articles/DynamicSandboxing.htm

            // Now we need to set the appdomain policy,
            // and to do that we will need to create a Policy Level.
            // A Policy Level is a tree-like structure that has Code Groups as its nodes.
            // Each code group consists of a Membership Condition (something that
            // defines if an assembly in question belongs to the code group) and
            // a Permission Set that is granted to the assembly if it does.
            PolicyLevel domainPolicy = PolicyLevel.CreateAppDomainLevel();

            // Let's create a code group that gives Internet permission set
            // to all code.
            // First, let's create a membership condition that accepts all code.
            AllMembershipCondition allCodeMC = new AllMembershipCondition();

            // If you were to build a more complex policy (giving different permissions
            // to different assemblies) you could use other membership conditions,
            // such as ZoneMembershipCondition, StrongNameMembershipCondition, etc.

            // Now let's create a policy statement that represents Internet permissions.
            // Here we just grab named permission set called "Internet" from the default policy,
            // but you could also create your own permission set with whatever permissions
            // you want in there.
            PermissionSet   internetPermissionSet   = domainPolicy.GetNamedPermissionSet("Internet");
            PolicyStatement internetPolicyStatement = new PolicyStatement(internetPermissionSet);

            // We are ready to create a code group that maps all code to Internet permissions
            CodeGroup allCodeInternetCG = new UnionCodeGroup(allCodeMC, internetPolicyStatement);

            // We have used a UnionCodeGroup here. It does not make much difference for
            // a simple policy like ours here, but if you were to set up a more complex one
            // you would probably add some child code groups and then the type of the parent
            // code group would matter. UnionCodeGroup unions all permissions granted by its
            // child code groups (as opposed to FirstMatchCodeGroup that only takes one child
            // code group into effect).
            // Once we have the CodeGroup set up we can add it to our Policy Level.
            domainPolicy.RootCodeGroup = allCodeInternetCG;

            // If our root code group had any children the whole tree would be added
            // to the appdomain security policy now.
            // Imagine you wanted to modify our policy so that your strongname signed
            // assemblies would get FullTrust and all other assemblies would get Internet
            // permissions. Do accomplish that you would create a new UnionCodeGroup,
            // whose membership condition would be a StrongNameMembershipCondition
            // specifying your public key, and its permission set would be a "FullTrust"
            // or just a "new PermissionSet(PermissionState.Unrestricted)".
            // Then you would add that code group as a child to our allCodeInternetCG by
            // calling its AddChild method. Whenever you then loaded a correct strong
            // name signed assembly into your appdomain it would get Internet from the
            // root code group and FullTrust from the child code group, and the effective
            // permissions would be a union of the two, which is FullTrust.
            // and our final policy related step is setting the AppDomain policy
            this.Domain.SetAppDomainPolicy(domainPolicy);
        }
Example #7
0
                public static void SetAppDomainPolicy(AppDomain appDomain)
                {
                    // Create an AppDomain policy level.
                    PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();
                    // The root code group of the policy level combines all
                    // permissions of its children.
                    UnionCodeGroup rootCodeGroup;
                    PermissionSet  ps = new PermissionSet(PermissionState.None);

                    ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                    rootCodeGroup = new UnionCodeGroup(new AllMembershipCondition(),
                                                       new PolicyStatement(ps, PolicyStatementAttribute.Nothing));

                    NamedPermissionSet localIntranet = FindNamedPermissionSet("LocalIntranet");
                    // The following code limits all code on this machine to local intranet permissions
                    // when running in this application domain.
                    UnionCodeGroup virtualIntranet = new UnionCodeGroup(
                        new ZoneMembershipCondition(SecurityZone.MyComputer),
                        new PolicyStatement(localIntranet,
                                            PolicyStatementAttribute.Nothing));

                    virtualIntranet.Name = "Virtual Intranet";
                    // Add the code groups to the policy level.
                    rootCodeGroup.AddChild(virtualIntranet);
                    pLevel.RootCodeGroup = rootCodeGroup;
                    appDomain.SetAppDomainPolicy(pLevel);
                }
Example #8
0
        // -ag label|name membership psetname flag
        // -addgroup label|name membership psetname flag
        static bool AddCodeGroup(string[] args, ref int i)
        {
            string name = args [++i];

            PolicyLevel pl     = null;
            CodeGroup   parent = null;
            CodeGroup   cg     = FindCodeGroup(name, ref parent, ref pl);

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

            UnionCodeGroup child = new UnionCodeGroup(
                new AllMembershipCondition(),
                new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));

            if (!ProcessCodeGroup(child, args, ref i))
            {
                return(false);
            }

            cg.AddChild(child);
            SecurityManager.SavePolicyLevel(pl);
            Console.WriteLine("CodeGroup '{0}' added in {1} policy level.",
                              cg.Name, pl.Label);
            return(true);
        }
Example #9
0
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            PolicyLevel ent;
            PolicyLevel mach;
            PolicyLevel user;
            string      sAssemblyPath = this.Context.Parameters["custassembly"];

            System.Collections.IEnumerator policies = SecurityManager.PolicyHierarchy();
            policies.MoveNext();
            ent = (PolicyLevel)policies.Current;
            policies.MoveNext();
            mach = (PolicyLevel)policies.Current;
            policies.MoveNext();
            user = (PolicyLevel)policies.Current;

            PermissionSet          fullTrust = user.GetNamedPermissionSet("FullTrust");
            PolicyStatement        statement = new PolicyStatement(fullTrust, PolicyStatementAttribute.Nothing);
            UrlMembershipCondition condition = new UrlMembershipCondition(sAssemblyPath);
            CodeGroup group = new UnionCodeGroup(condition, statement);

            group.Name = "DefineUFL";
            user.RootCodeGroup.AddChild(group);
            SecurityManager.SavePolicy();

            base.Install(stateSaver);
        }
Example #10
0
        // Grant all code signed with the Ecma private key full trust
        // (all of the the .Net Framework and CLR assemblies)
        private static UnionCodeGroup MakeEcmaCodeGroup()
        {
            var ecma = new UnionCodeGroup(
                new StrongNameMembershipCondition(new StrongNamePublicKeyBlob(s_ecmaPublicKey), null, null),
                new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));

            return(ecma);
        }
Example #11
0
        public static void UnionCodeGroupCallMethods()
        {
            UnionCodeGroup  ucg = new UnionCodeGroup(new GacMembershipCondition(), new PolicyStatement(new PermissionSet(new PermissionState())));
            CodeGroup       cg  = ucg.Copy();
            PolicyStatement ps  = ucg.Resolve(new Evidence());

            cg = ucg.ResolveMatchingCodeGroups(new Evidence());
        }
Example #12
0
        // Grant all code signed with the Microsoft private key full trust
        // (all of the the .Net Framework and CLR assemblies)
        private static UnionCodeGroup MakeMSCodeGroup()
        {
            var ms = new UnionCodeGroup(
                new StrongNameMembershipCondition(new StrongNamePublicKeyBlob(s_microsoftPublicKey), null, null),
                new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));

            return(ms);
        }
Example #13
0
        //----------------------------------------------------------------------------
        // ConstructAppPolicy
        //----------------------------------------------------------------------------
        public PolicyLevel ConstructAppPolicy(Evidence securityEvidence)
        {
            Console.WriteLine("Constructing App Policy Level...");

            // NOTENOTE: not effective if not both url and zone in evidence

            // Populate the PolicyLevel with code groups that will do the following:
            // 1) For all assemblies that come from this app's cache directory,
            //    give permissions from retrieved permission set from SecurityManager.
            // 2) For all other assemblies, give FullTrust permission set.  Remember,
            //    since the permissions will be intersected with other policy levels,
            //    just because we grant full trust to all other assemblies does not mean
            //    those assemblies will end up with full trust.

            PolicyLevel AppPolicy = null;

            // ResolvePolicy will return a System.Security.PermissionSet
            PermissionSet AppPerms = SecurityManager.ResolvePolicy(securityEvidence);

            // Create a new System.Security.Policy.PolicyStatement that does not contain any permissions.
            PolicyStatement Nada = new PolicyStatement(new PermissionSet(PermissionState.None));    //PermissionSet());

            // Create a PolicyStatement for the permissions that we want to grant to code from the app directory:
            PolicyStatement AppStatement = new PolicyStatement(AppPerms);

            // Create Full trust PolicyStatement so all other code gets full trust, by passing in an _unrestricted_ PermissionSet
            PolicyStatement FullTrustStatement = new PolicyStatement(new PermissionSet(PermissionState.Unrestricted));

            // Create a System.Security.Policy.FirstMatchCodeGroup as the root that matches all
            // assemblies by supplying an AllMembershipCondition:
            FirstMatchCodeGroup RootCG = new FirstMatchCodeGroup(new AllMembershipCondition(), Nada);

            // Create a child UnionCodeGroup to handle the assemblies from the app cache.  We do this
            // by using a UrlMembershipCondition set to the app cache directory:
            UnionCodeGroup AppCG = new UnionCodeGroup(new UrlMembershipCondition("file://" + _sAppBase + "*"), AppStatement);

            // Add AppCG to RootCG as first child.  This is important because we need it to be evaluated first
            RootCG.AddChild(AppCG);

            // Create a second child UnionCodeGroup to handle all other code, by using the AllMembershipCondition again
            UnionCodeGroup AllCG = new UnionCodeGroup(new AllMembershipCondition(), FullTrustStatement);

            // Add AllCG to RootCG after AppCG.  If AppCG doesnt apply to the assembly, AllCG will.
            RootCG.AddChild(AllCG);

            // This will be the PolicyLevel that we will associate with the new AppDomain.
            AppPolicy = PolicyLevel.CreateAppDomainLevel();

            // Set the RootCG as the root code group on the new policy level
            AppPolicy.RootCodeGroup = RootCG;

            // NOTENOTE
            // Code from the site that lives on the local machine will get the reduced permissions as expected.
            // Dependencies of this app (not under app dir or maybe dependencies that live in the GAC) would still get full trust.
            // If the full trust dependencies need to do something trusted, they carry the burden of asserting to overcome the stack walk.

            return(AppPolicy);
        }
Example #14
0
        public void ResolveMatchingCodeGroups_OneLevel()
        {
            UnionCodeGroup level1 = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));
            CodeGroup      match  = level1.ResolveMatchingCodeGroups(new Evidence());

            Assert.IsNotNull(match, "Match");
            Assert.IsTrue(match.Equals(level1, false), "Equals(false)");
            Assert.IsTrue(match.Equals(level1, true), "Equals(true)");
        }
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            try
            {
                PolicyLevel enterprise;
                PolicyLevel machine;
                PolicyLevel user;

                string assemblyLocation = this.Context.Parameters["assemblyLocation"];
                string groupName        = this.Context.Parameters["groupName"];

                IEnumerator enumerator = SecurityManager.PolicyHierarchy();
                // 1st one is enterprise
                enumerator.MoveNext();
                enterprise = (PolicyLevel)enumerator.Current;
                // 2nd one is machine
                enumerator.MoveNext();
                machine = (PolicyLevel)enumerator.Current;
                // 3rd one is user
                enumerator.MoveNext();
                user = (PolicyLevel)enumerator.Current;

                PermissionSet          permissionSet = user.GetNamedPermissionSet("FullTrust");
                PolicyStatement        statement     = new PolicyStatement(permissionSet, PolicyStatementAttribute.Nothing);
                UrlMembershipCondition condition     = new UrlMembershipCondition(assemblyLocation);
                CodeGroup codeGroup = new UnionCodeGroup(condition, statement);
                codeGroup.Name = groupName;

                // see if the code group already exists, and if so, remove it
                CodeGroup existingCodeGroup = null;
                foreach (CodeGroup group in user.RootCodeGroup.Children)
                {
                    if (group.Name == codeGroup.Name)
                    {
                        existingCodeGroup = group;
                        break;
                    }
                }
                if (existingCodeGroup != null)
                {
                    user.RootCodeGroup.RemoveChild(existingCodeGroup);
                }
                SecurityManager.SavePolicy();

                // add the code group
                user.RootCodeGroup.AddChild(codeGroup);
                SecurityManager.SavePolicy();
            }
            catch (Exception ex)
            {
                throw new InstallException("Cannot set the security policy.", ex);
            }

            // Call the base implementation.
            base.Install(stateSaver);
        }
Example #16
0
        public void Resolve_AllMembershipCondition_Unrestricted()
        {
            UnionCodeGroup  cg     = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));
            PolicyStatement result = cg.Resolve(new Evidence());

            Assert.AreEqual(PolicyStatementAttribute.Nothing, result.Attributes, "Attributes");
            Assert.AreEqual(String.Empty, result.AttributeString, "AttributeString");
            Assert.IsTrue(result.PermissionSet.IsUnrestricted(), "IsUnrestricted");
            Assert.AreEqual(0, result.PermissionSet.Count, "Count");
        }
Example #17
0
        public void CopyWithChildren()
        {
            UnionCodeGroup cgChild = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));
            UnionCodeGroup cg      = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));

            cg.AddChild(cgChild);
            UnionCodeGroup cg2 = (UnionCodeGroup)cg.Copy();

            Assert.AreEqual(cg.Children.Count, cg2.Children.Count, "Children");
            Assert.AreEqual(cg.ToXml().ToString(), cg2.ToXml().ToString(), "ToXml");
        }
Example #18
0
        public void Constructor()
        {
            UnionCodeGroup cg = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));

            Assert.AreEqual(String.Empty, cg.AttributeString, "AttributeString");
            Assert.IsNull(cg.Description, "Description");
            Assert.IsNotNull(cg.MembershipCondition, "MembershipCondition");
            Assert.IsNull(cg.Name, "Name");
            Assert.IsNull(cg.PermissionSetName, "PermissionSetName");
            Assert.IsNotNull(cg.PolicyStatement, "PolicyStatement");
        }
Example #19
0
        private void SetSecurity()
        {
            levelOfAccess = PolicyLevel.CreateAppDomainLevel();
            executeOnly   = new PermissionSet(PermissionState.None);
            executeOnly.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            //executeOnly.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, "C:\\Windows\\"));
            PolicyStatement executeOnlyStatement = new PolicyStatement(executeOnly);
            UnionCodeGroup  applicablePolicy     = new UnionCodeGroup(new AllMembershipCondition(), executeOnlyStatement);

            levelOfAccess.RootCodeGroup = applicablePolicy;
        }
Example #20
0
        public void Constructor_MembershipConditionPolicyStatementNull()
        {
            // legal
            UnionCodeGroup cg = new UnionCodeGroup(new AllMembershipCondition(), null);

            Assert.IsNull(cg.AttributeString, "AttributeString");
            Assert.IsNull(cg.Description, "Description");
            Assert.IsNotNull(cg.MembershipCondition, "MembershipCondition");
            Assert.IsNull(cg.Name, "Name");
            Assert.IsNull(cg.PermissionSetName, "PermissionSetName");
            Assert.IsNull(cg.PolicyStatement, "PolicyStatement");
        }
        /// <summary>
        ///
        /// </summary>
        ///
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);

            try
            {
                // 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 == "Machine")
                    {
                        machinePolicyLevel = level;
                        break;
                    }
                }

                if (machinePolicyLevel == null)
                {
                    throw new ApplicationException(
                              "Could not find Machine Policy level. Code Access Security " +
                              "is not configured for this application."
                              );
                }

                // Get the installation directory of the current installer
                string assemblyPath     = this.Context.Parameters["assemblypath"];
                string installDirectory = assemblyPath.Substring(0, assemblyPath.LastIndexOf("\\"));

                if (!installDirectory.EndsWith(@"\"))
                {
                    installDirectory += @"\";
                }

                installDirectory += "*";

                //Create a code group with a new FullTrust permission set
                PolicyStatement policyStatement = new PolicyStatement(new NamedPermissionSet("FullTrust"));
                CodeGroup       codeGroup       = new UnionCodeGroup(new UrlMembershipCondition(installDirectory), policyStatement);
                codeGroup.Description = "Permissions for Outlook Addin";
                codeGroup.Name        = "Outlook Addin";

                machinePolicyLevel.RootCodeGroup.AddChild(codeGroup);
                SecurityManager.SavePolicy();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Example #22
0
        public void Copy()
        {
            UnionCodeGroup cg  = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));
            UnionCodeGroup cg2 = (UnionCodeGroup)cg.Copy();

            Assert.AreEqual(cg.AttributeString, cg2.AttributeString, "AttributeString");
            Assert.AreEqual(cg.Children.Count, cg2.Children.Count, "Children");
            Assert.AreEqual(cg.Description, cg2.Description, "Description");
            Assert.AreEqual(cg.MergeLogic, cg2.MergeLogic, "MergeLogic");
            Assert.AreEqual(cg.Name, cg2.Name, "Name");
            Assert.AreEqual(cg.PermissionSetName, cg2.PermissionSetName, "PermissionSetName");
            Assert.AreEqual(cg.ToXml().ToString(), cg2.ToXml().ToString(), "ToXml");
        }
Example #23
0
        private void AddUrlCodeGroup(CodeGroup parentGroup, String groupName, String url, String permissionSetName)
        {
            RemoveGroupIfExists(parentGroup, groupName);

            PermissionSet        permSet             = new NamedPermissionSet(permissionSetName);
            IMembershipCondition membershipCondition = new UrlMembershipCondition(url);
            PolicyStatement      statement           = new PolicyStatement(permSet);
            CodeGroup            group = new UnionCodeGroup(membershipCondition, statement);

            group.Name = groupName;

            parentGroup.AddChild(group);
        }
        // Create new code groups using the custom named permission sets previously created.
        private static void CreateCodeGroups()
        {
            // Create instances of the named permission sets created earlier to establish the
            // permissions for the new code groups.
            NamedPermissionSet companyCodeSet    = new NamedPermissionSet("MyCompany", PermissionState.Unrestricted);
            NamedPermissionSet departmentCodeSet = new NamedPermissionSet("MyDepartment", PermissionState.Unrestricted);
            // Create new code groups using the named permission sets.
            PolicyStatement policyMyCompany    = new PolicyStatement(companyCodeSet, PolicyStatementAttribute.LevelFinal);
            PolicyStatement policyMyDepartment = new PolicyStatement(departmentCodeSet, PolicyStatementAttribute.Exclusive);
            // Create new code groups using UnionCodeGroup.
            CodeGroup myCompanyZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Intranet), policyMyCompany);

            myCompanyZone.Name = "MyCompanyCodeGroup";

            byte[] b1 = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 206, 206, 170, 84, 111, 145, 26, 208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180 };
            StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1);

            CodeGroup myDepartmentZone = new UnionCodeGroup(new StrongNameMembershipCondition(blob, null, null), policyMyDepartment);

            myDepartmentZone.Name = "MyDepartmentCodeGroup";

            // Move through the policy levels looking for the Machine policy level.
            // Create two new code groups at that level.
            IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();

            while (policyEnumerator.MoveNext())
            {
                // At the Machine level delete already existing copies of the custom code groups,
                // then create the new code groups.
                PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;
                if (currentLevel.Label == "Machine")
                {
                    // Remove old instances of the custom groups.
                    DeleteCustomCodeGroups();
                    // Add the new code groups.
                    //*******************************************************
                    // To add a child code group, add the child to the parent prior to adding
                    // the parent to the root.
                    myCompanyZone.AddChild(myDepartmentZone);
                    // Add the parent to the root code group.
                    currentLevel.RootCodeGroup.AddChild(myCompanyZone);
                    SecurityManager.SavePolicy();
                }
            }
            // Save the security policy.
            SecurityManager.SavePolicy();
            Console.WriteLine("Security policy modified.");
            Console.WriteLine("New code groups added at the Machine policy level.");
        }
        private static PolicyLevel GetPolicyForUrl(String strUrl, int iZone, String strAppPath)
        {
            if (strUrl == null || strAppPath == null || strUrl.Length < 1 || strAppPath.Length < 1)
            {
                return(null);
            }

            Evidence       evidence = new Evidence();
            PolicyLevel    plReturn = PolicyLevel.CreateAppDomainLevel();
            PermissionSet  denyPS   = null;
            PermissionSet  ps;
            UnionCodeGroup allCG;
            UnionCodeGroup snCG;
            UnionCodeGroup cg;

            evidence.AddAssembly(new Url(strUrl));
            evidence.AddAssembly(new Zone((SecurityZone)iZone));

            ps = SecurityManager.ResolvePolicy(evidence,
                                               null, null, null, out denyPS);

            ps.RemovePermission(typeof(UrlIdentityPermission));
            ps.RemovePermission(typeof(ZoneIdentityPermission));


            allCG = new UnionCodeGroup(new AllMembershipCondition(),
                                       new PolicyStatement(new PermissionSet(PermissionState.None)));
            snCG = new UnionCodeGroup(
                new StrongNameMembershipCondition(new StrongNamePublicKeyBlob(s_microsoftPublicKey), null, null),
                new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));

            if (!strAppPath.EndsWith("/"))
            {
                strAppPath += "/";
            }
            strAppPath += "*";

            cg = new UnionCodeGroup(
                new UrlMembershipCondition(strAppPath),
                new PolicyStatement(ps));

            allCG.AddChild(snCG);
            allCG.AddChild(cg);
            plReturn.RootCodeGroup.AddChild(allCG);

            return(plReturn);
        }
Example #26
0
        public void ResolveMatchingCodeGroups_ThreeLevel()
        {
            UnionCodeGroup level1 = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));
            CodeGroup      level2 = level1.Copy();

            level1.AddChild(level2);
            UnionCodeGroup level3 = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Untrusted), new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));

            level2.AddChild(level3);

            CodeGroup match = level1.ResolveMatchingCodeGroups(new Evidence());

            Assert.IsNotNull(match, "Match");
            Assert.IsTrue(match.Equals(level1, false), "Equals(false)");
            // Equals (true) isn't a deep compare (just one level)
            Assert.IsTrue(match.Equals(level1, true), "Equals(true)");
        }
Example #27
0
        internal CNewCodeGroupWiz2() : base(null)
        {
            // Since we're inheriting off of a property page and not a wizard
            // page, we need to set our size ourselves....
            CWizardPage wizPage = new CWizardPage();

            PageSize = wizPage.PageSize;


            m_sTitle          = CResourceStore.GetString("CNewCodeGroupWiz2:Title");
            m_sHeaderTitle    = CResourceStore.GetString("CNewCodeGroupWiz2:HeaderTitle");
            m_sHeaderSubTitle = CResourceStore.GetString("CNewCodeGroupWiz2:HeaderSubTitle");
            m_cg        = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));
            MyCodeGroup = m_cg;
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(CNewCodeGroupWiz2));
            m_point2ndPiece = ((System.Drawing.Point)(resources.GetObject("m_uc.Location")));
        }// CNewCodeGroupWiz2
Example #28
0
    /// <summary>

    /// Configures FullTrust for the entire installdirectory

    /// </summary>

    private void ConfigureCodeAccessSecurity()

    {
        PolicyLevel machinePolicyLevel = GetPolicyLevel();



        if (null == GetCodeGroup(machinePolicyLevel))

        {
            // Create a new FullTrust permission set

            PermissionSet permissionSet = new NamedPermissionSet(this.namedPermissionSet);



            IMembershipCondition membershipCondition =

                new UrlMembershipCondition(InstallDirectory);



            // Create the code group

            PolicyStatement policyStatement = new PolicyStatement(permissionSet);

            CodeGroup codeGroup = new UnionCodeGroup(membershipCondition, policyStatement);

            codeGroup.Description = this.codeGroupDescription;

            codeGroup.Name = this.codeGroupName;



            // Add the code group

            machinePolicyLevel.RootCodeGroup.AddChild(codeGroup);



            // Save changes

            SecurityManager.SavePolicy();
        }
    }
Example #29
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);
        }
Example #30
0
        public void ToFromXmlRoundtrip()
        {
            const string    ps_Name = "TestName";
            PolicyStatement ps      = new PolicyStatement(new NamedPermissionSet(ps_Name));
            UnionCodeGroup  cg      = new UnionCodeGroup(new AllMembershipCondition(), ps);

            cg.Name        = "SomeName";
            cg.Description = "Some Description";
            Assert.IsTrue(cg.Equals(cg), "Equals (itself)");
            SecurityElement se = cg.ToXml();

            UnionCodeGroup cg2 = new UnionCodeGroup(new AllMembershipCondition(), ps);

            cg2.Name        = "SomeOtherName";
            cg2.Description = "Some Other Description";
            Assert.IsTrue(!cg.Equals(cg2), "Equals (another)");

            cg2.FromXml(se);
            Assert.IsTrue(cg.Equals(cg2), "Equals (FromXml)");
        }
Example #31
0
	// source: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
	static AppDomain CreateRestrictedDomain (string filename)
	{
		PermissionSet emptySet = new PermissionSet (PermissionState.None);
		PolicyStatement emptyPolicy = new PolicyStatement (emptySet);
		UnionCodeGroup root = new UnionCodeGroup (new AllMembershipCondition (), emptyPolicy);

		PermissionSet userSet = null;
		if (filename [0] == '@')
			userSet = GetNamedPermissionSet (filename.Substring (1));
		else
			userSet = LoadFromFile (filename);

		PolicyStatement userPolicy = new PolicyStatement (userSet);
		root.AddChild (new UnionCodeGroup (new AllMembershipCondition (), userPolicy));

		PolicyLevel pl = PolicyLevel.CreateAppDomainLevel ();
		pl.RootCodeGroup = root;

		AppDomain ad = AppDomain.CreateDomain ("Restricted");
		ad.SetAppDomainPolicy (pl);
		return ad;
	}
Example #32
0
    // Create new code groups using the custom named permission sets previously created. 
    private static void CreateCodeGroups()
    {
        // Create instances of the named permission sets created earlier to establish the 
        // permissions for the new code groups.
        NamedPermissionSet companyCodeSet = new NamedPermissionSet("MyCompany",PermissionState.Unrestricted);
        NamedPermissionSet departmentCodeSet = new NamedPermissionSet("MyDepartment",PermissionState.Unrestricted);
        // Create new code groups using the named permission sets.
        PolicyStatement policyMyCompany = new PolicyStatement(companyCodeSet,PolicyStatementAttribute.LevelFinal);
        PolicyStatement policyMyDepartment = new PolicyStatement(departmentCodeSet,PolicyStatementAttribute.Exclusive);
        // Create new code groups using UnionCodeGroup.
        CodeGroup myCompanyZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Intranet), policyMyCompany);
        myCompanyZone.Name = "MyCompanyCodeGroup";

        byte[] b1 = { 0, 36, 0, 0, 4, 128, 0, 0, 148, 0, 0, 0, 6, 2, 0, 0, 0, 36, 0, 0, 82, 83, 65, 49, 0, 4, 0, 0, 1, 0, 1, 0, 237, 146, 145, 51, 34, 97, 123, 196, 90, 174, 41, 170, 173, 221, 41, 193, 175, 39, 7, 151, 178, 0, 230, 152, 218, 8, 206, 206, 170,84, 111, 145, 26, 208, 158, 240, 246, 219, 228, 34, 31, 163, 11, 130, 16, 199, 111, 224, 4, 112, 46, 84, 0, 104, 229, 38, 39, 63, 53, 189, 0, 157, 32, 38, 34, 109, 0, 171, 114, 244, 34, 59, 9, 232, 150, 192, 247, 175, 104, 143, 171, 42, 219, 66, 66, 194, 191, 218, 121, 59, 92, 42, 37, 158, 13, 108, 210, 189, 9, 203, 204, 32, 48, 91, 212, 101, 193, 19, 227, 107, 25, 133, 70, 2, 220, 83, 206, 71, 102, 245, 104, 252, 87, 109, 190, 56, 34, 180};
        StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(b1);

        CodeGroup myDepartmentZone = new UnionCodeGroup(new StrongNameMembershipCondition(blob, null, null), policyMyDepartment);
        myDepartmentZone.Name = "MyDepartmentCodeGroup";

        // Move through the policy levels looking for the Machine policy level. 
        // Create two new code groups at that level.
        IEnumerator policyEnumerator = SecurityManager.PolicyHierarchy();
        while(policyEnumerator.MoveNext())
        {
            // At the Machine level delete already existing copies of the custom code groups, 
            // then create the new code groups.
            PolicyLevel currentLevel = (PolicyLevel)policyEnumerator.Current;
            if (currentLevel.Label == "Machine")
            {

                // Remove old instances of the custom groups.
                DeleteCustomCodeGroups();
                // Add the new code groups. 
                //******************************************************* 
                // To add a child code group, add the child to the parent prior to adding 
                // the parent to the root.
                myCompanyZone.AddChild(myDepartmentZone);
                // Add the parent to the root code group.
                currentLevel.RootCodeGroup.AddChild(myCompanyZone);
                SecurityManager.SavePolicy();
            }
        }
        // Save the security policy.
        SecurityManager.SavePolicy();
        Console.WriteLine("Security policy modified.");
        Console.WriteLine("New code groups added at the Machine policy level.");
    }