Inheritance: CodeGroup, IUnionSemanticCodeGroup
        public override void Install(System.Collections.IDictionary stateSaver)
        {
            PolicyLevel ent;
            PolicyLevel mach;
            PolicyLevel user;
            string sAssemblyPath = this.Context.Parameters["custassembly"];
            //string sAssemblyPath = this.Context.Parameters["XWord.dll"];
            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 = "TestWordAddInCS";
            user.RootCodeGroup.AddChild(group);
            SecurityManager.SavePolicy();

            base.Install(stateSaver);
        }
Beispiel #2
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());
 }
        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;
        }
Beispiel #4
0
        // Create the default root code group.
        private CodeGroup DefaultRootCodeGroup()
        {
            UnionCodeGroup group = new UnionCodeGroup
                                       (new AllMembershipCondition(), null);

            group.Name        = "All_Code";
            group.Description = _("Security_RootGroupDescription");
            return(group);
        }
Beispiel #5
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");
		}
Beispiel #6
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");
		}
Beispiel #7
0
        /// <summary>Creates a new policy level for use at the application domain policy level.</summary>
        /// <returns>The newly created <see cref="T:System.Security.Policy.PolicyLevel" />.</returns>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
        /// </PermissionSet>
        public static PolicyLevel CreateAppDomainLevel()
        {
            UnionCodeGroup unionCodeGroup = new UnionCodeGroup(new AllMembershipCondition(), new PolicyStatement(DefaultPolicies.FullTrust));

            unionCodeGroup.Name = "All_Code";
            PolicyLevel policyLevel = new PolicyLevel("AppDomain", PolicyLevelType.AppDomain);

            policyLevel.RootCodeGroup = unionCodeGroup;
            policyLevel.Reset();
            return(policyLevel);
        }
Beispiel #8
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");
		}
        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);
        }
Beispiel #10
0
		internal CodeGroup Copy (bool childs) 
		{
			UnionCodeGroup copy = new UnionCodeGroup (MembershipCondition, PolicyStatement);
			copy.Name = Name;
			copy.Description = Description;
			if (childs) {
				foreach (CodeGroup child in Children) {
					copy.AddChild (child.Copy ());
				}
			}
			return copy;
		}
Beispiel #11
0
        /// <summary>生成当前代码组的深层副本。</summary>
        /// <returns>当前代码组(包括其成员条件和子代码组)的等效副本。</returns>
        /// <PermissionSet>
        ///   <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode" />
        /// </PermissionSet>
        public override CodeGroup Copy()
        {
            UnionCodeGroup unionCodeGroup = new UnionCodeGroup();

            unionCodeGroup.MembershipCondition = this.MembershipCondition;
            unionCodeGroup.PolicyStatement     = this.PolicyStatement;
            unionCodeGroup.Name        = this.Name;
            unionCodeGroup.Description = this.Description;
            foreach (CodeGroup child in (IEnumerable)this.Children)
            {
                unionCodeGroup.AddChild(child);
            }
            return((CodeGroup)unionCodeGroup);
        }
Beispiel #12
0
        private static void CreateAPolicyLevel()
        {
            try
            {
                // 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));

                // This code group grants FullTrust to assemblies with the strong name key from this assembly.
                UnionCodeGroup myCodeGroup = new UnionCodeGroup(
                    new StrongNameMembershipCondition(
                        new StrongNamePublicKeyBlob(GetKey()),
                        null,
                        null),
                    new PolicyStatement(new PermissionSet(PermissionState.Unrestricted),
                        PolicyStatementAttribute.Nothing)
                    );
                myCodeGroup.Name = "My CodeGroup";

                // Add the code groups to the policy level.
                rootCodeGroup.AddChild(myCodeGroup);
                pLevel.RootCodeGroup = rootCodeGroup;
                Console.WriteLine("Permissions granted to all code running in this AppDomain level: ");
                Console.WriteLine(rootCodeGroup.ToXml());
                Console.WriteLine("Child code groups in RootCodeGroup: ");
                IList codeGroups = pLevel.RootCodeGroup.Children;
                IEnumerator codeGroup = codeGroups.GetEnumerator();
                while (codeGroup.MoveNext())
                {
                    Console.WriteLine("\t" + ((CodeGroup)codeGroup.Current).Name);
                }
                Console.WriteLine("Demonstrate adding and removing named permission sets.");
                Console.WriteLine("Original named permissions sets:");
                ListPermissionSets(pLevel);
                NamedPermissionSet myInternet = pLevel.GetNamedPermissionSet("Internet");
                    

            }
            catch
            {
            }
        }
        /// <summary>Makes a deep copy of the current code group.</summary>
        /// <returns>An equivalent copy of the current code group, including its membership conditions and child code groups.</returns>
        // Token: 0x06002A5C RID: 10844 RVA: 0x0009D9A8 File Offset: 0x0009BBA8
        public override CodeGroup Copy()
        {
            UnionCodeGroup unionCodeGroup = new UnionCodeGroup();

            unionCodeGroup.MembershipCondition = base.MembershipCondition;
            unionCodeGroup.PolicyStatement     = base.PolicyStatement;
            unionCodeGroup.Name        = base.Name;
            unionCodeGroup.Description = base.Description;
            foreach (object obj in base.Children)
            {
                unionCodeGroup.AddChild((CodeGroup)obj);
            }
            return(unionCodeGroup);
        }
 public override CodeGroup Copy()
 {
     UnionCodeGroup group = new UnionCodeGroup {
         MembershipCondition = base.MembershipCondition,
         PolicyStatement = base.PolicyStatement,
         Name = base.Name,
         Description = base.Description
     };
     IEnumerator enumerator = base.Children.GetEnumerator();
     while (enumerator.MoveNext())
     {
         group.AddChild((CodeGroup) enumerator.Current);
     }
     return group;
 }
