예제 #1
0
    // Create a child code group with read-access file permissions and add it
    // to the specified code group.
    private static void addChildCodeGroup(ref FirstMatchCodeGroup codeGroup)
    {
        // Create a first match code group with read access.
        //<Snippet8>
        FileIOPermission rootFilePermissions =
            new FileIOPermission(PermissionState.None);

        rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read;
        rootFilePermissions.SetPathList(FileIOPermissionAccess.Read, "C:\\");

        PermissionSet permissions =
            new PermissionSet(PermissionState.Unrestricted);

        permissions.AddPermission(rootFilePermissions);

        FirstMatchCodeGroup tempFolderCodeGroup = new FirstMatchCodeGroup(
            new AllMembershipCondition(),
            new PolicyStatement(permissions));

        // Set the name of the child code group and add it to
        // the specified code group.
        tempFolderCodeGroup.Name = "Read-only code group";
        codeGroup.AddChild(tempFolderCodeGroup);
        //</Snippet8>
    }
예제 #2
0
        public void Constructor()
        {
            FirstMatchCodeGroup cg = new FirstMatchCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));

            Assert.IsNotNull(cg.PolicyStatement, "PolicyStatement");
            Assert.IsNotNull(cg.MembershipCondition, "MembershipCondition");
        }
예제 #3
0
    // If a domain attribute is not found in the specified
    // FirstMatchCodeGroup, add a child XML element identifying a custom
    // membership condition.
    private static void addXmlMember(ref FirstMatchCodeGroup codeGroup)
    {
        //<Snippet10>
        SecurityElement xmlElement = codeGroup.ToXml();
        //</Snippet10>

        SecurityElement rootElement = new SecurityElement("CodeGroup");

        if (xmlElement.Attribute("domain") == null)
        {
            //<Snippet11>
            SecurityElement newElement =
                new SecurityElement("CustomMembershipCondition");
            newElement.AddAttribute("class", "CustomMembershipCondition");
            newElement.AddAttribute("version", "1");
            newElement.AddAttribute("domain", "contoso.com");

            rootElement.AddChild(newElement);

            codeGroup.FromXml(rootElement);
            //</Snippet11>
        }

        Console.WriteLine("Added a custom membership condition:");
        Console.WriteLine(rootElement.ToString());
    }
예제 #4
0
        public void Constructor_MembershipConditionPolicyStatementNull()
        {
            // legal
            FirstMatchCodeGroup cg = new FirstMatchCodeGroup(new AllMembershipCondition(), null);

            Assert.IsNull(cg.PolicyStatement, "PolicyStatement");
        }
    static void Main(string[] args)
    {
        // Create a new FirstMatchCodeGroup.
        FirstMatchCodeGroup codeGroup = constructDefaultGroup();

        // Create a deep copy of the FirstMatchCodeGroup.
        FirstMatchCodeGroup copyCodeGroup =
            (FirstMatchCodeGroup)codeGroup.Copy();

        // Compare the original code group with the copy.
        CompareTwoCodeGroups(codeGroup, copyCodeGroup);

        addPolicy(ref codeGroup);
        addXmlMember(ref codeGroup);
        updateMembershipCondition(ref codeGroup);
        addChildCodeGroup(ref codeGroup);

        Console.Write("Comparing the resolved code group ");
        Console.WriteLine("with the initial code group.");
        FirstMatchCodeGroup resolvedCodeGroup =
            ResolveGroupToEvidence(codeGroup);

        if (CompareTwoCodeGroups(codeGroup, resolvedCodeGroup))
        {
            PrintCodeGroup(resolvedCodeGroup);
        }
        else
        {
            PrintCodeGroup(codeGroup);
        }

        Console.WriteLine("This sample completed successfully; " +
                          "press Enter to exit.");
        Console.ReadLine();
    }
