private PermissionSet getPermissionSet(AGIScriptMappingElement scriptMapping)
        {
            PermissionSet permission = null;

            switch (scriptMapping.PermissionSet)
            {
            case ScriptPermissionSet.FullTrust:
                permission = PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet("FullTrust");
                break;

            case ScriptPermissionSet.Internet:
                permission = PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet("Internet");
                break;

            case ScriptPermissionSet.Intranet:
                permission = PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet("Intranet");
                break;

            case ScriptPermissionSet.Host:
                permission = AppDomain.CurrentDomain.ApplicationTrust.DefaultGrantSet.PermissionSet;
                break;

            case ScriptPermissionSet.Custom:
                permission = new PermissionSet(PermissionState.None);
                permission.FromXml(scriptMapping.CustomPermissionSet.SecurityElement);
                break;
            }

            return(permission);
        }
Esempio n. 2
0
        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);
        }
Esempio n. 3
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);
    }
Esempio n. 4
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;
        }
Esempio n. 5
0
        private PermissionSet GetPermissionSetForApp(string readonlyDir, string appDir)
        {
            SecurityConfig scfg = null;

            try
            {
                //first load the config
                scfg = SecurityConfig.Load();
            }
            catch (Exception ex)
            {
                logger.Warn("Error loading security config", ex);
                //load the default permission set, and save it to file.
                scfg = new SecurityConfig(true);
                try
                {
                    scfg.Save();
                }
                catch (Exception ex1)
                {
                    logger.Warn("Error saving security config", ex1);
                }
            }

            //return scfg.GetGThreadPermissions(readonlyDir, appDir);
            PermissionSet ps = (PolicyLevel.CreateAppDomainLevel()).GetNamedPermissionSet("FullTrust");

            return(ps);
        }
Esempio n. 6
0
        public void Recover_AppDomainLevel()
        {
            PolicyLevel pl = PolicyLevel.CreateAppDomainLevel();

            pl.Recover();
            // can't recover as it's not file based
        }
        static void Main(string[] args)
        {
            // Create a new application domain.
            AppDomain domain = System.AppDomain.CreateDomain("MyDomain");

            // Create a new AppDomain PolicyLevel.
            PolicyLevel polLevel = PolicyLevel.CreateAppDomainLevel();
            // Create a new, empty permission set.
            PermissionSet permSet = new PermissionSet(PermissionState.None);

            // Add permission to execute code to the permission set.
            permSet.AddPermission
                (new SecurityPermission(SecurityPermissionFlag.Execution));
            // Give the policy level's root code group a new policy statement based
            // on the new permission set.
            polLevel.RootCodeGroup.PolicyStatement = new PolicyStatement(permSet);
            // Give the new policy level to the application domain.
            domain.SetAppDomainPolicy(polLevel);

            // Try to execute the assembly.
            try
            {
                // This will throw a PolicyException if the executable tries to
                // access any resources like file I/O or tries to create a window.
                domain.ExecuteAssembly("Assemblies\\MyWindowsExe.exe");
            }
            catch (PolicyException e)
            {
                Console.WriteLine("PolicyException: {0}", e.Message);
            }

            AppDomain.Unload(domain);
        }
Esempio n. 8
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);
                }
Esempio n. 9
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);
        }
        public static void SetPermissionsSet(this AppDomain appDomain, PermissionSet permissions)
        {
            PolicyLevel policy = PolicyLevel.CreateAppDomainLevel();

            policy.RootCodeGroup.PolicyStatement = new PolicyStatement(permissions);
            appDomain.SetAppDomainPolicy(policy);
        }
Esempio n. 11
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);
        }