Beispiel #15
0
        internal CodeGroup Copy(bool childs)
        {
            UnionCodeGroup copy = new UnionCodeGroup(MembershipCondition, PolicyStatement);

            copy.Name        = Name;
            copy.Description = Description;
            if (childs)
            {
                foreach (CodeGroup child in Children)
                {
                    copy.AddChild(child.Copy());
                }
            }
            return(copy);
        }
        // Hardcode defaults in case
        // (a) the specified policy file doesn't exists; and
        // (b) no corresponding default policy file exists
        internal void CreateDefaultLevel(PolicyLevelType type)
        {
            PolicyStatement psu = new PolicyStatement(DefaultPolicies.FullTrust);

            switch (type)
            {
            case PolicyLevelType.Machine:
                // by default all stuff is in the machine policy...
                PolicyStatement psn = new PolicyStatement(DefaultPolicies.Nothing);
                root_code_group      = new UnionCodeGroup(new AllMembershipCondition(), psn);
                root_code_group.Name = "All_Code";

                UnionCodeGroup myComputerZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.MyComputer), psu);
                myComputerZone.Name = "My_Computer_Zone";
                // TODO: strongname code group for ECMA and MS keys
                root_code_group.AddChild(myComputerZone);

                UnionCodeGroup localIntranetZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Intranet),
                                                                      new PolicyStatement(DefaultPolicies.LocalIntranet));
                localIntranetZone.Name = "LocalIntranet_Zone";
                // TODO: same site / same directory
                root_code_group.AddChild(localIntranetZone);

                PolicyStatement psi          = new PolicyStatement(DefaultPolicies.Internet);
                UnionCodeGroup  internetZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Internet), psi);
                internetZone.Name = "Internet_Zone";
                // TODO: same site
                root_code_group.AddChild(internetZone);

                UnionCodeGroup restrictedZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Untrusted), psn);
                restrictedZone.Name = "Restricted_Zone";
                root_code_group.AddChild(restrictedZone);

                UnionCodeGroup trustedZone = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Trusted), psi);
                trustedZone.Name = "Trusted_Zone";
                // TODO: same site
                root_code_group.AddChild(trustedZone);
                break;

            case PolicyLevelType.User:
            case PolicyLevelType.Enterprise:
            case PolicyLevelType.AppDomain:
                // while the other policies don't restrict anything
                root_code_group      = new UnionCodeGroup(new AllMembershipCondition(), psu);
                root_code_group.Name = "All_Code";
                break;
            }
        }
        internal CodeGroup Copy(bool childs)
        {
            UnionCodeGroup unionCodeGroup = new UnionCodeGroup(base.MembershipCondition, base.PolicyStatement);

            unionCodeGroup.Name        = base.Name;
            unionCodeGroup.Description = base.Description;
            if (childs)
            {
                foreach (object obj in base.Children)
                {
                    CodeGroup codeGroup = (CodeGroup)obj;
                    unionCodeGroup.AddChild(codeGroup.Copy());
                }
            }
            return(unionCodeGroup);
        }
Beispiel #18
0
        public override CodeGroup Copy()
        {
            UnionCodeGroup group = new UnionCodeGroup {
                MembershipCondition = base.MembershipCondition,
                PolicyStatement     = base.PolicyStatement,
                Name        = base.Name,
                Description = base.Description
            };
            IEnumerator enumerator = base.Children.GetEnumerator();

            while (enumerator.MoveNext())
            {
                group.AddChild((CodeGroup)enumerator.Current);
            }
            return(group);
        }
	// Make a copy of this code group.
	public override CodeGroup Copy()
			{
				UnionCodeGroup group;
				group = new UnionCodeGroup
					(MembershipCondition, PolicyStatement);
				group.Name = Name;
				group.Description = Description;
				IList children = Children;
				if(children != null)
				{
					foreach(CodeGroup child in children)
					{
						group.AddChild(child);
					}
				}
				return group;
			}
Beispiel #20
0
        // Make a copy of this code group.
        public override CodeGroup Copy()
        {
            UnionCodeGroup group;

            group = new UnionCodeGroup
                        (MembershipCondition, PolicyStatement);
            group.Name        = Name;
            group.Description = Description;
            IList children = Children;

            if (children != null)
            {
                foreach (CodeGroup child in children)
                {
                    group.AddChild(child);
                }
            }
            return(group);
        }
Beispiel #21
0
        /// <include file='doc\UnionCodeGroup.uex' path='docs/doc[@for="UnionCodeGroup.Copy"]/*' />
        public override CodeGroup Copy()
        {
            UnionCodeGroup group = new UnionCodeGroup();

            group.MembershipCondition = this.MembershipCondition;
            group.PolicyStatement     = this.PolicyStatement;
            group.Name        = this.Name;
            group.Description = this.Description;

            IEnumerator enumerator = this.Children.GetEnumerator();

            while (enumerator.MoveNext())
            {
                group.AddChild((CodeGroup)enumerator.Current);
            }


            return(group);
        }