예제 #6
0
파일: source.cs 프로젝트: ruo2012/samples-1
    void Method()
    {
        FirstMatchCodeGroup codeGroup = new FirstMatchCodeGroup(null, new PolicyStatement(new PermissionSet(PermissionState.None)));

        // <Snippet1>
        codeGroup.PolicyStatement = new PolicyStatement(new NamedPermissionSet("MyPermissionSet"));
        // </Snippet1>
    }
예제 #7
0
        public static void FirstMatchCodeGroupCallMethods()
        {
            FirstMatchCodeGroup fmcg = new FirstMatchCodeGroup(new GacMembershipCondition(), new PolicyStatement(new PermissionSet(new PermissionState())));
            CodeGroup           cg   = fmcg.Copy();
            PolicyStatement     ps   = fmcg.Resolve(new Evidence());

            cg = fmcg.ResolveMatchingCodeGroups(new Evidence());
        }
예제 #8
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);
        }
    // Set the membership condition of the code group.
    private static void updateMembershipCondition(
        ref FirstMatchCodeGroup codeGroup)
    {
        // Set the membership condition of the specified FirstMatchCodeGroup
        // to the Intranet zone.
        ZoneMembershipCondition zoneCondition =
            new ZoneMembershipCondition(SecurityZone.Intranet);

        codeGroup.MembershipCondition = zoneCondition;
    }
예제 #10
0
        public void CopyWithChildren()
        {
            FirstMatchCodeGroup cgChild = new FirstMatchCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.Unrestricted)));
            FirstMatchCodeGroup cg      = new FirstMatchCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));

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

            Assert.AreEqual(cg.Children.Count, cg2.Children.Count, "Children");
            Assert.AreEqual(cg.ToXml().ToString(), cg2.ToXml().ToString(), "ToXml");
        }
    // Retrieve the resolved code group based on the evidence from the
    // specified code group.
    private static FirstMatchCodeGroup ResolveGroupToEvidence(
        FirstMatchCodeGroup codeGroup)
    {
        // Resolve matching code groups to the executing assembly.
        Assembly  assembly          = typeof(Members).Assembly;
        Evidence  evidence          = assembly.Evidence;
        CodeGroup resolvedCodeGroup =
            codeGroup.ResolveMatchingCodeGroups(evidence);

        return((FirstMatchCodeGroup)resolvedCodeGroup);
    }
예제 #12
0
        public void Copy()
        {
            FirstMatchCodeGroup cg  = new FirstMatchCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));
            FirstMatchCodeGroup cg2 = (FirstMatchCodeGroup)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");
        }
 // Compare the two FirstMatchCodeGroups.
 private static bool CompareTwoCodeGroups(
     FirstMatchCodeGroup firstCodeGroup,
     FirstMatchCodeGroup secondCodeGroup)
 {
     // Compare the two specified FirstMatchCodeGroups for equality.
     if (firstCodeGroup.Equals(secondCodeGroup))
     {
         Console.WriteLine("The two code groups are equal.");
         return(true);
     }
     else
     {
         Console.WriteLine("The two code groups are not equal.");
         return(false);
     }
 }
예제 #14
0
    // Create a FirstMatchCodeGroup with an exclusive policy and membership
    // condition.
    private static FirstMatchCodeGroup constructDefaultGroup()
    {
        // Construct a new FirstMatchCodeGroup with Read, Write, Append
        // and PathDiscovery access.
        // Create read access permission to the root directory on drive C.
        //<Snippet2>
        FileIOPermission rootFilePermissions =
            new FileIOPermission(PermissionState.None);

        rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read;
        rootFilePermissions.SetPathList(FileIOPermissionAccess.Read, "C:\\");

        // Add a permission to a named permission set.
        NamedPermissionSet namedPermissions =
            new NamedPermissionSet("RootPermissions");

        namedPermissions.AddPermission(rootFilePermissions);

        // Create a PolicyStatement with exclusive rights to the policy.
        PolicyStatement policy = new PolicyStatement(
            namedPermissions, PolicyStatementAttribute.Exclusive);

        // Create a FirstMatchCodeGroup with a membership condition that
        // matches all code, and an exclusive policy.
        FirstMatchCodeGroup codeGroup =
            new FirstMatchCodeGroup(
                new AllMembershipCondition(),
                policy);

        //</Snippet2>

        // Set the name of the first match code group.
        //<Snippet3>
        codeGroup.Name = "TempCodeGroup";
        //</Snippet3>

        // Set the description of the first match code group.
        //<Snippet4>
        codeGroup.Description = "Temp folder permissions group";
        //</Snippet4>

        return(codeGroup);
    }
