Esempio n. 1
0
        // Code Access Security

        internal void Resolve()
        {
            lock (this) {
                // FIXME: As we (currently) delay the resolution until the first CAS
                // Demand it's too late to evaluate the Minimum permission set as a
                // condition to load the assembly into the AppDomain
                LoadAssemblyPermissions();
                Evidence e = new Evidence(UnprotectedGetEvidence());                   // we need a copy to add PRE
                e.AddHost(new PermissionRequestEvidence(_minimum, _optional, _refuse));
                _granted = SecurityManager.ResolvePolicy(e,
                                                         _minimum, _optional, _refuse, out _denied);
            }
        }
Esempio n. 2
0
        public void Check()
        {
            DomainApplicationMembershipCondition domapp = new DomainApplicationMembershipCondition();
            Evidence e = null;

            Assert.IsFalse(domapp.Check(e), "Check (null)");
            e = new Evidence();
            Assert.IsFalse(domapp.Check(e), "Check (empty)");
            e.AddHost(new Zone(SecurityZone.MyComputer));
            Assert.IsFalse(domapp.Check(e), "Check (zone)");

            // TODO - more (non failing ;) tests
        }
        private PermissionSet GetDefaultMyComputerPolicy(out PermissionSet denied)
        {
            // This function is a crazy little hack that just returns the default MyComputer
            // zone policy.  This is actually useful for detecting what policy an assembly
            // would be granted as long as it's unsigned.  We should add support for
            // signed stuff in later.

            Evidence ev = new Evidence();

            ev.AddHost(new Zone(SecurityZone.MyComputer));

            return(ResolvePolicy(ev, new PermissionSet(false), new PermissionSet(true), null, out denied));
        }
Esempio n. 4
0
        /// <summary>
        ///     Add an object to the host evidence list, ensuring that only one item of evidence of the
        ///     given type exists in the final evidence collection.
        /// </summary>
        /// <typeparam name="T">Type of evidence being added</typeparam>
        /// <param name="evidence">evidence collection to add to</param>
        /// <param name="evidenceObject">object to add to the evidence collection</param>
        /// <exception cref="ArgumentNullException">if <paramref name="evidenceObject" /> is null</exception>
        /// <exception cref="InvalidOperationException">
        ///     if the evidence collection already contains an evidence object of type <typeparamref name="T"/>
        /// </exception>
        public static void AddHostEvidence <T>(this Evidence evidence, T evidenceObject) where T : class
        {
            if (evidenceObject == null)
            {
                throw new ArgumentNullException("evidenceObject");
            }
            if (evidence.GetHostEvidence <T>() != null)
            {
                throw new InvalidOperationException(String.Format(Resources.Culture, Resources.DuplicateEvidence, typeof(T).ToString()));
            }

            evidence.AddHost(evidenceObject);
        }
        private static PermissionSet CreatePermissionSetFromLocation(string configurationFile)
        {
            // Readability note:
            //  Uri is System.Uri
            //  Url is System.Security.Policy.Url

            Uri configUri = new Uri(configurationFile);

            // Build evidence for location of current configuration file
            Evidence evidence = new Evidence();

            evidence.AddHost(new Url(configUri.ToString()));
            if (!configUri.IsFile)
            {
                evidence.AddHost(Site.CreateFromUrl(configUri.ToString()));
            }
            evidence.AddHost(Zone.CreateFromUrl(configUri.ToString()));


            PermissionSet permissionSet = SecurityManager.ResolvePolicy(evidence);

            return(permissionSet);
        }