Esempio n. 12
0
        public void CreateAppDomainLevel()
        {
            PolicyLevel pl = PolicyLevel.CreateAppDomainLevel();

            Assert.AreEqual("AppDomain", pl.Label, "Label");
            Assert.AreEqual("FullTrust", pl.RootCodeGroup.PermissionSetName, "RootCodeGroup==FullTrust");
            Assert.AreEqual(0, pl.RootCodeGroup.Children.Count, "RootCodeGroup/NoChildren");
            Assert.IsTrue(pl.RootCodeGroup.PolicyStatement.PermissionSet.IsUnrestricted(), "RootCodeGroup.PolicyStatement.PermissionSet.IsUnrestricted");
        }
Esempio n. 13
0
        public void ToXml()
        {
            HashMembershipCondition hash = new HashMembershipCondition(md5, digestMd5);
            SecurityElement         se   = hash.ToXml();

            Assert.AreEqual("IMembershipCondition", se.Tag, "Tag");
            Assert.IsTrue(se.Attribute("class").StartsWith("System.Security.Policy.HashMembershipCondition"), "class");
            Assert.AreEqual("1", se.Attribute("version"), "version");
            Assert.AreEqual(se.ToString(), hash.ToXml(null).ToString(), "ToXml(null)");
            Assert.AreEqual(se.ToString(), hash.ToXml(PolicyLevel.CreateAppDomainLevel()).ToString(), "ToXml(PolicyLevel)");
        }
Esempio n. 14
0
        public void ResolveMatchingCodeGroups_Empty()
        {
            PolicyLevel pl     = PolicyLevel.CreateAppDomainLevel();
            CodeGroup   result = pl.ResolveMatchingCodeGroups(new Evidence());

            Assert.IsNotNull(result, "CodeGroup");
            Assert.AreEqual(String.Empty, result.AttributeString, "AttributeString");
            Assert.AreEqual(0, result.Children.Count, "Count");
            Assert.AreEqual("Union", result.MergeLogic, "MergeLogic");
            Assert.IsTrue(result.PolicyStatement.PermissionSet.IsUnrestricted(), "IsUnrestricted");
        }
Esempio n. 15
0
        public void Resolve_Empty()
        {
            PolicyLevel     pl     = PolicyLevel.CreateAppDomainLevel();
            PolicyStatement result = pl.Resolve(new Evidence());

            Assert.IsNotNull(result, "PolicyStatement");
            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");
        }
Esempio n. 16
0
        public void ToXml()
        {
            DomainApplicationMembershipCondition domapp = new DomainApplicationMembershipCondition();
            SecurityElement se = domapp.ToXml();

            Assert.AreEqual("IMembershipCondition", se.Tag, "Tag");
            Assert.IsTrue(se.Attribute("class").StartsWith("System.Security.Policy.DomainApplicationMembershipCondition"), "class");
            Assert.AreEqual("1", se.Attribute("version"), "version");
            Assert.AreEqual(se.ToString(), domapp.ToXml(null).ToString(), "ToXml(null)");
            Assert.AreEqual(se.ToString(), domapp.ToXml(PolicyLevel.CreateAppDomainLevel()).ToString(), "ToXml(PolicyLevel)");
        }
Esempio n. 17
0
        public void FromXml()
        {
            PolicyLevel     pl = PolicyLevel.CreateAppDomainLevel();
            SecurityElement se = pl.ToXml();

            pl.FromXml(se);
            Assert.AreEqual("AppDomain", pl.Label, "Label");
            Assert.AreEqual("All_Code", pl.RootCodeGroup.Name, "RootCodeGroup");
            Assert.AreEqual("FullTrust", pl.RootCodeGroup.PermissionSetName, "PermissionSetName");
            Assert.AreEqual(0, pl.RootCodeGroup.Children.Count, "Children");
        }
Esempio n. 18
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;
        }