예제 #15
0
        public void ToFromXmlRoundtrip()
        {
            const string        ps_Name = "TestName";
            PolicyStatement     ps      = new PolicyStatement(new NamedPermissionSet(ps_Name));
            FirstMatchCodeGroup cg      = new FirstMatchCodeGroup(new AllMembershipCondition(), ps);

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

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

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

            cg2.FromXml(se);
            Assert.IsTrue(cg.Equals(cg2), "Equals (FromXml)");
        }
예제 #16
0
        /// <summary>
        /// Loads a policy from a file (<see cref="SecurityManager.LoadPolicyLevelFromFile"/>),
        /// replacing placeholders
        /// <list>
        ///   <item>$AppDir$, $AppDirUrl$ => <paramref name="appDirectory"/></item>
        ///   <item>$CodeGen$ => (TODO)</item>
        ///   <item>$OriginHost$ => <paramref name="originUrl"/></item>
        ///   <item>$Gac$ => the current machine's GAC path</item>
        /// </list>
        /// </summary>
        /// <param name="policyFileLocation"></param>
        /// <param name="originUrl"></param>
        /// <param name="appDirectory"></param>
        /// <returns></returns>
        public static PolicyLevel LoadDomainPolicyFromUri(Uri policyFileLocation, string appDirectory, string originUrl)
        {
            bool        foundGacToken = false;
            PolicyLevel domainPolicy  = CreatePolicyLevel(policyFileLocation, appDirectory, appDirectory, originUrl, out foundGacToken);

            if (foundGacToken)
            {
                CodeGroup rootCodeGroup             = domainPolicy.RootCodeGroup;
                bool      hasGacMembershipCondition = false;
                foreach (CodeGroup childCodeGroup in rootCodeGroup.Children)
                {
                    if (childCodeGroup.MembershipCondition is GacMembershipCondition)
                    {
                        hasGacMembershipCondition = true;
                        break;
                    }
                }
                if (!hasGacMembershipCondition && (rootCodeGroup is FirstMatchCodeGroup))
                {
                    FirstMatchCodeGroup firstMatchCodeGroup = (FirstMatchCodeGroup)rootCodeGroup;
                    if ((firstMatchCodeGroup.MembershipCondition is AllMembershipCondition) && (firstMatchCodeGroup.PermissionSetName == PERMISSIONSET_NOTHING))
                    {
                        PermissionSet unrestrictedPermissionSet = new PermissionSet(PermissionState.Unrestricted);
                        CodeGroup     gacGroup  = new UnionCodeGroup(new GacMembershipCondition(), new PolicyStatement(unrestrictedPermissionSet));
                        CodeGroup     rootGroup = new FirstMatchCodeGroup(rootCodeGroup.MembershipCondition, rootCodeGroup.PolicyStatement);
                        foreach (CodeGroup childGroup in rootCodeGroup.Children)
                        {
                            if (((childGroup is UnionCodeGroup) && (childGroup.MembershipCondition is UrlMembershipCondition)) && (childGroup.PolicyStatement.PermissionSet.IsUnrestricted() && (gacGroup != null)))
                            {
                                rootGroup.AddChild(gacGroup);
                                gacGroup = null;
                            }
                            rootGroup.AddChild(childGroup);
                        }
                        domainPolicy.RootCodeGroup = rootGroup;
                    }
                }
            }
            return(domainPolicy);
        }
    // Add file permission to restrict write access to all files
    // on the local machine.
    private static void addPolicy(ref FirstMatchCodeGroup codeGroup)
    {
        // Set the PolicyStatement property to a policy with read access to
        // the root directory on drive C.
        FileIOPermission rootFilePermissions =
            new FileIOPermission(PermissionState.None);

        rootFilePermissions.AllLocalFiles = FileIOPermissionAccess.Read;
        rootFilePermissions.SetPathList(FileIOPermissionAccess.Read, "C:\\");

        NamedPermissionSet namedPermissions =
            new NamedPermissionSet("RootPermissions");

        namedPermissions.AddPermission(rootFilePermissions);

        // Create a PolicyStatement with exclusive rights to the policy.
        PolicyStatement policy = new PolicyStatement(
            namedPermissions,
            PolicyStatementAttribute.Exclusive);

        codeGroup.PolicyStatement = policy;
    }