Esempio n. 6
0
        private AppDomain CreateRemoteDomain()
        {
            var friendlyName = string.Format("{0}:TestExecutor-{1}",
                                             AppDomain.CurrentDomain.FriendlyName,
                                             _assemblyName.Name);
            var domainSetup = new AppDomainSetup();
            var uri         = new Uri(_assemblyName.CodeBase);
            var lastSlash   = uri.OriginalString.LastIndexOf('/');
            var appBase     = uri.OriginalString.Substring(0, lastSlash) + "\\";

            domainSetup.ApplicationBase = appBase;
            domainSetup.ApplicationName = _assemblyName.Name;

            domainSetup.ShadowCopyFiles = "true";
            // Uses CLR's download cache, which is the default location. [29aug09, ml]

            domainSetup.ShadowCopyDirectories = appBase;
            // This might not be good enough since it would not shadow copy subfolders... [02sep09, ml]

            var configFile = appBase + "/web.config";

            if (File.Exists(configFile))
            {
                domainSetup.ConfigurationFile = configFile;
            }
            else
            {
                domainSetup.ConfigurationFile = _assemblyName.CodeBase + ".config";
            }

            var evidence = new Evidence(AppDomain.CurrentDomain.Evidence);

            evidence.AddHost(new Zone(SecurityZone.MyComputer));
            var permissions = new PermissionSet(PermissionState.Unrestricted);

            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.AllFlags));//Execution));
            permissions.AddPermission(new UIPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            permissions.AddPermission(new ReflectionPermission(PermissionState.Unrestricted));

            var appDomain = AppDomain.CreateDomain(friendlyName,
                                                         //AppDomain.CurrentDomain.Evidence,
                                                   null, //evidence,
                                                   domainSetup,
                                                   permissions,
                                                   GetStrongName(Assembly.GetExecutingAssembly()));

            return(appDomain);
        }
    public bool CreateEvidence()
    {
        bool retVal = true;

        try
        {
            // Create empty evidence using the default contructor.
            Evidence ev1 = new Evidence();
            Console.WriteLine("Created empty evidence with the default constructor.");

            // Constructor used to create null host evidence.
            Evidence ev2a = new Evidence(null);
            Console.WriteLine("Created an Evidence object with null host evidence.");

            // Constructor used to create host evidence.
            Url url = new Url("http://www.treyresearch.com");
            Console.WriteLine("Adding host evidence " + url.ToString());
            ev2a.AddHost(url);
            Evidence ev2b = new Evidence(ev2a);
            Console.WriteLine("Copy evidence into new evidence");
            IEnumerator enum1 = ev2b.GetHostEnumerator();
            enum1.MoveNext();
            Console.WriteLine(enum1.Current.ToString());
			
            // Constructor used to create both host and assembly evidence.
            Object [] oa1 = {};
            Site site = new Site("www.wideworldimporters.com");
            Object [] oa2 = { url, site };
            Evidence ev3a = new Evidence(oa1, oa2);
            enum1 = ev3a.GetHostEnumerator();
            IEnumerator enum2 = ev3a.GetAssemblyEnumerator();
            enum2.MoveNext();
            Object obj1 = enum2.Current;
            enum2.MoveNext();
            Console.WriteLine("URL = " + obj1.ToString() + "  Site = " + enum2.Current.ToString());
			
            // Constructor used to create null host and null assembly evidence.
            Evidence ev3b = new Evidence(null, null);
            Console.WriteLine("Create new evidence with null host and assembly evidence");
			
        }
        catch (Exception e)
        {
            Console.WriteLine("Fatal error: {0}", e.ToString());
            return false;
        }

        return retVal;
    }
Esempio n. 8
0
        public void Equals_GetHashCode()
        {
            Evidence e1 = new Evidence();
            Evidence e2 = new Evidence();

            Assert.AreEqual(e1.GetHashCode(), e2.GetHashCode(), "GetHashCode-1");
            Assert.IsTrue(e1.Equals(e2), "e1.Equals(e2)");
            e1.AddAssembly(String.Empty);
            e2.AddAssembly(String.Empty);
            Assert.AreEqual(e1.GetHashCode(), e2.GetHashCode(), "GetHashCode-2");
            e1.AddHost(String.Empty);
            e2.AddHost(String.Empty);
            Assert.AreEqual(e1.GetHashCode(), e2.GetHashCode(), "GetHashCode-3");
            Assert.IsTrue(e2.Equals(e1), "e2.Equals(e1)");
        }