Beispiel #22
0
        internal void CreateDefaultLevel(PolicyLevelType type)
        {
            PolicyStatement policy = new PolicyStatement(DefaultPolicies.FullTrust);

            switch (type)
            {
            case PolicyLevelType.User:
            case PolicyLevelType.Enterprise:
            case PolicyLevelType.AppDomain:
                this.root_code_group      = new UnionCodeGroup(new AllMembershipCondition(), policy);
                this.root_code_group.Name = "All_Code";
                break;

            case PolicyLevelType.Machine:
            {
                PolicyStatement policy2 = new PolicyStatement(DefaultPolicies.Nothing);
                this.root_code_group      = new UnionCodeGroup(new AllMembershipCondition(), policy2);
                this.root_code_group.Name = "All_Code";
                UnionCodeGroup unionCodeGroup = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.MyComputer), policy);
                unionCodeGroup.Name = "My_Computer_Zone";
                this.root_code_group.AddChild(unionCodeGroup);
                UnionCodeGroup unionCodeGroup2 = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Intranet), new PolicyStatement(DefaultPolicies.LocalIntranet));
                unionCodeGroup2.Name = "LocalIntranet_Zone";
                this.root_code_group.AddChild(unionCodeGroup2);
                PolicyStatement policy3         = new PolicyStatement(DefaultPolicies.Internet);
                UnionCodeGroup  unionCodeGroup3 = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Internet), policy3);
                unionCodeGroup3.Name = "Internet_Zone";
                this.root_code_group.AddChild(unionCodeGroup3);
                UnionCodeGroup unionCodeGroup4 = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Untrusted), policy2);
                unionCodeGroup4.Name = "Restricted_Zone";
                this.root_code_group.AddChild(unionCodeGroup4);
                UnionCodeGroup unionCodeGroup5 = new UnionCodeGroup(new ZoneMembershipCondition(SecurityZone.Trusted), policy3);
                unionCodeGroup5.Name = "Trusted_Zone";
                this.root_code_group.AddChild(unionCodeGroup5);
                break;
            }
            }
        }
Beispiel #23
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);
        }
Beispiel #24
0
        [System.Security.SecurityCritical]  // auto-generated
        private static void SetupSecurity()
        {
            PolicyLevel level = PolicyLevel.CreateAppDomainLevel();

            CodeGroup rootGroup = new UnionCodeGroup( new AllMembershipCondition(), level.GetNamedPermissionSet( "Execution" ) );

            StrongNamePublicKeyBlob microsoftBlob = new StrongNamePublicKeyBlob( AssemblyRef.MicrosoftPublicKeyFull );
            CodeGroup microsoftGroup = new UnionCodeGroup( new StrongNameMembershipCondition( microsoftBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) );

            StrongNamePublicKeyBlob ecmaBlob = new StrongNamePublicKeyBlob( AssemblyRef.EcmaPublicKeyFull );
            CodeGroup ecmaGroup = new UnionCodeGroup( new StrongNameMembershipCondition( ecmaBlob, null, null ), level.GetNamedPermissionSet( "FullTrust" ) );

            CodeGroup gacGroup = new UnionCodeGroup( new GacMembershipCondition(), level.GetNamedPermissionSet( "FullTrust" ) );

            rootGroup.AddChild( microsoftGroup );
            rootGroup.AddChild( ecmaGroup );
            rootGroup.AddChild( gacGroup );

            level.RootCodeGroup = rootGroup;

            try
            {
                AppDomain.CurrentDomain.SetAppDomainPolicy( level );
            }
            catch (PolicyException)
            {
            }
        }
Beispiel #25
0
        static void AddGroupHandler( String[] args, int index, out int numArgsUsed )
        {
            if (args[index].Equals( "__internal_usage__" ))
            {
                numArgsUsed = 1;
                PauseCapableWriteLine( manager.GetString( "Help_Option_AddGroup" ) );
                return;
            }
        
            numArgsUsed = 2;

            if (args.Length - index < 4) 
            {
                Error( manager.GetString( "OptionTable_AddGroup" ), manager.GetString( "Error_NotEnoughArgs" ), -1 );
                return;
            }
        
            Object parentValue = null;

            PolicyLevel level = GetLevel();
        
            if (level == null)
            {
                if (m_levelType == LevelType.All || m_levelType == LevelType.AllCustom)
                    Error( manager.GetString( "OptionTable_AddGroup" ), String.Format( manager.GetString( "Dialog_NotValidWithAll" ), manager.GetString( "OptionTable_All" ) ), -1 );
                else
                    Error( manager.GetString( "OptionTable_AddGroup" ), manager.GetString( "Error_UnableToRetrieveLevel" ), -1 );
            }
        
            try
            {
                parentValue = GetLabel( args[index+1] );
            }
            catch (Exception e)
            {
                if (e is SecurityException)
                    Error( manager.GetString( "OptionTable_AddGroup" ), manager.GetString( "Error_PolicyPermissionDenied" ), -1 );
                else        
                    Error( manager.GetString( "OptionTable_AddGroup" ), manager.GetString( "Error_InvalidLabel" ), -1 );
                return;
            }
        
            if (parentValue == null)
            {
                if (m_levelType == LevelType.All || m_levelType == LevelType.AllCustom)
                    Error( manager.GetString( "OptionTable_AddGroup" ), String.Format( manager.GetString( "Dialog_NotValidWithAll" ), manager.GetString( "OptionTable_All" ) ), -1 );
                else
                    Error( manager.GetString( "OptionTable_AddGroup" ), manager.GetString( "Error_InvalidLabel" ), -1 );
                return;
            }
       
            if (!(parentValue is CodeGroup))
            {
                Error( manager.GetString( "OptionTable_AddGroup" ), manager.GetString( "Error_CodeGroup_MustBeCodeGroup" ), -1 );
                return;
            }
        
            int offset = 0, exlOffset = 0;
        
            IMembershipCondition mship = CreateMembershipCondition( level, args, index+2, out offset );
        
            if (args.Length <= index + 2 + offset)
            {
                Error( manager.GetString( "OptionTable_AddGroup" ), manager.GetString( "Error_CodeGroup_NoPermissionSet" ), -1 );
                return;
            }

            CodeGroup newGroup = null;

            try
            {
                newGroup = new UnionCodeGroup( mship, new PolicyStatement( GetPermissionSet( level, args[index + 2 + offset] ), PolicyStatementAttribute.Nothing ) );

                PolicyStatement statement = newGroup.PolicyStatement;

                statement.Attributes = IsExclusive( newGroup, args, index + 3 + offset, out exlOffset );

                newGroup.PolicyStatement = statement;
            }
            catch (Exception e)
            {
                String message = e.Message;

                if (message == null || message.Equals( "" ))
                {
                    message = e.GetType().AssemblyQualifiedName;
                }

                Error( manager.GetString( "OptionTable_AddGroup" ), message, -1 );
            }

            ((CodeGroup)parentValue).AddChild( newGroup );
            ReplaceLabel( args[index+1], (CodeGroup)parentValue );

            SafeSavePolicy();
        
            PauseCapableWriteLine( String.Format( manager.GetString( "Dialog_AddedCodeGroup" ), args[index+2], level.Label ) );        
        
            numArgsUsed = offset + exlOffset + 3;
        }
	// Create the default root code group.
	private CodeGroup DefaultRootCodeGroup()
			{
				UnionCodeGroup group = new UnionCodeGroup
					(new AllMembershipCondition(), null);
				group.Name = "All_Code";
				group.Description = _("Security_RootGroupDescription");
				return group;
			}