예제 #18
0
        // Arguments: Codebase, flags, zone, srcurl
        // If the flags indicate zone then a zone must be provided.
        // If the flags indicate a site then a srcurl must be provided, codebase must be a filepath
        public int Execute(string codebase, Int32 flags, Int32 evidenceZone, string evidenceSrcUrl, string stringArg)
        {
            string file = codebase;

            if ((file.Length == 0) || (file[0] == '\0'))
            {
                throw new ArgumentException("Invalid codebase");
            }

            Console.WriteLine("Codebase- {0}", file);

            // Find the appbase of the executable. For now we assume the
            // form to be http://blah/... with forward slashes. This
            // need to be update.
            // Note: aso works with '\' as in file paths
            string appbase           = null;
            string ConfigurationFile = null;
            int    k = file.LastIndexOf('/');

            if (k <= 0)
            {
                k = file.LastIndexOf('\\');
                if (k == 0)
                {
                    appbase           = file;
                    ConfigurationFile = file;
                }
            }

            if (k != 0)
            {
                // if k is still < 0 at this point, appbase should be an empty string
                appbase = file.Substring(0, k + 1);
                if (k + 1 < file.Length)
                {
                    ConfigurationFile = file.Substring(k + 1);
                }
            }

            // Check 1: disallow non-fully qualified path/codebase
            if ((appbase.Length == 0) || (appbase[0] == '.'))
            {
                throw new ArgumentException("Codebase must be fully qualified");
            }

            // BUGBUG: should appbase be the source of the code, not local?
            Console.WriteLine("AppBase- {0}", appbase);

            // Build up the configuration File name
            if (ConfigurationFile != null)
            {
                StringBuilder bld = new StringBuilder();
                bld.Append(ConfigurationFile);
                bld.Append(".config");
                ConfigurationFile = bld.ToString();
            }

            Console.WriteLine("Config- {0}", ConfigurationFile);

            // Get the flags
            // 0x1 we have Zone
            // 0x2 we have a unique id.
            int dwFlag = flags;

            Evidence securityEvidence = null;

            // Check 2: disallow called with no evidence
            if (dwFlag == SECURITY_NONE)
            {
                // BUGBUG?: disallow executing with no evidence
                throw new ArgumentException("Flag set at no evidence");
            }

            if ((dwFlag & SECURITY_SITE) != 0 ||
                (dwFlag & SECURITY_ZONE) != 0)
            {
                securityEvidence = new Evidence();
            }

            // BUGBUG: check other invalid cases for dwFlag

            string appURLbase = null;

            if ((dwFlag & SECURITY_ZONE) != 0)
            {
                int zone = evidenceZone;
                securityEvidence.AddHost(new Zone((System.Security.SecurityZone)zone));

                Console.WriteLine("Evidence Zone- {0}", zone);
            }
            if ((dwFlag & SECURITY_SITE) != 0)
            {
                if (file.Length < 7 || String.Compare(file.Substring(0, 7), "file://", true) != 0)
                {
                    securityEvidence.AddHost(System.Security.Policy.Site.CreateFromUrl(evidenceSrcUrl));

                    Console.WriteLine("Evidence SiteFromUrl- {0}", evidenceSrcUrl);

                    // BUGBUG: possible security hole? - if this intersects with Url/Zone _may_ resolve to a less restrictive policy...
                    // if srcUrl is given, assume file/appbase is a local file path
                    StringBuilder bld = new StringBuilder();
                    bld.Append("file://");
                    bld.Append(appbase);
                    securityEvidence.AddHost(new ApplicationDirectory(bld.ToString()));

                    Console.WriteLine("Evidence AppDir- {0}", bld);
                }

                // URLs may be matched exactly or by a wildcard in the final position,
                // for example: http://www.fourthcoffee.com/process/*
                StringBuilder bld2 = new StringBuilder();
                if (evidenceSrcUrl[evidenceSrcUrl.Length - 1] == '/')
                {
                    bld2.Append(evidenceSrcUrl);
                }
                else
                {
                    int j = evidenceSrcUrl.LastIndexOf('/');
                    if (j > 0)
                    {
                        if (j > 7)  // evidenceSrcUrl == "http://a/file.exe"
                        {
                            bld2.Append(evidenceSrcUrl.Substring(0, j + 1));
                        }
                        else
                        {
                            // evidenceSrcUrl == "http://foo.com" -> but why?
                            bld2.Append(evidenceSrcUrl);
                            bld2.Append('/');
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Invalid Url format");
                    }
                }

                appURLbase = bld2.ToString();

                bld2.Append('*');

                securityEvidence.AddHost(new Url(bld2.ToString()));

                Console.WriteLine("Evidence Url- {0}", bld2);
            }

            // other evidence: Hash, Publisher, StrongName

            // 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.

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

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

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

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

            // 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://" + appbase + "*"), AppStatement);

            // Add AppCG to RootCG as first child.  This is important because we need it to be evaluated first
//	     if ((dwFlag & TYPE_AVALON) == 0)
            RootCG.AddChild(AppCG);

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

            // 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.
            PolicyLevel 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.

            // Set domain name to site name if possible
            string friendlyName = null;

            if ((dwFlag & SECURITY_SITE) != 0)
            {
                friendlyName = GetSiteName(evidenceSrcUrl);
            }
            else
            {
                friendlyName = GetSiteName(file);
            }
            Console.WriteLine("AppDomain friendlyName- {0}", friendlyName);

            // set up arguments
            // only allow 1 for now
            string[] args;
            if (stringArg != null)
            {
                args    = new string[1];
                args[0] = stringArg;
            }
            else
            {
                args = new string[0];
            }

            AppDomainSetup properties = new AppDomainSetup();

//            properties.DisallowPublisherPolicy=true;  // not allowed to set safe mode
            properties.ApplicationBase = appbase;   // BUGBUG: security? see note on ApplicationDirectory above
            properties.PrivateBinPath  = "bin";
            if (ConfigurationFile != null)
            {
                properties.ConfigurationFile = ConfigurationFile;   // should not set config file if it doesnot exist?
            }
            AppDomain proxy = AppDomain.CreateDomain(friendlyName, null, properties);

            if (proxy != null)
            {
                // set the AppPolicy policy level as the policy level for the AppDomain
                proxy.SetAppDomainPolicy(AppPolicy);

                AssemblyName asmname = Assembly.GetExecutingAssembly().GetName();
                Console.WriteLine("AsmExecute name- {0}", asmname);

                try
                {
                    // Use remoting. Otherwise asm will be loaded both in current and the new AppDomain
                    // ... as explained by URT dev
                    // asmexec.dll must be found on path (CorPath?) or in the GAC for this to work.
                    ObjectHandle handle = proxy.CreateInstance(asmname.FullName, "FusionCLRHost.AsmExecute");
                    if (handle != null)
                    {
                        AsmExecute execproxy = (AsmExecute)handle.Unwrap();
                        int        retVal    = -1;

                        if (execproxy != null)
                        {
                            // prepare for on-demand/asm resolution
                            execproxy.InitOnDemand(appbase, appURLbase);
                        }

                        Console.WriteLine("\n========");

                        if (execproxy != null)
                        {
                            if ((dwFlag & TYPE_AVALON) != 0)
                            {
                                retVal = execproxy.ExecuteAsAvalon(file, securityEvidence, args);
                            }
                            else
                            {
                                retVal = execproxy.ExecuteAsAssembly(file, securityEvidence, args);
                            }
                        }

                        Console.WriteLine("\n========");

                        return(retVal);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("AsmExecute CreateInstance(AsmExecute) / execute assembly failed:\n{0}: {1}", e.GetType(), e.Message);
                    throw e;
                }
            }
            else
            {
                Console.WriteLine("AsmExecute CreateDomain failed");
            }

            // BUGBUG: throw Exception?
            return(-1);
        }
예제 #19
0
        // This routine sets up the Code Access Security policy that Terrarium runs under.  It is key
        // to ensuring that organisms can never do anything dangerous.
        //
        // The policy tree looks like this:
        // All Code - Nothing
        //   My Computer - Nothing
        //      Terrarium Code Directory - Execute permission only
        //      Terrarium Key - Full Trust
        //      System.dll Code base - Full Trust (for XML serialization emitted assemblies)
        //      MS Name - Full Trust
        //      ECMA Name - Full Trust
        //      Terrarium.Exe Code Dir - Execute Only
        //
        // Order is important since we're using a first match code group.  If an assembly lives in the cache directory,
        // it gets nothing.
        internal static PolicyLevel MakePolicyLevel(string cacheDir)
        {
            var noPerms = new PermissionSet(PermissionState.None);

            // All Code, Nothing
            var allCode = new FirstMatchCodeGroup(new AllMembershipCondition(),
                                                  new PolicyStatement(noPerms));

            // My Computer, Nothing
            var myComputer =
                new FirstMatchCodeGroup(new ZoneMembershipCondition(SecurityZone.MyComputer),
                                        new PolicyStatement(noPerms));

            // Terrarium code dir: if name is blank, skip it
            UnionCodeGroup cacheDirGroup = null;

            if (cacheDir != null)
            {
                var cacheDirFull = Path.GetFullPath(cacheDir);
                if (Directory.Exists(cacheDirFull))
                {
                    var fileCanon = cacheDirFull.Replace("\\", "/");
                    var fileUrl   = String.Format("file://{0}/*", fileCanon);

                    cacheDirGroup = new UnionCodeGroup(new UrlMembershipCondition(fileUrl),
                                                       new PolicyStatement(MakeExecutionOnlyPermSet()));
                }
            }

            // When webservices creates a serialization dll dynamically, it loads it into memory
            // and it gets the evidence from System.Dll.  Thus, to make sure these assemblies get
            // full trust, we need to make sure that anything that has this same evidence is
            // added to policy
            var codeBase  = typeof(Process).Assembly.CodeBase;
            var systemDll =
                new UnionCodeGroup(new UrlMembershipCondition(codeBase),
                                   new PolicyStatement(MakeTrustedPermSet()));

            var myCodeTrust =
                new UnionCodeGroup(new StrongNameMembershipCondition(
                                       MakeSelfRelativeBlob(), null, null),
                                   new PolicyStatement(MakeTrustedPermSet()));

            var myMSTrust = MakeMSCodeGroup();
            var ecmaTrust = MakeEcmaCodeGroup();

            // Terrarium does a Load(byte []) on assemblies to check them before it copies them to the PAC to
            // truly load them.  However, since unsigned (by MS or Terrarium) assemblies outside of the PAC
            // don't get execute permissions, this load fails.  Since we are doing a Load(byte []), the evidence
            // will say that the assembly is coming from the same location as Terrarium.Exe, therefore
            // we need to add policy that gives unsigned assemblies in the same location as terrarium.exe
            // Execute permissions.  This is the exact code (and logic) we use for the systemDll code group above.
            var terrariumCodeBase  = typeof(GameEngine).Assembly.CodeBase;
            var checkAssemblyTrust = new UnionCodeGroup(new UrlMembershipCondition(terrariumCodeBase),
                                                        new PolicyStatement(MakeExecutionOnlyPermSet()));

            // add children of MyComputer CG
            if (cacheDirGroup != null)
            {
                myComputer.AddChild(cacheDirGroup);
            }

            myComputer.AddChild(myCodeTrust);
            myComputer.AddChild(systemDll);
            myComputer.AddChild(myMSTrust);
            myComputer.AddChild(ecmaTrust);
            myComputer.AddChild(checkAssemblyTrust);

            // add MyComputer under All Code
            allCode.AddChild(myComputer);
            var level = PolicyLevel.CreateAppDomainLevel();

            level.RootCodeGroup = allCode;
            return(level);
        }
예제 #20
0
        public void ResolveMatchingCodeGroups_Null()
        {
            FirstMatchCodeGroup cg = new FirstMatchCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));

            cg.ResolveMatchingCodeGroups(null);
        }