Esempio n. 9
0
        // static members
        public static Evidence CreateEvidenceForUrl(string securityUrl)
        {
            Evidence evidence = new Evidence();

            if ((securityUrl != null) && (securityUrl.Length > 0))
            {
                try
                {
                    Url url = new Url(securityUrl);
                    evidence.AddHost(url);
                }
                catch (ArgumentException)
                {
                }

                try
                {
                    Zone zone = Zone.CreateFromUrl(securityUrl);
                    evidence.AddHost(zone);
                }
                catch (ArgumentException)
                {
                }

                try
                {
                    Site site = Site.CreateFromUrl(securityUrl);
                    evidence.AddHost(site);
                }
                catch (ArgumentException)
                {
                }
            }

            return(evidence);
        }
        internal void InitStore(IsolatedStorageScope scope,
                                Object domain, Object assem, Object app)
        {
            Assembly      callerAssembly;
            PermissionSet psAllowed = null, psDenied = null;
            Evidence      domainEv = null, assemEv = null, appEv = null;

            if (IsApp(scope))
            {
                appEv = new Evidence();
                appEv.AddHost(app);
            }
            else
            {
                assemEv = new Evidence();
                assemEv.AddHost(assem);

                if (IsDomain(scope))
                {
                    domainEv = new Evidence();
                    domainEv.AddHost(domain);
                }
            }

            _InitStore(scope, domainEv, null, assemEv, null, appEv, null);

            // Set the quota based on the caller, not the evidence supplied

            if (!IsRoaming(scope))  // No quota for roaming
            {
                callerAssembly = nGetCaller();

                GetControlEvidencePermission().Assert();
                callerAssembly.nGetGrantSet(out psAllowed, out psDenied);

                if (psAllowed == null)
                {
                    throw new IsolatedStorageException(
                              Environment.GetResourceString(
                                  "IsolatedStorage_AssemblyGrantSet"));
                }
            }

            // This can be called only by trusted assemblies.
            // This quota really does not correspond to the permissions
            // granted for this evidence.
            SetQuota(psAllowed, psDenied);
        }
Esempio n. 11
0
        public void ProvideAppDomainEvidence()
        {
            HostSecurityManager hsm = new HostSecurityManager();

            Assert.IsNull(hsm.ProvideAppDomainEvidence(null), "null");

            Evidence e      = new Evidence();
            Evidence result = hsm.ProvideAppDomainEvidence(e);

            Assert.IsNotNull(result, "empty");
            Assert.AreEqual(0, result.Count, "Count-0");

            e.AddHost(new Zone(SecurityZone.Untrusted));
            result = hsm.ProvideAppDomainEvidence(e);
            Assert.AreEqual(1, result.Count, "Count-1");
        }
Esempio n. 12
0
        private static void CheckPackageSecurity(string package, string location)
        {
            // Ensures that the package location is included in the MyComputer trusted zone.
            Evidence ev   = new Evidence();
            Zone     zone = Zone.CreateFromUrl(location);

            ev.AddHost(zone);

            if (!new ZoneMembershipCondition(SecurityZone.MyComputer).Check(ev))
            {
                throw new SecurityException(String.Format(
                                                System.Globalization.CultureInfo.CurrentCulture,
                                                Properties.Resources.RecipeManager_PackageNotTrusted,
                                                package, location));
            }
        }
Esempio n. 13
0
        public void ProvideAssemblyEvidence_NullAssembly()
        {
            HostSecurityManager hsm = new HostSecurityManager();

            Evidence result = hsm.ProvideAssemblyEvidence(null, null);

            Assert.IsNull(result, "null");

            Evidence e = new Evidence();

            result = hsm.ProvideAssemblyEvidence(null, e);
            Assert.AreEqual(0, result.Count, "Count-empty");

            e.AddHost(new Zone(SecurityZone.Untrusted));
            result = hsm.ProvideAssemblyEvidence(null, e);
            Assert.AreEqual(1, result.Count, "Count-1");
        }
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001")] //Assembly.LoadFrom
            public Assembly AssemblyResolveEventHandler(object sender, ResolveEventArgs args)
            {
                string location;

                if (locations.TryGetValue(args.Name, out location))
                {
#if TESTBUILD_CLR20
                    Evidence evidence = new Evidence();
                    evidence.AddHost(new Zone(SecurityZone.MyComputer));
                    return(Assembly.LoadFrom(location, evidence));
#endif
#if TESTBUILD_CLR40
                    return(Assembly.LoadFrom(location));
#endif
                }
                return(null);    // Should I do log here?
            }