Beispiel #27
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");
		}
 private static PolicyLevel GetPartialTrustPolicyLevel(TrustSection trustSection, SecurityPolicySection securityPolicySection, CompilationSection compilationSection, string physicalPath, VirtualPath virtualPath)
 {
     if ((securityPolicySection == null) || (securityPolicySection.TrustLevels[trustSection.Level] == null))
     {
         throw new ConfigurationErrorsException(System.Web.SR.GetString("Unable_to_get_policy_file", new object[] { trustSection.Level }), string.Empty, 0);
     }
     string policyFileExpanded = securityPolicySection.TrustLevels[trustSection.Level].PolicyFileExpanded;
     if ((policyFileExpanded == null) || !System.Web.Util.FileUtil.FileExists(policyFileExpanded))
     {
         throw new HttpException(System.Web.SR.GetString("Unable_to_get_policy_file", new object[] { trustSection.Level }));
     }
     PolicyLevel level = null;
     string path = System.Web.Util.FileUtil.RemoveTrailingDirectoryBackSlash(physicalPath);
     string newValue = HttpRuntime.MakeFileUrl(path);
     string tempDirectory = null;
     string tempDirAttribName = null;
     string configFileName = null;
     int configLineNumber = 0;
     if ((compilationSection != null) && !string.IsNullOrEmpty(compilationSection.TempDirectory))
     {
         tempDirectory = compilationSection.TempDirectory;
         compilationSection.GetTempDirectoryErrorInfo(out tempDirAttribName, out configFileName, out configLineNumber);
     }
     if (tempDirectory != null)
     {
         tempDirectory = tempDirectory.Trim();
         if (!Path.IsPathRooted(tempDirectory))
         {
             tempDirectory = null;
         }
         else
         {
             try
             {
                 tempDirectory = new DirectoryInfo(tempDirectory).FullName;
             }
             catch
             {
                 tempDirectory = null;
             }
         }
         if (tempDirectory == null)
         {
             throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_temp_directory", new object[] { tempDirAttribName }), configFileName, configLineNumber);
         }
         try
         {
             Directory.CreateDirectory(tempDirectory);
             goto Label_0165;
         }
         catch (Exception exception)
         {
             throw new ConfigurationErrorsException(System.Web.SR.GetString("Invalid_temp_directory", new object[] { tempDirAttribName }), exception, configFileName, configLineNumber);
         }
     }
     tempDirectory = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "Temporary ASP.NET Files");
 Label_0165:
     if (!Util.HasWriteAccessToDirectory(tempDirectory))
     {
         if (!Environment.UserInteractive)
         {
             throw new HttpException(System.Web.SR.GetString("No_codegen_access", new object[] { Util.GetCurrentAccountName(), tempDirectory }));
         }
         tempDirectory = Path.Combine(Path.GetTempPath(), "Temporary ASP.NET Files");
     }
     string str7 = AppManagerAppDomainFactory.ConstructSimpleAppName(VirtualPath.GetVirtualPathStringNoTrailingSlash(virtualPath));
     string str9 = HttpRuntime.MakeFileUrl(System.Web.Util.FileUtil.RemoveTrailingDirectoryBackSlash(Path.Combine(tempDirectory, str7)));
     string originUrl = trustSection.OriginUrl;
     FileStream stream = new FileStream(policyFileExpanded, FileMode.Open, FileAccess.Read);
     StreamReader reader = new StreamReader(stream, Encoding.UTF8);
     string str = reader.ReadToEnd();
     reader.Close();
     str = str.Replace("$AppDir$", path).Replace("$AppDirUrl$", newValue).Replace("$CodeGen$", str9);
     if (originUrl == null)
     {
         originUrl = string.Empty;
     }
     str = str.Replace("$OriginHost$", originUrl);
     string gacLocation = null;
     if (str.IndexOf("$Gac$", StringComparison.Ordinal) != -1)
     {
         gacLocation = HttpRuntime.GetGacLocation();
         if (gacLocation != null)
         {
             gacLocation = HttpRuntime.MakeFileUrl(gacLocation);
         }
         if (gacLocation == null)
         {
             gacLocation = string.Empty;
         }
         str = str.Replace("$Gac$", gacLocation);
     }
     level = SecurityManager.LoadPolicyLevelFromString(str, PolicyLevelType.AppDomain);
     if (level == null)
     {
         throw new ConfigurationErrorsException(System.Web.SR.GetString("Unable_to_get_policy_file", new object[] { trustSection.Level }));
     }
     if (gacLocation != null)
     {
         CodeGroup rootCodeGroup = level.RootCodeGroup;
         bool flag = false;
         foreach (CodeGroup group2 in rootCodeGroup.Children)
         {
             if (group2.MembershipCondition is GacMembershipCondition)
             {
                 flag = true;
                 break;
             }
         }
         if (!flag && (rootCodeGroup is FirstMatchCodeGroup))
         {
             FirstMatchCodeGroup group3 = (FirstMatchCodeGroup) rootCodeGroup;
             if (!(group3.MembershipCondition is AllMembershipCondition) || !(group3.PermissionSetName == "Nothing"))
             {
                 return level;
             }
             PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);
             CodeGroup group = new UnionCodeGroup(new GacMembershipCondition(), new PolicyStatement(permSet));
             CodeGroup group5 = new FirstMatchCodeGroup(rootCodeGroup.MembershipCondition, rootCodeGroup.PolicyStatement);
             foreach (CodeGroup group6 in rootCodeGroup.Children)
             {
                 if (((group6 is UnionCodeGroup) && (group6.MembershipCondition is UrlMembershipCondition)) && (group6.PolicyStatement.PermissionSet.IsUnrestricted() && (group != null)))
                 {
                     group5.AddChild(group);
                     group = null;
                 }
                 group5.AddChild(group6);
             }
             level.RootCodeGroup = group5;
         }
     }
     return level;
 }
 private CodeGroup CreateDefaultMachinePolicy()
 {
     UnionCodeGroup group = new UnionCodeGroup();
     group.FromXml(CreateCodeGroupElement("UnionCodeGroup", "Nothing", new AllMembershipCondition().ToXml()), this);
     group.Name = Environment.GetResourceString("Policy_AllCode_Name");
     group.Description = Environment.GetResourceString("Policy_AllCode_DescriptionNothing");
     UnionCodeGroup group2 = new UnionCodeGroup();
     group2.FromXml(CreateCodeGroupElement("UnionCodeGroup", "FullTrust", new ZoneMembershipCondition(SecurityZone.MyComputer).ToXml()), this);
     group2.Name = Environment.GetResourceString("Policy_MyComputer_Name");
     group2.Description = Environment.GetResourceString("Policy_MyComputer_Description");
     StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob("002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293");
     UnionCodeGroup group3 = new UnionCodeGroup();
     group3.FromXml(CreateCodeGroupElement("UnionCodeGroup", "FullTrust", new StrongNameMembershipCondition(blob, null, null).ToXml()), this);
     group3.Name = Environment.GetResourceString("Policy_Microsoft_Name");
     group3.Description = Environment.GetResourceString("Policy_Microsoft_Description");
     group2.AddChildInternal(group3);
     blob = new StrongNamePublicKeyBlob("00000000000000000400000000000000");
     UnionCodeGroup group4 = new UnionCodeGroup();
     group4.FromXml(CreateCodeGroupElement("UnionCodeGroup", "FullTrust", new StrongNameMembershipCondition(blob, null, null).ToXml()), this);
     group4.Name = Environment.GetResourceString("Policy_Ecma_Name");
     group4.Description = Environment.GetResourceString("Policy_Ecma_Description");
     group2.AddChildInternal(group4);
     group.AddChildInternal(group2);
     CodeGroup group5 = new UnionCodeGroup();
     group5.FromXml(CreateCodeGroupElement("UnionCodeGroup", "LocalIntranet", new ZoneMembershipCondition(SecurityZone.Intranet).ToXml()), this);
     group5.Name = Environment.GetResourceString("Policy_Intranet_Name");
     group5.Description = Environment.GetResourceString("Policy_Intranet_Description");
     CodeGroup group6 = new NetCodeGroup(new AllMembershipCondition()) {
         Name = Environment.GetResourceString("Policy_IntranetNet_Name"),
         Description = Environment.GetResourceString("Policy_IntranetNet_Description")
     };
     group5.AddChildInternal(group6);
     CodeGroup group7 = new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read) {
         Name = Environment.GetResourceString("Policy_IntranetFile_Name"),
         Description = Environment.GetResourceString("Policy_IntranetFile_Description")
     };
     group5.AddChildInternal(group7);
     group.AddChildInternal(group5);
     CodeGroup group8 = new UnionCodeGroup();
     group8.FromXml(CreateCodeGroupElement("UnionCodeGroup", "Internet", new ZoneMembershipCondition(SecurityZone.Internet).ToXml()), this);
     group8.Name = Environment.GetResourceString("Policy_Internet_Name");
     group8.Description = Environment.GetResourceString("Policy_Internet_Description");
     CodeGroup group9 = new NetCodeGroup(new AllMembershipCondition()) {
         Name = Environment.GetResourceString("Policy_InternetNet_Name"),
         Description = Environment.GetResourceString("Policy_InternetNet_Description")
     };
     group8.AddChildInternal(group9);
     group.AddChildInternal(group8);
     CodeGroup group10 = new UnionCodeGroup();
     group10.FromXml(CreateCodeGroupElement("UnionCodeGroup", "Nothing", new ZoneMembershipCondition(SecurityZone.Untrusted).ToXml()), this);
     group10.Name = Environment.GetResourceString("Policy_Untrusted_Name");
     group10.Description = Environment.GetResourceString("Policy_Untrusted_Description");
     group.AddChildInternal(group10);
     CodeGroup group11 = new UnionCodeGroup();
     group11.FromXml(CreateCodeGroupElement("UnionCodeGroup", "Internet", new ZoneMembershipCondition(SecurityZone.Trusted).ToXml()), this);
     group11.Name = Environment.GetResourceString("Policy_Trusted_Name");
     group11.Description = Environment.GetResourceString("Policy_Trusted_Description");
     CodeGroup group12 = new NetCodeGroup(new AllMembershipCondition()) {
         Name = Environment.GetResourceString("Policy_TrustedNet_Name"),
         Description = Environment.GetResourceString("Policy_TrustedNet_Description")
     };
     group11.AddChildInternal(group12);
     group.AddChildInternal(group11);
     return group;
 }
 /// <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;
 }