예제 #21
0
    // Print the properties of the specified code group to the console.
    private static void PrintCodeGroup(CodeGroup codeGroup)
    {
        // Compare the type of the specified object with the
        // FirstMatchCodeGroup type.
        //<Snippet12>
        if (!codeGroup.GetType().Equals(typeof(FirstMatchCodeGroup)))
        //</Snippet12>
        {
            throw new ArgumentException(
                      "Expected the FirstMatchCodeGroup type.");
        }

        string codeGroupName       = codeGroup.Name;
        string membershipCondition = codeGroup.MembershipCondition.ToString();
        //<Snippet13>
        string permissionSetName = codeGroup.PermissionSetName;
        //</Snippet13>

        //<Snippet14>
        int hashCode = codeGroup.GetHashCode();
        //</Snippet14>

        string mergeLogic = "";

        //<Snippet15>
        if (codeGroup.MergeLogic.Equals("First Match"))
        //</Snippet15>
        {
            mergeLogic = "with first-match merge logic";
        }

        // Retrieve the class path for the FirstMatchCodeGroup.
        //<Snippet16>
        string firstMatchGroupClass = codeGroup.ToString();
        //</Snippet16>

        string attributeString = "";

        // Retrieve the string representation of the FirstMatchCodeGroup's
        // attributes.
        //<Snippet5>
        if (codeGroup.AttributeString != null)
        {
            attributeString = codeGroup.AttributeString;
        }
        //</Snippet5>

        // Write a summary to the console window.
        Console.WriteLine("\n*** " + firstMatchGroupClass + " summary ***");
        Console.Write("A FirstMatchCodeGroup named ");
        Console.Write(codeGroupName + mergeLogic);
        Console.Write(" has been created with hash code(" + hashCode + ").");
        Console.Write("\nThis code group contains a " + membershipCondition);
        Console.Write(" membership condition with the ");
        Console.WriteLine(permissionSetName + " permission set.");

        Console.Write("The code group contains the following policy: ");
        Console.Write(ResolveEvidence(codeGroup));
        Console.Write("\nIt also contains the following attributes: ");
        Console.WriteLine(attributeString);

        int childCount = codeGroup.Children.Count;

        if (childCount > 0)
        {
            Console.Write("There are " + childCount);
            Console.WriteLine(" child elements in the code group.");

            // Iterate through the child code groups to display their names
            // and then remove them from the specified code group.
            for (int i = 0; i < childCount; i++)
            {
                // Retrieve a child code group, which has been cast as a
                // FirstMatchCodeGroup type.
                //<Snippet21>
                FirstMatchCodeGroup childCodeGroup =
                    (FirstMatchCodeGroup)codeGroup.Children[i];
                //</Snippet21>

                Console.Write("Removing the " + childCodeGroup.Name + ".");
                // Remove the child code group.
                //<Snippet17>
                codeGroup.RemoveChild(childCodeGroup);
                //</Snippet17>
            }

            Console.WriteLine();
        }
        else
        {
            Console.WriteLine(" No child code groups were found in this" +
                              " code group.");
        }
    }