Esempio n. 15
0
        internal static PermissionSet AddPermissionForUri(PermissionSet originalPermSet, Uri srcUri)
        {
            PermissionSet result = originalPermSet;

            if (srcUri != null)
            {
                Evidence evidence = new Evidence();
                evidence.AddHost(new Url(BindUriHelper.UriToString(srcUri)));
                IMembershipCondition membershipCondition = new UrlMembershipCondition(BindUriHelper.UriToString(srcUri));
                CodeGroup            codeGroup           = srcUri.IsFile ? new FileCodeGroup(membershipCondition, FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery) : new NetCodeGroup(membershipCondition);
                PolicyStatement      policyStatement     = codeGroup.Resolve(evidence);
                if (!policyStatement.PermissionSet.IsEmpty())
                {
                    result = originalPermSet.Union(policyStatement.PermissionSet);
                }
            }
            return(result);
        }
Esempio n. 16
0
        public void Check()
        {
            PublisherMembershipCondition pmc = new PublisherMembershipCondition(x509);
            Publisher p = new Publisher(x509);

            Evidence e = null;

            Assert.IsFalse(pmc.Check(e), "Check (null)");
            e = new Evidence();
            Assert.IsFalse(pmc.Check(e), "Check (empty)");
            e.AddHost(new Zone(SecurityZone.MyComputer));
            Assert.IsFalse(pmc.Check(e), "Check (zone)");
            e.AddAssembly(p);
            Assert.IsFalse(pmc.Check(e), "Check (x509-assembly)");

            e = new Evidence();
            e.AddHost(p);
            Assert.IsTrue(pmc.Check(e), "Check (x509-host)");
        }
Esempio n. 17
0
        public void RunUserCode(String domainName)
        {
            //
            // Setup AppBase and Configuration file
            //
            IDictionary properties = new Hashtable();

            properties.Add(AppDomainFlags.ApplicationBase, "c:\\temp");
            properties.Add(AppDomainFlags.ConfigurationFile, "c:\\temp\\myapp.config");
            Console.WriteLine("Domain properties successfully initialized...");

            //
            // Create sample evidence - this example sets the domain level evidence
            // to the url of a web site
            //
            Evidence e = new Evidence();

            e.AddHost(new Url("http://www.somesite.com"));
            Console.WriteLine("Domain level evidence successfully created...");

            //
            // Create the domain.
            //
            AppDomain ad = AppDomain.CreateDomain(domainName,
                                                  e,
                                                  null,
                                                  properties);

            //
            // Define a sample domain specific code access security policy
            //
            ad.SetAppDomainPolicy(DefineHostPolicy());

            Console.WriteLine("Domain " + domainName + " successfully created...");

            //
            // unload the domain
            //
            Console.WriteLine("Domain " + domainName + " unloaded...");
            Console.WriteLine("Done.");
            AppDomain.Unload(ad);
        }
Esempio n. 18
0
    public static void Main()
    {
        // <Snippet1>
        // Set up the AppDomainSetup
        AppDomainSetup setup = new AppDomainSetup();

        setup.ApplicationBase   = "(some directory)";
        setup.ConfigurationFile = "(some file)";

        // Set up the Evidence
        Evidence baseEvidence = AppDomain.CurrentDomain.Evidence;
        Evidence evidence     = new Evidence(baseEvidence);

        evidence.AddAssembly("(some assembly)");
        evidence.AddHost("(some host)");

        // Create the AppDomain
        AppDomain newDomain = AppDomain.CreateDomain("newDomain", evidence, setup);
        // </Snippet1>
    }
        internal static PermissionSet AddPermissionForUri(PermissionSet originalPermSet, Uri srcUri)
        {
            PermissionSet newPermSet = originalPermSet;

            if (srcUri != null)
            {
                Evidence evidence = new Evidence();
                evidence.AddHost(new Url(BindUriHelper.UriToString(srcUri))); // important: the parameter must be a UrL object not a UrI object
                IMembershipCondition membership = new UrlMembershipCondition(BindUriHelper.UriToString(srcUri));
                CodeGroup            group      = (srcUri.IsFile) ?
                                                  (CodeGroup) new FileCodeGroup(membership, FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery)
                    :(CodeGroup) new NetCodeGroup(membership);
                PolicyStatement policy = group.Resolve(evidence);
                if (!policy.PermissionSet.IsEmpty())
                {
                    newPermSet = originalPermSet.Union(policy.PermissionSet);
                }
            }
            return(newPermSet);
        }