Beispiel #31
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;
		}
        /// From MRMModule.cs by Adam Frisby
        /// <summary>
        ///   Create an AppDomain that contains policy restricting code to execute
        ///   with only the permissions granted by a named permission set
        /// </summary>
        /// <param name = "permissionSetName">name of the permission set to restrict to</param>
        /// <param name = "appDomainName">'friendly' name of the appdomain to be created</param>
        /// <exception cref = "ArgumentNullException">
        ///   if <paramref name = "permissionSetName" /> is null
        /// </exception>
        /// <exception cref = "ArgumentOutOfRangeException">
        ///   if <paramref name = "permissionSetName" /> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>
        ///   Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        ///   Valid permissionSetName values are:
        ///   * FullTrust
        ///   * SkipVerification
        ///   * Execution
        ///   * Nothing
        ///   * LocalIntranet
        ///   * Internet
        ///   * Everything
        /// </remarks>
        public AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName, AppDomainSetup ads)
        {
            if (permissionSetName == null)
                throw new ArgumentNullException("permissionSetName");
            if (permissionSetName.Length == 0)
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");

            // Default to all code getting everything
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);
            AppDomain restrictedDomain = null;

#if NET_3_5

            PolicyStatement emptyPolicy = new PolicyStatement(new PermissionSet(PermissionState.None));
            UnionCodeGroup policyRoot = new UnionCodeGroup(new AllMembershipCondition(), emptyPolicy);

            bool foundName = false;
            // iterate over each policy level
            IEnumerator levelEnumerator = SecurityManager.PolicyHierarchy();
            while (levelEnumerator.MoveNext())
            {
                PolicyLevel level = levelEnumerator.Current as PolicyLevel;

                // if this level has defined a named permission set with the
                // given name, then intersect it with what we've retrieved
                // from all the previous levels
                if (level != null)
                {
                    PermissionSet levelSet = level.GetNamedPermissionSet(permissionSetName);
                    if (levelSet != null)
                    {
                        foundName = true;
                        if (setIntersection != null)
                            setIntersection = setIntersection.Intersect(levelSet);
                    }
                }
            }

            // Intersect() can return null for an empty set, so convert that
            // to an empty set object. Also return an empty set if we didn't find
            // the named permission set we were looking for
            if (setIntersection == null || !foundName)
                setIntersection = new PermissionSet(PermissionState.None);
            else
                setIntersection = new NamedPermissionSet(permissionSetName, setIntersection);

            // if no named permission sets were found, return an empty set,
            // otherwise return the set that was found
            setIntersection.AddPermission(new SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new SecurityPermission(PermissionState.Unrestricted));

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

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

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, null, ads);
            restrictedDomain.SetAppDomainPolicy(appDomainLevel);