예제 #22
0
        public void MergeLogic()
        {
            FirstMatchCodeGroup cg = new FirstMatchCodeGroup(new AllMembershipCondition(), new PolicyStatement(new PermissionSet(PermissionState.None)));

            Assert.AreEqual("First Match", cg.MergeLogic, "MergeLogic");
        }
예제 #23
0
        // Here is the managed portion of the QuickCache code.  It
        // is mainly concerned with detecting whether it is valid
        // for us to use the quick cache, and then calculating the
        // proper mapping of partial evidence to partial mapping.
        //
        // The choice of the partial evidence sets is fairly arbitrary
        // and in this case is tailored to give us meaningful
        // results from default policy.
        //
        // The choice of whether or not we can use the quick cache
        // is far from arbitrary.  There are a couple conditions that must
        // be true for the QuickCache to produce valid result.  These
        // are:
        //
        // * equivalent evidence objects must produce the same
        //   grant set (i.e. it must be independent of time of day,
        //   space on the harddisk, other "external" factors, and
        //   cannot be random).
        //
        // * evidence must be used positively (i.e. if evidence A grants
        //   permission X, then evidence A+B must grant at least permission
        //   X).
        //
        // In particular for our implementation, this means that we
        // limit the classes that can be used by policy to just
        // the ones defined within mscorlib and that there are
        // no Exclusive bits set on any code groups.

        internal static bool CanUseQuickCache(CodeGroup group)
        {
            ArrayList list = new ArrayList();

            list.Add(group);

            for (int i = 0; i < list.Count; ++i)
            {
                group = (CodeGroup)list[i];

                NetCodeGroup        netGroup   = group as NetCodeGroup;
                UnionCodeGroup      unionGroup = group as UnionCodeGroup;
                FirstMatchCodeGroup firstGroup = group as FirstMatchCodeGroup;
                FileCodeGroup       fileGroup  = group as FileCodeGroup;

                if (netGroup != null)
                {
                    if (!TestPolicyStatement(netGroup.PolicyStatement))
                    {
                        return(false);
                    }
                }
                else if (unionGroup != null)
                {
                    if (!TestPolicyStatement(unionGroup.PolicyStatement))
                    {
                        return(false);
                    }
                }
                else if (firstGroup != null)
                {
                    if (!TestPolicyStatement(firstGroup.PolicyStatement))
                    {
                        return(false);
                    }
                }
                else if (fileGroup != null)
                {
                    if (!TestPolicyStatement(fileGroup.PolicyStatement))
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }

                IMembershipCondition cond = group.MembershipCondition;

                if (cond != null && !(cond is IConstantMembershipCondition))
                {
                    return(false);
                }

                IList children = group.Children;

                if (children != null && children.Count > 0)
                {
                    IEnumerator enumerator = children.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        list.Add(enumerator.Current);
                    }
                }
            }

            return(true);
        }
예제 #24
0
 public void Constructor_MembershipConditionNullPolicyStatement()
 {
     FirstMatchCodeGroup cg = new FirstMatchCodeGroup(null, new PolicyStatement(new PermissionSet(PermissionState.None)));
 }