Esempio n. 20
0
        public void Create_PartialTrust()
        {
            // basic check of running a host in partial trust
            AppDomainSetup info = new AppDomainSetup();

            info.ApplicationBase = TestHelpers.BinDirectory;
            info.ApplicationName = "Test";
            Evidence evidence = new Evidence();

            evidence.AddHost(new Zone(SecurityZone.Internet));
            System.Security.PermissionSet permSet = SecurityManager.GetStandardSandbox(evidence);
            AppDomain newDomain = AppDomain.CreateDomain("test", evidence, info, permSet, null);

            ScriptRuntime runtime = CreateRemoteRuntime(newDomain);
            ScriptScope   scope   = runtime.CreateScope();

            scope.SetVariable("test", "value");

            AppDomain.Unload(newDomain);
        }
Esempio n. 21
0
        public void GetStore_DomainScope_Evidences()
        {
            IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly;

            Evidence de = new Evidence();

            de.AddHost(new Zone(SecurityZone.Internet));
            Evidence ae = new Evidence();

            ae.AddHost(new Zone(SecurityZone.Intranet));
            IsolatedStorageFile isf = IsolatedStorageFile.GetStore(scope, de, typeof(Zone), ae, typeof(Zone));

            // Maximum size for Internet isn't (by default) Int64.MaxValue
            Assert.AreEqual(scope, isf.Scope, "Scope");
            Assert.IsTrue((isf.AssemblyIdentity is Zone), "AssemblyIdentity");
            Assert.IsTrue((isf.AssemblyIdentity.ToString().IndexOf("Intranet") > 0), "Zone - Assembly");
            Assert.IsTrue((isf.DomainIdentity is Zone), "DomainIdentity");
            Assert.IsTrue((isf.DomainIdentity.ToString().IndexOf("Internet") > 0), isf.DomainIdentity.ToString());                 //"Zone - Domain");
            Assert.IsTrue((isf.CurrentSize >= 0), "CurrentSize");
        }
Esempio n. 22
0
        public void Check()
        {
            HashMembershipCondition hash = new HashMembershipCondition(md5, digestMd5);
            Evidence e = null;

            Assert.IsFalse(hash.Check(e), "Check (null)");
            e = new Evidence();
            Assert.IsFalse(hash.Check(e), "Check (empty)");
            e.AddHost(new Zone(SecurityZone.MyComputer));
            Assert.IsFalse(hash.Check(e), "Check (zone)");
            e.AddAssembly(hashEvidence);
            Assert.IsFalse(hash.Check(e), "Check (hash-assembly)");

            e = new Evidence();
            e.AddHost(hashEvidence);
            Assert.IsTrue(hash.Check(e), "Check (MD5-host)");

            hash = new HashMembershipCondition(sha1, digestSha1);
            Assert.IsTrue(hash.Check(e), "Check (SHA1-host)");
        }
Esempio n. 23
0
        public void Count()
        {
            object[] hostarray = { "host-1", "host-2", "host-3", "host-4" };
            object[] asmbarray = { "asmb-1", "asmb-2", "asmb-3", "asmb-4" };
            Evidence evidence  = new Evidence(hostarray, asmbarray);

            Assert.AreEqual(evidence.Count, 8);

            for (int i = 0; i < 100; i++)
            {
                if (0 == i % 2)
                {
                    evidence.AddHost(String.Format("host-{0}", i + 5));
                }
                else
                {
                    evidence.AddAssembly(String.Format("asmb-{0}", i + 5));
                }
                Assert.AreEqual(evidence.Count, 9 + i);
            }
        }