#else
            SecurityZone zone = SecurityZone.MyComputer;
            try
            {
                zone = (SecurityZone)Enum.Parse(typeof(SecurityZone), permissionSetName);
            }
            catch
            {
                zone = SecurityZone.MyComputer;
            }

            Evidence ev = new Evidence();
            ev.AddHostEvidence(new Zone(zone));
            setIntersection = SecurityManager.GetStandardSandbox(ev);
            setIntersection.AddPermission(new System.Net.SocketPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new System.Net.WebPermission(PermissionState.Unrestricted));
            setIntersection.AddPermission(new System.Security.Permissions.SecurityPermission(PermissionState.Unrestricted));

            // create an AppDomain where this policy will be in effect
            restrictedDomain = AppDomain.CreateDomain(appDomainName, ev, ads, setIntersection, null);
#endif

            return restrictedDomain;
        }
#pragma warning disable 618 // Policy is obsolete
        private CodeGroup CreateDefaultAllGroup() {
            UnionCodeGroup group = new UnionCodeGroup();
            group.FromXml(CreateCodeGroupElement("UnionCodeGroup", "FullTrust", new AllMembershipCondition().ToXml()), this);
            group.Name = Environment.GetResourceString("Policy_AllCode_Name");
            group.Description = Environment.GetResourceString("Policy_AllCode_DescriptionFullTrust");
            return group;
        }