Esempio n. 19
0
        public void ToXml()
        {
            PolicyLevel     pl  = Load(minimal, PolicyLevelType.Machine);
            PolicyLevel     pl2 = PolicyLevel.CreateAppDomainLevel();
            SecurityElement se  = pl.ToXml();

            pl2.FromXml(se);

            Assert.AreEqual(pl.FullTrustAssemblies.Count, pl2.FullTrustAssemblies.Count, "ToXml-FullTrustAssemblies");
            Assert.AreEqual(pl.NamedPermissionSets.Count, pl2.NamedPermissionSets.Count, "ToXml-NamedPermissionSets");
            Assert.IsTrue(pl.RootCodeGroup.Equals(pl2.RootCodeGroup, true), "ToXml-RootCodeGroup");
            Assert.AreEqual(pl.StoreLocation, pl2.StoreLocation, "ToXml-StoreLocation");
        }
Esempio n. 20
0
    static public void Main(string[] args)
    {
        try
        {
            // Create a new, empty permission set so we don't mistakenly grant some permission we don't want
            PermissionSet permissionSet = new PermissionSet(PermissionState.None);

            // Set the permissions that you will allow, in this case we only want to allow execution of code
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            // Make sure we have the permissions currently
            permissionSet.Demand();

            // Create the security policy level for this application domain
            PolicyLevel policyLevel = PolicyLevel.CreateAppDomainLevel();

            // Give the policy level's root code group a new policy statement based on the new permission set.
            policyLevel.RootCodeGroup.PolicyStatement = new PolicyStatement(permissionSet);

            CSScript.GlobalSettings.AddSearchDir(Environment.CurrentDirectory);

            File.Copy("Danger.cs", "Danger1.cs", true);
            var script = new AsmHelper(CSScript.Load("Danger.cs"));

            // Update the application domain's policy now
            AppDomain.CurrentDomain.SetAppDomainPolicy(policyLevel);

            var script1 = new AsmHelper(CSScript.Load("Danger1.cs"));

            Console.WriteLine();
            Console.WriteLine("Access local file from host application assembly...");
            using (FileStream f = File.Open("somefile.txt", FileMode.OpenOrCreate)) //OK because executing assembly was loaded before the new policy set
                Console.WriteLine("  Ok");
            Console.WriteLine();

            Console.WriteLine("Access local file from Script assembly (before security policy set)...");
            script.Invoke("*.SayHello"); //OK because executing assembly was loaded before the new policy set
            Console.WriteLine();

            Console.WriteLine("Access local file from Script assembly (after security policy set)...\n");
            script1.Invoke("*.SayHello"); //ERROR because executing assembly was loaded after the new policy set

            Console.WriteLine("The end...");
        }
        catch (Exception e)
        {
            Console.WriteLine();
            Console.WriteLine(e.Message);
            Console.WriteLine();
        }
    }
        public PolicyLevel CreateMediumTrustPolicy()
        {
            PolicyLevel policyLevel = PolicyLevel.CreateAppDomainLevel();
            string      contents;

            using (var file = File.OpenText(MediumTrustConfigFile))
            {
                contents = file.ReadToEnd();
            }
            SecurityElement securityElement = SecurityElement.FromString(Resources.MediumTrustConfig);

            policyLevel.FromXml(securityElement);
            return(policyLevel);
        }
Esempio n. 22
0
        public void Label()
        {
            PolicyLevel pl = Load(minimal, PolicyLevelType.AppDomain);

            Assert.AreEqual("AppDomain", pl.Label, "Label.AppDomain");
            pl = Load(minimal, PolicyLevelType.Enterprise);
            Assert.AreEqual("Enterprise", pl.Label, "Label.Enterprise");
            pl = Load(minimal, PolicyLevelType.Machine);
            Assert.AreEqual("Machine", pl.Label, "Label.Machine");
            pl = Load(minimal, PolicyLevelType.User);
            Assert.AreEqual("User", pl.Label, "Label.User");
            // static method
            pl = PolicyLevel.CreateAppDomainLevel();
            Assert.AreEqual("AppDomain", pl.Label, "Label.AppDomain");
        }