Esempio n. 24
0
        protected static ObjectHandle CreateInstanceHelper(AppDomainSetup adSetup)
        {
            if (adSetup == null)
            {
                throw new ArgumentNullException("adSetup");
            }

            if (adSetup.ActivationArguments == null)
            {
                string msg = Locale.GetText("{0} is missing it's {1} property");
                throw new ArgumentException(String.Format(msg, "AppDomainSetup", "ActivationArguments"), "adSetup");
            }

            HostSecurityManager hsm = null;

            if (AppDomain.CurrentDomain.DomainManager != null)
            {
                hsm = AppDomain.CurrentDomain.DomainManager.HostSecurityManager;
            }
            else
            {
                hsm = new HostSecurityManager(); // default
            }
            Evidence applicationEvidence = new Evidence();

            applicationEvidence.AddHost(adSetup.ActivationArguments);
            TrustManagerContext context = new TrustManagerContext();
            ApplicationTrust    trust   = hsm.DetermineApplicationTrust(applicationEvidence, null, context);

            if (!trust.IsApplicationTrustedToRun)
            {
                string msg = Locale.GetText("Current policy doesn't allow execution of addin.");
                throw new PolicyException(msg);
            }

            // FIXME: we're missing the information from the manifest
            AppDomain ad = AppDomain.CreateDomain("friendlyName", null, adSetup);

            return(ad.CreateInstance("assemblyName", "typeName", null));
        }
Esempio n. 25
0
        private void TestSerializationOnPartialTrust()
        {
            var appDomainSetUp = new AppDomainSetup()
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };
            var evidence = new Evidence();

#if MONO || NETFX_35
#pragma warning disable 0612
            // TODO: patching
            // currently, Mono does not declare AddHostEvidence
            evidence.AddHost(new Zone(SecurityZone.Internet));
#pragma warning restore 0612
            var permisions = GetDefaultInternetZoneSandbox();
#else
            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
            var permisions = SecurityManager.GetStandardSandbox(evidence);
#endif
            AppDomain workerDomain = AppDomain.CreateDomain("PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName(this.GetType()));
            try
            {
                var innerMessage = Guid.NewGuid().ToString();
                var message      = Guid.NewGuid().ToString();
                workerDomain.SetData("MsgPack.GenericExceptionTester.InnerMessage", innerMessage);
                workerDomain.SetData("MsgPack.GenericExceptionTester.Message", message);
                workerDomain.SetData("MsgPack.GenericExceptionTester.Proxy", this);
                workerDomain.DoCallBack(TestSerializationOnPartialTrustCore);

                var target = workerDomain.GetData("MsgPack.GenericExceptionTester.Target") as T;
                Assert.That(target, Is.Not.Null);
                Assert.That(target.Message, Is.EqualTo(target.Message));
                Assert.That(target.InnerException, Is.Not.Null.And.TypeOf(typeof(Exception)));
                Assert.That(target.InnerException.Message, Is.EqualTo(target.InnerException.Message));
            }
            finally
            {
                AppDomain.Unload(workerDomain);
            }
        }
Esempio n. 26
0
        private void ResolveEvidenceHost(SecurityZone zone, bool unrestricted, bool empty)
        {
            string   prefix = zone.ToString() + "-";
            Evidence e      = new Evidence();

            e.AddHost(new Zone(zone));
            PermissionSet ps = SecurityManager.ResolvePolicy(e);

            // as 2.0 use Unrestricted for Identity permissions they have no need to be
            // kept in resolved permission set
            Assert.IsTrue((unrestricted || (ps.Count > 0)), prefix + "Count");
            Assert.AreEqual(empty, ps.IsEmpty(), prefix + "IsEmpty");
            Assert.AreEqual(unrestricted, ps.IsUnrestricted(), prefix + "IsUnrestricted");
            if (unrestricted)
            {
                Assert.IsNull(ps.GetPermission(typeof(ZoneIdentityPermission)), prefix + "GetPermission(ZoneIdentityPermission)");
            }
            else
            {
                Assert.IsNotNull(ps.GetPermission(typeof(ZoneIdentityPermission)), prefix + "GetPermission(ZoneIdentityPermission)");
            }
        }