Beispiel #34
0
        /// <summary>
        /// Deliver full trust unto the Application Domain.
        /// </summary>
        /// <param name="ad">The application Domain to apply the security level to.</param>
        public static void SetSecurityPolicy(AppDomain ad)
        {
            PolicyLevel pLevel = PolicyLevel.CreateAppDomainLevel();
            PermissionSet ps = new PermissionSet( PermissionState.Unrestricted );
            UnionCodeGroup rootCodeGroup = new UnionCodeGroup( new AllMembershipCondition(),
                new PolicyStatement( ps, PolicyStatementAttribute.Nothing ) );

            pLevel.RootCodeGroup = rootCodeGroup;
            ad.SetAppDomainPolicy( pLevel );
        }
        [System.Security.SecurityCritical]  // auto-generated
        private CodeGroup CreateDefaultMachinePolicy() {
            UnionCodeGroup root = new UnionCodeGroup();
            root.FromXml(CreateCodeGroupElement("UnionCodeGroup", "Nothing", new AllMembershipCondition().ToXml()), this);
            root.Name = Environment.GetResourceString("Policy_AllCode_Name");
            root.Description = Environment.GetResourceString("Policy_AllCode_DescriptionNothing");

            UnionCodeGroup myComputerCodeGroup = new UnionCodeGroup();
            myComputerCodeGroup.FromXml(CreateCodeGroupElement("UnionCodeGroup", "FullTrust", new ZoneMembershipCondition(SecurityZone.MyComputer).ToXml()), this);
            myComputerCodeGroup.Name = Environment.GetResourceString("Policy_MyComputer_Name");
            myComputerCodeGroup.Description = Environment.GetResourceString("Policy_MyComputer_Description");

            // This code give trust to anything StrongName signed by Microsoft.
            StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(AssemblyRef.MicrosoftPublicKeyFull);
            UnionCodeGroup microsoft = new UnionCodeGroup();
            microsoft.FromXml(CreateCodeGroupElement("UnionCodeGroup", "FullTrust", new StrongNameMembershipCondition(blob, null, null).ToXml()), this);
            microsoft.Name = Environment.GetResourceString("Policy_Microsoft_Name");
            microsoft.Description = Environment.GetResourceString("Policy_Microsoft_Description");
            myComputerCodeGroup.AddChildInternal(microsoft);

            // This code give trust to anything StrongName signed using the ECMA
            // public key (core system assemblies).
            blob = new StrongNamePublicKeyBlob(AssemblyRef.EcmaPublicKeyFull);
            UnionCodeGroup ecma = new UnionCodeGroup();
            ecma.FromXml(CreateCodeGroupElement("UnionCodeGroup", "FullTrust", new StrongNameMembershipCondition(blob, null, null).ToXml()), this);
            ecma.Name = Environment.GetResourceString("Policy_Ecma_Name");
            ecma.Description = Environment.GetResourceString("Policy_Ecma_Description");
            myComputerCodeGroup.AddChildInternal(ecma);

            root.AddChildInternal(myComputerCodeGroup);

            // do the rest of the zones
            CodeGroup intranet = new UnionCodeGroup();
            intranet.FromXml(CreateCodeGroupElement("UnionCodeGroup", "LocalIntranet", new ZoneMembershipCondition(SecurityZone.Intranet).ToXml()), this);
            intranet.Name = Environment.GetResourceString("Policy_Intranet_Name");
            intranet.Description = Environment.GetResourceString("Policy_Intranet_Description");

            CodeGroup intranetNetCode = new NetCodeGroup(new AllMembershipCondition());
            intranetNetCode.Name = Environment.GetResourceString("Policy_IntranetNet_Name");
            intranetNetCode.Description = Environment.GetResourceString("Policy_IntranetNet_Description");
            intranet.AddChildInternal(intranetNetCode);

            CodeGroup intranetFileCode = new FileCodeGroup(new AllMembershipCondition(), FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery);
            intranetFileCode.Name = Environment.GetResourceString("Policy_IntranetFile_Name");
            intranetFileCode.Description = Environment.GetResourceString("Policy_IntranetFile_Description");
            intranet.AddChildInternal(intranetFileCode);

            root.AddChildInternal(intranet);

            CodeGroup internet = new UnionCodeGroup();
            internet.FromXml(CreateCodeGroupElement("UnionCodeGroup", "Internet", new ZoneMembershipCondition(SecurityZone.Internet).ToXml()), this);
            internet.Name = Environment.GetResourceString("Policy_Internet_Name");
            internet.Description = Environment.GetResourceString("Policy_Internet_Description");

            CodeGroup internetNet = new NetCodeGroup(new AllMembershipCondition());
            internetNet.Name = Environment.GetResourceString("Policy_InternetNet_Name");
            internetNet.Description = Environment.GetResourceString("Policy_InternetNet_Description");
            internet.AddChildInternal(internetNet);

            root.AddChildInternal(internet);

            CodeGroup untrusted = new UnionCodeGroup();
            untrusted.FromXml(CreateCodeGroupElement("UnionCodeGroup", "Nothing", new ZoneMembershipCondition(SecurityZone.Untrusted).ToXml()), this);
            untrusted.Name = Environment.GetResourceString("Policy_Untrusted_Name");
            untrusted.Description = Environment.GetResourceString("Policy_Untrusted_Description");
            root.AddChildInternal(untrusted);

            CodeGroup trusted = new UnionCodeGroup();
            trusted.FromXml(CreateCodeGroupElement("UnionCodeGroup", "Internet", new ZoneMembershipCondition(SecurityZone.Trusted).ToXml()), this);
            trusted.Name = Environment.GetResourceString("Policy_Trusted_Name");
            trusted.Description = Environment.GetResourceString("Policy_Trusted_Description");
            CodeGroup trustedNet = new NetCodeGroup(new AllMembershipCondition());
            trustedNet.Name = Environment.GetResourceString("Policy_TrustedNet_Name");
            trustedNet.Description = Environment.GetResourceString("Policy_TrustedNet_Description");
            trusted.AddChildInternal(trustedNet);

            root.AddChildInternal(trusted);

            return root;
        }
                public static PolicyLevel CreateAppDomainLevel ()
                {
			UnionCodeGroup cg = new UnionCodeGroup (new AllMembershipCondition (), new PolicyStatement (DefaultPolicies.FullTrust));
			cg.Name = "All_Code";
			PolicyLevel pl = new PolicyLevel ("AppDomain", PolicyLevelType.AppDomain);
			pl.RootCodeGroup = cg;
			pl.Reset ();
                        return pl;
                }
        public override CodeGroup Copy()
        {
            UnionCodeGroup group = new UnionCodeGroup();
            
            group.MembershipCondition = this.MembershipCondition;
            group.PolicyStatement = this.PolicyStatement;
            group.Name = this.Name;
            group.Description = this.Description;

            IEnumerator enumerator = this.Children.GetEnumerator();

            while (enumerator.MoveNext())
            {
                group.AddChild( (CodeGroup)enumerator.Current );
            }

            
            return group;
        }