Esempio n. 23
0
    // Compare two PolicyLevels using ToXml and FromXml.
    private static bool ComparePolicyLevels(PolicyLevel pLevel1, PolicyLevel pLevel2)
    {
        bool        retVal     = false;
        PolicyLevel firstCopy  = PolicyLevel.CreateAppDomainLevel();
        PolicyLevel secondCopy = PolicyLevel.CreateAppDomainLevel();

        // Create copies of the two PolicyLevels passed in.
        // Convert the two PolicyLevels to their canonical form using ToXml and FromXml.
        firstCopy.FromXml(pLevel1.ToXml());
        secondCopy.FromXml(pLevel2.ToXml());
        if (firstCopy.ToXml().ToString().CompareTo(secondCopy.ToXml().ToString()) == 0)
        {
            retVal = true;
        }
        return(retVal);
    }
Esempio n. 24
0
        public void FromXml_Invalid()
        {
            PolicyLevel     pl = PolicyLevel.CreateAppDomainLevel();
            SecurityElement se = pl.ToXml();

            se.Tag = "Mono";
            // strangely this works :(
            pl.FromXml(se);
            // let's get weirder :)
            foreach (SecurityElement child in se.Children)
            {
                child.Tag = "Mono";
            }
            pl.FromXml(se);
            // it's enough >:)
        }
        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);
        }
Esempio n. 26
0
        private void Resolve_Zone_Unrestricted_Attribute(SecurityZone zone, PolicyStatementAttribute attr)
        {
            IMembershipCondition mc = new ZoneMembershipCondition(zone);
            PolicyStatement      ps = new PolicyStatement(new PermissionSet(PermissionState.Unrestricted));

            ps.Attributes = attr;
            PolicyLevel pl = PolicyLevel.CreateAppDomainLevel();

            pl.RootCodeGroup = new UnionCodeGroup(mc, ps);

            Resolve_Zone(pl, SecurityZone.Internet, attr, (zone == SecurityZone.Internet), 0);
            Resolve_Zone(pl, SecurityZone.Intranet, attr, (zone == SecurityZone.Intranet), 0);
            Resolve_Zone(pl, SecurityZone.MyComputer, attr, (zone == SecurityZone.MyComputer), 0);
            Resolve_Zone(pl, SecurityZone.NoZone, attr, (zone == SecurityZone.NoZone), 0);
            Resolve_Zone(pl, SecurityZone.Trusted, attr, (zone == SecurityZone.Trusted), 0);
            Resolve_Zone(pl, SecurityZone.Untrusted, attr, (zone == SecurityZone.Untrusted), 0);
        }
Esempio n. 27
0
        /// <summary>
        /// Creates a sandboxed app domain
        /// </summary>
        /// <param name="Permissions">The PermissionSet to apply to the new app domain</param>
        /// <param name="fullTrustAssembliesPath">Stream containing the full trust public key blobs</param>
        private void CreateSandboxedDomain(PermissionSet Permissions, string fullTrustAssembliesPath)
        {
            //create policy level
            PolicyLevel polLevel = PolicyLevel.CreateAppDomainLevel();

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

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

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

            //apply security policy
            sandbox.SetAppDomainPolicy(polLevel);
        }
 internal void Init(string rule, byte[] il, byte[] pdb)
 {
     _assembly    = Assembly.Load(il, pdb);
     _grammarType = GetTypeForRule(_assembly, rule);
     if (_grammarType == null)
     {
         throw new FormatException(SR.Get(SRID.RecognizerRuleNotFoundStream, rule));
     }
     _rule = rule;
     try
     {
         _grammar = (Grammar)_assembly.CreateInstance(_grammarType.FullName);
     }
     catch (MissingMemberException)
     {
         throw new ArgumentException(SR.Get(SRID.RuleScriptInvalidParameters, _grammarType.FullName, rule), "rule");
     }
     _internetPermissionSet = PolicyLevel.CreateAppDomainLevel().GetNamedPermissionSet("Internet");
     _internetPermissionSet.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));
 }
Esempio n. 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);
        }
Esempio n. 30
0
        public PermissionSet CreatePermissionSet()
        {
            PermissionSet pset = null;

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