Esempio n. 27
0
        public void AddHost()
        {
            Evidence evidence = new Evidence();

            object[] comparray = new object[100];
            string   obj;

            for (int i = 0; i < 100; i++)
            {
                obj          = String.Format("asmb-{0}", i + 1);
                comparray[i] = obj;
                evidence.AddHost(obj);
                Assert.AreEqual(evidence.Count, i + 1);
            }

            int index = 0;

            foreach (object compobj in evidence)
            {
                Assert.AreEqual(comparray[index++], compobj, "Comparison object does not equal evidence host object");
            }
        }
Esempio n. 28
0
        private void Resolve_Zone(PolicyLevel level, SecurityZone z, PolicyStatementAttribute attr, bool unrestricted, int count)
        {
            string   prefix = z.ToString() + "-" + attr.ToString() + "-";
            Evidence e      = new Evidence();

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

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

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

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

                case PolicyStatementAttribute.All:
                    Assert.AreEqual("Exclusive LevelFinal", result.AttributeString, prefix + "AttributeString");
                    break;
                }
            }
            else
            {
                Assert.AreEqual(PolicyStatementAttribute.Nothing, result.Attributes, prefix + "Attributes");
                Assert.AreEqual(String.Empty, result.AttributeString, prefix + "AttributeString");
            }
            Assert.AreEqual(unrestricted, result.PermissionSet.IsUnrestricted(), prefix + "IsUnrestricted");
            Assert.AreEqual(count, result.PermissionSet.Count, prefix + "Count");
        }
Esempio n. 29
0
        private void LoadAssemblyToSeppareteDomain(FileInfo info)
        {
            var domaininfo = new AppDomainSetup();

            domaininfo.ApplicationBase = domaininfo.PrivateBinPath = info.Directory.FullName;


            //var pset = new PermissionSet(PermissionState.None);
            //pset.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            //pset.AddPermission(new UIPermission(PermissionState.Unrestricted));

            var evidence = new Evidence(AppDomain.CurrentDomain.Evidence);

            evidence.AddAssembly("(some assembly)");
            evidence.AddHost(new Zone(SecurityZone.MyComputer));
            var domain = AppDomain.CreateDomain(
                "MyDomain",
                evidence,
                domaininfo
                );


            // Write the application domain information to the console.
            //Console.WriteLine("Host domain: " + AppDomain.CurrentDomain.FriendlyName);
            //Console.WriteLine("child domain: " + domain.FriendlyName);
            //Console.WriteLine();
            //Console.WriteLine("Application base is: " + domain.SetupInformation.ApplicationBase);
            //Console.WriteLine("Configuration file is: " + domain.SetupInformation.ConfigurationFile);

            // Unloads the application domain.
            //AppDomain.Unload(domain);
            var assemblyRef = AssemblyName.GetAssemblyName(info.FullName);

            domain.Load(assemblyRef);

            EventSpyCore.Domains.Add(domain);
        }
        public void TestEqualsPartialTrust()
        {
            var appDomainSetUp = new AppDomainSetup()
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };
            var evidence = new Evidence();

#if MONO || NETFX_35
#pragma warning disable 0612
            // TODO: patching
            // currently, Mono does not declare AddHostEvidence
            evidence.AddHost(new Zone(SecurityZone.Internet));
#pragma warning restore 0612
            var permisions = GetDefaultInternetZoneSandbox();
#else
            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
            var permisions = SecurityManager.GetStandardSandbox(evidence);
#endif // if MONO || NETFX_35
            AppDomain workerDomain = AppDomain.CreateDomain("PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName(this.GetType()), GetStrongName(typeof(Assert)));
            try
            {
                workerDomain.DoCallBack(TestEqualsWorker);

#if !MONO
                // P/Invoke is not disabled on Mono even if in the InternetZone.
                Assert.That(( bool )workerDomain.GetData("MessagePackString.IsFastEqualsDisabled"), Is.True);
#endif // if !MONO
                Console.WriteLine("TestEqualsPartialTrust");
                ShowResult(workerDomain.GetData("TestEqualsWorker.Performance") as Tuple <double, double, double, double>);
            }
            finally
            {
                AppDomain.Unload(workerDomain);
            }
        }