Beispiel #38
0
 internal static string GetDataFormBaseDir()
 {
     string str = config.Configs["DataForm"].GetString("BaseDir", string.Empty);
     if (str.StartsWith("http://") || str.StartsWith("ftp://"))
     {
         IEnumerator enumerator = SecurityManager.PolicyHierarchy();
         enumerator.MoveNext();
         for (PolicyLevel level = enumerator.Current as PolicyLevel; level != null; level = enumerator.Current as PolicyLevel)
         {
             if (level.Label == "Machine")
             {
                 foreach (NamedPermissionSet set in level.NamedPermissionSets)
                 {
                     if (set.Name == "FullTrust")
                     {
                         UrlMembershipCondition membershipCondition = new UrlMembershipCondition(str + "*");
                         PolicyStatement policy = new PolicyStatement(set);
                         UnionCodeGroup group = new UnionCodeGroup(membershipCondition, policy);
                         level.RootCodeGroup.AddChild(group);
                     }
                 }
                 return str;
             }
             enumerator.MoveNext();
         }
         return str;
     }
     return string.Concat(new object[] { "file://", AppDomain.CurrentDomain.BaseDirectory, Path.DirectorySeparatorChar, str });
 }
		// Hardcode defaults in case 
		// (a) the specified policy file doesn't exists; and
		// (b) no corresponding default policy file exists
		internal void CreateDefaultLevel (PolicyLevelType type) 
		{
			PolicyStatement psu = new PolicyStatement (DefaultPolicies.FullTrust);

			switch (type) {
			case PolicyLevelType.Machine:
				// by default all stuff is in the machine policy...
				PolicyStatement psn = new PolicyStatement (DefaultPolicies.Nothing);
				root_code_group = new UnionCodeGroup (new AllMembershipCondition (), psn);
				root_code_group.Name = "All_Code";

				UnionCodeGroup myComputerZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.MyComputer), psu);
				myComputerZone.Name = "My_Computer_Zone";
				// TODO: strongname code group for ECMA and MS keys
				root_code_group.AddChild (myComputerZone);

				UnionCodeGroup localIntranetZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.Intranet), 
					new PolicyStatement (DefaultPolicies.LocalIntranet));
				localIntranetZone.Name = "LocalIntranet_Zone";
				// TODO: same site / same directory
				root_code_group.AddChild (localIntranetZone);

				PolicyStatement psi = new PolicyStatement (DefaultPolicies.Internet);
				UnionCodeGroup internetZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.Internet), psi);
				internetZone.Name = "Internet_Zone";
				// TODO: same site
				root_code_group.AddChild (internetZone);

				UnionCodeGroup restrictedZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.Untrusted), psn);
				restrictedZone.Name = "Restricted_Zone";
				root_code_group.AddChild (restrictedZone);

				UnionCodeGroup trustedZone = new UnionCodeGroup (new ZoneMembershipCondition (SecurityZone.Trusted), psi);
				trustedZone.Name = "Trusted_Zone";
				// TODO: same site
				root_code_group.AddChild (trustedZone);
				break;
			case PolicyLevelType.User:
			case PolicyLevelType.Enterprise:
			case PolicyLevelType.AppDomain:
				// while the other policies don't restrict anything
				root_code_group = new UnionCodeGroup (new AllMembershipCondition (), psu); 
				root_code_group.Name = "All_Code";
				break;
			}
		}
Beispiel #40
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;
		}
 private static void SetupSecurity()
 {
     PolicyLevel domainPolicy = PolicyLevel.CreateAppDomainLevel();
     CodeGroup group = new UnionCodeGroup(new AllMembershipCondition(), domainPolicy.GetNamedPermissionSet("Execution"));
     StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob("002400000480000094000000060200000024000052534131000400000100010007D1FA57C4AED9F0A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C834C99921EB23BE79AD9D5DCC1DD9AD236132102900B723CF980957FC4E177108FC607774F29E8320E92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF0FC4963D261C8A12436518206DC093344D5AD293");
     CodeGroup group2 = new UnionCodeGroup(new StrongNameMembershipCondition(blob, null, null), domainPolicy.GetNamedPermissionSet("FullTrust"));
     StrongNamePublicKeyBlob blob2 = new StrongNamePublicKeyBlob("00000000000000000400000000000000");
     CodeGroup group3 = new UnionCodeGroup(new StrongNameMembershipCondition(blob2, null, null), domainPolicy.GetNamedPermissionSet("FullTrust"));
     CodeGroup group4 = new UnionCodeGroup(new GacMembershipCondition(), domainPolicy.GetNamedPermissionSet("FullTrust"));
     group.AddChild(group2);
     group.AddChild(group3);
     group.AddChild(group4);
     domainPolicy.RootCodeGroup = group;
     try
     {
         AppDomain.CurrentDomain.SetAppDomainPolicy(domainPolicy);
     }
     catch (PolicyException)
     {
     }
 }