AddHost() private method

private AddHost ( object id ) : void
id object
return void
Exemplo n.º 1
0
        /// <summary>
        /// Construct an application domain for running a test package
        /// </summary>
        /// <param name="package">The TestPackage to be run</param>
        public AppDomain CreateDomain( TestPackage package )
        {
            AppDomainSetup setup = CreateAppDomainSetup(package);

            string domainName = "test-domain-" + package.Name;
            // Setup the Evidence
            Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
            if (evidence.Count == 0)
            {
                Zone zone = new Zone(SecurityZone.MyComputer);
                evidence.AddHost(zone);
                Assembly assembly = Assembly.GetExecutingAssembly();
                Url url = new Url(assembly.CodeBase);
                evidence.AddHost(url);
                Hash hash = new Hash(assembly);
                evidence.AddHost(hash);
            }

            log.Info("Creating AppDomain " + domainName);

            AppDomain runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup);

            // Set PrincipalPolicy for the domain if called for in the settings
            if (_settingsService != null && _settingsService.GetSetting("Options.TestLoader.SetPrincipalPolicy", false))
            {
                runnerDomain.SetPrincipalPolicy(_settingsService.GetSetting(
                    "Options.TestLoader.PrincipalPolicy", 
                    PrincipalPolicy.UnauthenticatedPrincipal));
            }

            return runnerDomain;
        }
		public void Check ()
		{
			ApplicationDirectoryMembershipCondition ad = new ApplicationDirectoryMembershipCondition ();
			Evidence e = null;
			Assert.IsFalse (ad.Check (e), "Check (null)");
			e = new Evidence ();
			Assert.IsFalse (ad.Check (e), "Check (empty)");
			e.AddHost (new Zone (SecurityZone.MyComputer));
			Assert.IsFalse (ad.Check (e), "Check (zone)");

			string codebase = Assembly.GetExecutingAssembly ().CodeBase;
			Url u = new Url (codebase);
			ApplicationDirectory adir = new ApplicationDirectory (codebase);

			e.AddHost (u);
			Assert.IsFalse (ad.Check (e), "Check (url-host)"); // not enough
			e.AddAssembly (adir);
			Assert.IsFalse (ad.Check (e), "Check (url-host+adir-assembly)");

			e = new Evidence ();
			e.AddHost (adir);
			Assert.IsFalse (ad.Check (e), "Check (adir-host)"); // not enough
			e.AddAssembly (u);
			Assert.IsFalse (ad.Check (e), "Check (url-assembly+adir-host)");

			e = new Evidence ();
			e.AddHost (u);
			e.AddHost (adir);
			Assert.IsTrue (ad.Check (e), "Check (url+adir host)"); // both!!
		}
Exemplo n.º 3
0
		public static Evidence CreateEvidenceForUrl (string securityUrl)
		{
			Evidence e = new Evidence ();

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

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

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

			return e;
		}
Exemplo n.º 4
0
        /// <summary>
        /// Construct an application domain for running a test package
        /// </summary>
        /// <param name="package">The TestPackage to be run</param>
        public AppDomain CreateDomain( TestPackage package )
        {
            AppDomainSetup setup = CreateAppDomainSetup(package);

            string domainName = "test-domain-" + package.Name;
            // Setup the Evidence
            Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
            if (evidence.Count == 0)
            {
                Zone zone = new Zone(SecurityZone.MyComputer);
                evidence.AddHost(zone);
                Assembly assembly = Assembly.GetExecutingAssembly();
                Url url = new Url(assembly.CodeBase);
                evidence.AddHost(url);
                Hash hash = new Hash(assembly);
                evidence.AddHost(hash);
            }

            log.Info("Creating AppDomain " + domainName);

            AppDomain runnerDomain;
            
            // TODO: Find an approach that works across all platforms
          
            //// TODO: Try to eliminate this test. Currently, running on
            //// Linux with the permission set specified causes an
            //// unexplained crash when unloading the domain.
            //if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            //{
            //    PermissionSet permissionSet = new PermissionSet( PermissionState.Unrestricted );	
            //    runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup, permissionSet, null);
            //}
            //else
                runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup);
            
            // Set PrincipalPolicy for the domain if called for in the settings
                if (ServiceContext.UserSettings.GetSetting("Options.TestLoader.SetPrincipalPolicy", false))
                    runnerDomain.SetPrincipalPolicy((PrincipalPolicy)ServiceContext.UserSettings.GetSetting(
                    "Options.TestLoader.PrincipalPolicy", PrincipalPolicy.UnauthenticatedPrincipal));

            //// HACK: Only pass down our AddinRegistry one level so that tests of NUnit
            //// itself start without any addins defined.
            //if ( !IsTestDomain( AppDomain.CurrentDomain ) )
            //    runnerDomain.SetData("AddinRegistry", Services.AddinRegistry);

            //// Inject DomainInitializer into the remote domain - there are other
            //// approaches, but this works for all CLR versions.
            //DomainInitializer initializer = DomainInitializer.CreateInstance(runnerDomain);

            //// HACK: Under nunit-console, direct use of the enum fails
            //int traceLevel = IsTestDomain(AppDomain.CurrentDomain)
            //    ? (int)InternalTraceLevel.Off : (int)InternalTrace.Level;

            //initializer.InitializeDomain(traceLevel);

            return runnerDomain;
        }
 public static Evidence CreateEvidenceForUrl(string securityUrl) {
     Evidence evidence = new Evidence();
     if (securityUrl != null && securityUrl.Length > 0) {
         evidence.AddHost(new Url(securityUrl));
         evidence.AddHost(Zone.CreateFromUrl(securityUrl));
         Uri uri = new Uri(securityUrl, UriKind.RelativeOrAbsolute);
         if (uri.IsAbsoluteUri && !uri.IsFile) {
             evidence.AddHost(Site.CreateFromUrl(securityUrl));
         }
     }
     return evidence;
 }
Exemplo n.º 6
0
		public void Check ()
		{
			GacMembershipCondition gac = new GacMembershipCondition ();
			Evidence e = null;
			Assert.IsFalse (gac.Check (e), "Check (null)");
			e = new Evidence ();
			Assert.IsFalse (gac.Check (e), "Check (empty)");
			e.AddHost (new Zone (SecurityZone.MyComputer));
			Assert.IsFalse (gac.Check (e), "Check (zone)");
			GacInstalled g = new GacInstalled ();
			e.AddAssembly (g);
			Assert.IsFalse (gac.Check (e), "Check (gac-assembly)");
			e.AddHost (g);
			Assert.IsTrue (gac.Check (e), "Check (gac-host)");
		}
		public void Check ()
		{
			AllMembershipCondition all = new AllMembershipCondition ();
			Evidence e = null;
			Assert.IsTrue (all.Check (e), "Check (null)");
			e = new Evidence ();
			Assert.IsTrue (all.Check (e), "Check (empty)");
			e.AddHost (new Zone (SecurityZone.MyComputer));
			Assert.IsTrue (all.Check (e), "Check (zone)");
			Url u = new Url ("http://www.go-mono.com/");
			e.AddAssembly (u);
			Assert.IsTrue (all.Check (e), "Check (all-assembly)");
			Site s = new Site ("www.go-mono.com");
			e.AddHost (s);
			Assert.IsTrue (all.Check (e), "Check (all-host)");
		}
Exemplo n.º 8
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);
		}
		public void Check ()
		{
			ApplicationMembershipCondition app = new ApplicationMembershipCondition ();
			Evidence e = null;
			Assert.IsFalse (app.Check (e), "Check (null)");
			e = new Evidence ();
			Assert.IsFalse (app.Check (e), "Check (empty)");
			e.AddHost (new Zone (SecurityZone.MyComputer));
			Assert.IsFalse (app.Check (e), "Check (zone)");

			// TODO - more (non failing ;) tests
		}
		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");
		}
Exemplo n.º 11
0
        static ScriptCompiler()
        {
            cParams = new CompilerParameters();
            cParams.GenerateExecutable = false;
            cParams.GenerateInMemory = false;
            cParams.IncludeDebugInformation = false;
            //cParams.OutputAssembly=ScriptOutputPath;
            cParams.ReferencedAssemblies.Add(System.IO.Path.Combine(Program.ExecutableDirectory, "fomm.Scripting.dll"));
            cParams.ReferencedAssemblies.Add("System.dll");
            cParams.ReferencedAssemblies.Add("System.Drawing.dll");
            cParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cParams.ReferencedAssemblies.Add("System.Xml.dll");

            evidence = new Evidence();
            evidence.AddHost(new Zone(System.Security.SecurityZone.Internet));
        }
Exemplo n.º 12
0
        internal Evidence ShallowCopy()
        {
            Evidence evidence = new Evidence();

            IEnumerator enumerator;

            enumerator = this.GetHostEnumerator();

            while (enumerator.MoveNext())
            {
                evidence.AddHost(enumerator.Current);
            }

            enumerator = this.GetAssemblyEnumerator();

            while (enumerator.MoveNext())
            {
                evidence.AddAssembly(enumerator.Current);
            }

            return(evidence);
        }
Exemplo n.º 13
0
		private static Evidence GetDefaultDomainIdentity()
		{
			Evidence evidence = new Evidence();
			bool zoneEvidence = false;
			IEnumerator hostEnumerator = AppDomain.CurrentDomain.Evidence.GetHostEnumerator();
			while (hostEnumerator.MoveNext())
			{
				if (hostEnumerator.Current is Zone)
					zoneEvidence = true;
				evidence.AddHost(hostEnumerator.Current);
			}
			hostEnumerator = AppDomain.CurrentDomain.Evidence.GetAssemblyEnumerator();
			while (hostEnumerator.MoveNext())
			{
				evidence.AddAssembly(hostEnumerator.Current);
			}
			if (!zoneEvidence)
				evidence.AddHost(new Zone(SecurityZone.MyComputer));
			return evidence;
		}
Exemplo n.º 14
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);
			}
		}
Exemplo n.º 15
0
        static internal Evidence GetDefaultHostEvidence(Assembly a)
        {
            Evidence e     = new Evidence();
            string   aname = a.EscapedCodeBase;

            // by default all assembly have the Zone, Url and Hash evidences
            e.AddHost(Zone.CreateFromUrl(aname));
            e.AddHost(new Url(aname));
            e.AddHost(new Hash(a));

            // non local files (e.g. http://) also get a Site evidence
            if (String.Compare("FILE://", 0, aname, 0, 7, true, CultureInfo.InvariantCulture) != 0)
            {
                e.AddHost(Site.CreateFromUrl(aname));
            }

            // strongnamed assemblies gets a StrongName evidence
            AssemblyName an = a.GetName();

            byte[] pk = an.GetPublicKey();
            if ((pk != null) && (pk.Length > 0))
            {
                StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(pk);
                e.AddHost(new StrongName(blob, an.Name, an.Version));
            }

            // Authenticode(r) signed assemblies get a Publisher evidence
            if (IsAuthenticodePresent(a))
            {
                // Note: The certificate is part of the evidences even if it is not trusted!
                // so we can't call X509Certificate.CreateFromSignedFile
                AuthenticodeDeformatter ad = new AuthenticodeDeformatter(a.Location);
                if (ad.SigningCertificate != null)
                {
                    X509Certificate x509 = new X509Certificate(ad.SigningCertificate.RawData);
                    if (x509.GetHashCode() != 0)
                    {
                        e.AddHost(new Publisher(x509));
                    }
                }
            }
            // assemblies loaded from the GAC also get a Gac evidence (new in Fx 2.0)
            if (a.GlobalAssemblyCache)
            {
                e.AddHost(new GacInstalled());
            }

            // the current HostSecurityManager may add/remove some evidence
            AppDomainManager dommgr = AppDomain.CurrentDomain.DomainManager;

            if (dommgr != null)
            {
                if ((dommgr.HostSecurityManager.Flags & HostSecurityManagerOptions.HostAssemblyEvidence) ==
                    HostSecurityManagerOptions.HostAssemblyEvidence)
                {
                    e = dommgr.HostSecurityManager.ProvideAssemblyEvidence(a, e);
                }
            }

            return(e);
        }
Exemplo n.º 16
0
        public void CompilePlugins(PermissionSet pluginSandboxPermissions, List<String> ignoredPluginClassNames = null) {
            try {

                if (File.Exists(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml")) == true) {
                    WritePluginConsole("Loading plugin cache..");

                    try {
                        this.PluginCache = XDocument.Load(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml")).Root.FromXElement<PluginCache>();
                    }
                    catch (Exception e) {
                        WritePluginConsole("Error loading plugin cache: {0}", e.Message);
                    }
                }

                // Recover from exceptions or logic errors if the document parsed correctly, but didn't deserialize correctly.
                if (this.PluginCache == null) {
                    this.PluginCache = new PluginCache();
                }

                // Make sure we ignore any plugins passed in. These won't even be loaded again.
                if (ignoredPluginClassNames != null) {
                    IgnoredPluginClassNames = ignoredPluginClassNames;
                }

                // Clear out all invocations if this is a reload.
                Invocations.Clear();

                WritePluginConsole("Preparing plugins directory..");
                PreparePluginsDirectory();

                WritePluginConsole("Moving legacy plugins..");
                MoveLegacyPlugins();

                WritePluginConsole("Creating compiler..");
                // CodeDomProvider pluginsCodeDomProvider = CodeDomProvider.CreateProvider("CSharp");
                var providerOptions = new Dictionary<String, String>();
                providerOptions.Add("CompilerVersion", "v3.5");
                CodeDomProvider pluginsCodeDomProvider = new CSharpCodeProvider(providerOptions);

                WritePluginConsole("Configuring compiler..");
                CompilerParameters parameters = GenerateCompilerParameters();
                // AppDomainSetup domainSetup = new AppDomainSetup() { ApplicationBase = this.PluginBaseDirectory };
                // Start of XpKillers mono workaround

                AppDomainSetup domainSetup = null;
                Type t = Type.GetType("Mono.Runtime");
                if (t != null) {
                    //Console.WriteLine("You are running with the Mono VM");
                    WritePluginConsole("Running with Mono VM..");
                    //AppDomain.CurrentDomain.BaseDirectory
                    domainSetup = new AppDomainSetup() {
                        ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
                    };
                    domainSetup.PrivateBinPath = PluginBaseDirectory;
                }
                else {
                    // Console.WriteLine("You are running something else (native .Net)");
                    WritePluginConsole("Running with native .Net..");
                    domainSetup = new AppDomainSetup() {
                        ApplicationBase = PluginBaseDirectory
                    };
                }
                // Workaround end

                WritePluginConsole("Building sandbox..");
                var hostEvidence = new Evidence();
                hostEvidence.AddHost(new Zone(SecurityZone.MyComputer));

                AppDomainSandbox = AppDomain.CreateDomain(ProconClient.HostName + ProconClient.Port + "Engine", hostEvidence, domainSetup, pluginSandboxPermissions);

                WritePluginConsole("Configuring sandbox..");
                // create the factory class in the secondary app-domain
                PluginFactory = (CPRoConPluginLoaderFactory) AppDomainSandbox.CreateInstance("PRoCon.Core", "PRoCon.Core.Plugin.CPRoConPluginLoaderFactory").Unwrap();
                PluginCallbacks = new CPRoConPluginCallbacks(ProconClient.ExecuteCommand, ProconClient.GetAccountPrivileges, ProconClient.GetVariable, ProconClient.GetSvVariable, ProconClient.GetMapDefines, ProconClient.TryGetLocalized, RegisterCommand, UnregisterCommand, GetRegisteredCommands, ProconClient.GetWeaponDefines, ProconClient.GetSpecializationDefines, ProconClient.Layer.GetLoggedInAccounts, RegisterPluginEvents);

                WritePluginConsole("Compiling and loading plugins..");


                var pluginsDirectoryInfo = new DirectoryInfo(PluginBaseDirectory);

                foreach (FileInfo pluginFile in pluginsDirectoryInfo.GetFiles("*.cs")) {
                    string className = Regex.Replace(pluginFile.Name, "\\.cs$", "");

                    if (IgnoredPluginClassNames.Contains(className) == false) {
                        CompilePlugin(pluginFile, className, pluginsCodeDomProvider, parameters);

                        LoadPlugin(className, PluginFactory, pluginSandboxPermissions.IsUnrestricted());
                    }
                    else {
                        WritePluginConsole("Compiling {0}... ^1^bIgnored", className);
                    }
                }

                XDocument pluginCacheDocument = new XDocument(this.PluginCache.ToXElement());

                pluginCacheDocument.Save(Path.Combine(this.PluginBaseDirectory, "PluginCache.xml"));

                pluginsCodeDomProvider.Dispose();
            }
            catch (Exception e) {
                WritePluginConsole(e.Message);
            }
        }
 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;
 } 
Exemplo n.º 18
0
		private Evidence CreateHostEvidence (object o)
		{
			Evidence e = new Evidence ();
			e.AddHost (o);
			return e;
		}
		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");
		}
Exemplo n.º 20
0
		public void CreateDomain_StringEvidenceAppDomainSetup ()
		{
			Evidence e = new Evidence ();
			AppDomainSetup info = new AppDomainSetup ();
			info.ApplicationName = "ApplicationName";

			ad = AppDomain.CreateDomain ("CreateDomain_StringEvidenceAppDomainSetup", e, info);
			Assert.IsNotNull (ad.Evidence, "Evidence");
			Assert.AreEqual (0, ad.Evidence.Count, "Evidence.Count");
			Assert.IsNotNull (ad.SetupInformation, "SetupInformation");
			Assert.AreEqual ("ApplicationName", ad.SetupInformation.ApplicationName);

			e.AddHost (new Zone (SecurityZone.MyComputer));
			Assert.AreEqual (0, ad.Evidence.Count, "Evidence.Count");
			// evidence isn't copied but referenced
		}
Exemplo n.º 21
0
		static internal Evidence GetDefaultHostEvidence (Assembly a) 
		{
			Evidence e = new Evidence ();
			string aname = a.EscapedCodeBase;

			// by default all assembly have the Zone, Url and Hash evidences
			e.AddHost (Zone.CreateFromUrl (aname));
			e.AddHost (new Url (aname));
			e.AddHost (new Hash (a));

			// non local files (e.g. http://) also get a Site evidence
			if (String.Compare ("FILE://", 0, aname, 0, 7, true, CultureInfo.InvariantCulture) != 0) {
				e.AddHost (Site.CreateFromUrl (aname));
			}

			// strongnamed assemblies gets a StrongName evidence
			AssemblyName an = a.GetName ();
			byte[] pk = an.GetPublicKey ();
			if ((pk != null) && (pk.Length > 0)) {
				StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob (pk);
				e.AddHost (new StrongName (blob, an.Name, an.Version));
			}

			// Authenticode(r) signed assemblies get a Publisher evidence
			if (IsAuthenticodePresent (a)) {
				// Note: The certificate is part of the evidences even if it is not trusted!
				// so we can't call X509Certificate.CreateFromSignedFile
				AuthenticodeDeformatter ad = new AuthenticodeDeformatter (a.Location);
				if (ad.SigningCertificate != null) {
					X509Certificate x509 = new X509Certificate (ad.SigningCertificate.RawData);
					if (x509.GetHashCode () != 0) {
						e.AddHost (new Publisher (x509));
					}
				}
			}
			// assemblies loaded from the GAC also get a Gac evidence (new in Fx 2.0)
			if (a.GlobalAssemblyCache) {
				e.AddHost (new GacInstalled ());
			}

			// the current HostSecurityManager may add/remove some evidence
			AppDomainManager dommgr = AppDomain.CurrentDomain.DomainManager;
			if (dommgr != null) {
				if ((dommgr.HostSecurityManager.Flags & HostSecurityManagerOptions.HostAssemblyEvidence) ==
					HostSecurityManagerOptions.HostAssemblyEvidence) {
					e = dommgr.HostSecurityManager.ProvideAssemblyEvidence (a, e);
				}
			}

			return e;
		}
		public void ProvideAssemblyEvidence ()
		{
			HostSecurityManager hsm = new HostSecurityManager ();
			Assembly a = Assembly.GetExecutingAssembly ();

			Evidence result = hsm.ProvideAssemblyEvidence (a, null);
			Assert.IsNull (result, "null");

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

			e.AddHost (new Zone (SecurityZone.Untrusted));
			result = hsm.ProvideAssemblyEvidence (a, e);
			Assert.AreEqual (1, result.Count, "Count-1");
		}
Exemplo n.º 23
0
		public void GetStore_DomainScope_Evidence_NullAssemblyEvidence ()
		{
			IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly;

			Evidence de = new Evidence ();
			de.AddHost (new Zone (SecurityZone.Internet));
			IsolatedStorageFile isf = IsolatedStorageFile.GetStore (scope, de, typeof (Zone), null, null);
		}
Exemplo n.º 24
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");
#if !NET_2_1
			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");
#endif
			Assert.IsTrue ((isf.CurrentSize >= 0), "CurrentSize");
		}
Exemplo n.º 25
0
        internal void InitStore(IsolatedStorageScope scope, 
            Object app, Object assem)
        {
            Assembly callerAssembly;
            PermissionSet psAllowed = null, psDenied = null;
            Evidence appEv = null, assemEv = new Evidence();

            assemEv.AddHost(assem);

            if (IsDomain(scope))
            {
                appEv = new Evidence();
                appEv.AddHost(app);
            }

            _InitStore(scope, appEv, null, assemEv, 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);
        }
Exemplo n.º 26
0
        private static void CheckAddedAssemblies( PolicyLevel level, ref ArrayList assemblies )
        {
            try
            {
                if (assemblies == null || level == null)
                    return;

                IEnumerator enumerator = assemblies.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    Assembly assembly = (Assembly)enumerator.Current;
                    StrongName sn = FindStrongName( assembly.Evidence );

                    if (sn == null)
                    {
                    PauseCapableWriteLine( manager.GetString( "Dialog_AssemblyNotStrongNamed" ) );
                        if (!GetAnswer())
                            throw new ExitException();
                    }
                    else if (!sn.Name.Equals( "mscorlib" ))
                    {
                        IEnumerator snEnumerator = level.FullTrustAssemblies.GetEnumerator();
                        bool found = false;

                        Evidence evidence = new Evidence();
                        evidence.AddHost( sn );

                        while (snEnumerator.MoveNext())
                        {
                            if (((StrongNameMembershipCondition)snEnumerator.Current).Check( evidence ))
                            {
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                        PauseCapableWriteLine( manager.GetString( "Dialog_StrongNameAssemblyAdded1" ) );
                            PauseCapableWriteLine( sn.Name + " " + sn.Version );
                        PauseCapableWriteLine( manager.GetString( "Dialog_StrongNameAssemblyAdded2" ) );
                            if (GetAnswer())
                            {
                                level.AddFullTrustAssembly( sn );
                            }
                        }
                    }
                }
            }
            finally
            {
                assemblies = new ArrayList();
            }
        }
Exemplo n.º 27
0
        static Evidence GenerateShellEvidence( String fileName, String option )
        {
            Assembly asm = LoadAssembly( fileName, option, false );

            if (asm == null)
            {
                String fullPath = Path.GetFullPath( fileName );

                if (fullPath == null || !File.Exists( fullPath ))
                    Error( option, manager.GetString( "Error_UnableToLoadAssembly" ), -1 );

                    if (PolicyPrompt)
                {
                    PauseCapableWriteLine( String.Format( manager.GetString( "Dialog_UseFakeEvidenceQuestion" ), fileName ) );

                    if (!GetAnswer())
                    {
                        PauseCapableWriteLine( manager.GetString( "Dialog_OperationAborted" ) );
                        throw new ExitException();
                    }
                }
                else
                {
                    PauseCapableWriteLine( String.Format( manager.GetString( "Dialog_UseFakeEvidence" ), fileName ) );
                }

                String fileUrl = "file:///" + fullPath;

                Evidence evidence = new Evidence();
                evidence.AddHost( Zone.CreateFromUrl( fileUrl ) );
                evidence.AddHost( new Url( fileUrl ) );

                return evidence;
            }
            else
            {           
                return asm.Evidence;
            }
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("RiskyType object in CURRENT APPDOMAIN");
                // risk1 is instance of RiskyType main AppDomain
                RiskyType risk1 = new RiskyType();

            #if(UNRESTRICTED)
                // show process ID and AppDomain name for RiskType instance
                risk1.ProcessID();
                risk1.AppDomainName();
            #endif

                // invoke safe and risky methods in first AppDomain
                string safeResult = risk1.LowRisk();
                Console.WriteLine(safeResult);
                string riskyResult = risk1.HighRisk("risky.txt");
                Console.Write(riskyResult);
                Console.WriteLine("\n");

            #if(UNRESTRICTED)
                // create new AppDomain with same privileges as first AppDomain
                // to show processID/appdomain name info
                AppDomain restrictedDomain = AppDomain.CreateDomain("restrictedDomain");
            #else
                // create new AppDomain with privileges restricted by security policy
                Evidence ev = new Evidence();
                ev.AddHost(new Zone(SecurityZone.Internet));
                AppDomain restrictedDomain = AppDomain.CreateDomain("restrictedDomain", ev);
            #endif

                Console.WriteLine("RiskyType object in RESTRICTED APPDOMAIN");

                // use reflection to load the assembly Risky into new app domain and create an instance of RiskyType
                // the instance, risk2, is a transparent proxy to an instance of RiskyType in restricted domain
                // RiskyType must subclass MarshalByRefObject
                RiskyType risk2 = (RiskyType)restrictedDomain.CreateInstanceAndUnwrap(
                    "Risky", "Risky.RiskyType");

            #if(UNRESTRICTED)
                // show process ID and AppDomain name for RiskType instance accessed through proxy
                risk2.ProcessID();
                risk2.AppDomainName();
            #endif

                // invoke safe and risky methods in new AppDomain
                safeResult = risk2.LowRisk();
                Console.WriteLine(safeResult);
                riskyResult = risk2.HighRisk("risky.txt");
                Console.Write(riskyResult);
                Console.WriteLine("\n");
            }
            catch (SecurityException e)
            {
                Console.WriteLine("SecurityException: {0}", e.Message);
            }
            finally
            {
                Console.ReadKey();
            }
        }
Exemplo n.º 29
0
		public void GetStore_AssemblyScope_Evidence_NullDomainEvidence ()
		{
			IsolatedStorageScope scope = IsolatedStorageScope.User | IsolatedStorageScope.Assembly;

			Evidence ae = new Evidence ();
			ae.AddHost (new Zone (SecurityZone.Internet));
			IsolatedStorageFile isf = IsolatedStorageFile.GetStore (scope, null, null, ae, typeof (Zone));
		}
Exemplo n.º 30
0
		static Evidence CreateAssemblyEvidence(string fileName)
		{
			//HACK: I am unsure whether 'Hash' evidence is required - since this will be difficult to obtain, we will not supply it...
 
			Evidence newEvidence = new Evidence();

			//We must have zone evidence, or we will get a policy exception
			Zone zone = new Zone(SecurityZone.MyComputer);
			newEvidence.AddHost(zone);

			//If the assembly is strong-named, we must supply this evidence
			//for StrongNameIdentityPermission demands
			AssemblyName assemblyName = AssemblyName.GetAssemblyName(fileName);
			byte[] pk = assemblyName.GetPublicKey();
			if (pk!=null && pk.Length != 0)
			{
				StrongNamePublicKeyBlob blob = new StrongNamePublicKeyBlob(pk);
				StrongName strongName = new StrongName(blob, assemblyName.Name, assemblyName.Version);
				newEvidence.AddHost(strongName);
			}

			return newEvidence;
		}
Exemplo n.º 31
0
		/// <summary>
		/// Construct an application domain for running a test package
		/// </summary>
		/// <param name="package">The TestPackage to be run</param>
		public AppDomain CreateDomain( TestPackage package )
		{
			AppDomainSetup setup = new AppDomainSetup();
			 
			//For paralell tests, we need to use distinct application name
        	setup.ApplicationName = "Tests" + "_" + Environment.TickCount;

            FileInfo testFile = package.FullName != null && package.FullName != string.Empty
                ? new FileInfo(package.FullName)
                : null;

            string appBase = package.BasePath;
            string configFile = package.ConfigurationFile;
            string binPath = package.PrivateBinPath;

            if (testFile != null)
            {
                if (appBase == null || appBase == string.Empty)
                    appBase = testFile.DirectoryName;

                if (configFile == null || configFile == string.Empty)
                    configFile = Services.ProjectService.CanLoadProject(testFile.Name)
                        ? Path.GetFileNameWithoutExtension(testFile.Name) + ".config"
                        : testFile.Name + ".config";
            }
            else if (appBase == null || appBase == string.Empty)
                appBase = GetCommonAppBase(package.Assemblies);

            setup.ApplicationBase = appBase;
            // TODO: Check whether Mono still needs full path to config file...
            setup.ConfigurationFile = appBase != null && configFile != null
                ? Path.Combine(appBase, configFile)
                : configFile;

            if (package.AutoBinPath)
				binPath = GetPrivateBinPath( appBase, package.Assemblies );

			setup.PrivateBinPath = binPath;

            if (package.GetSetting("ShadowCopyFiles", true))
            {
                setup.ShadowCopyFiles = "true";
                setup.ShadowCopyDirectories = appBase;
                setup.CachePath = GetCachePath();
            }
            else
                setup.ShadowCopyFiles = "false";

			string domainName = "test-domain-" + package.Name;
            // Setup the Evidence
            Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
            if (evidence.Count == 0)
            {
                Zone zone = new Zone(SecurityZone.MyComputer);
                evidence.AddHost(zone);
                Assembly assembly = Assembly.GetExecutingAssembly();
                Url url = new Url(assembly.CodeBase);
                evidence.AddHost(url);
                Hash hash = new Hash(assembly);
                evidence.AddHost(hash);
            }

            log.Info("Creating AppDomain " + domainName);

			AppDomain runnerDomain;
			
			// TODO: Try to eliminate this test. Currently, running on
			// Linux with the permission set specified causes an
			// unexplained crash when unloading the domain.
#if NET_2_0
			if (Environment.OSVersion.Platform == PlatformID.Win32NT)
			{
            	PermissionSet permissionSet = new PermissionSet( PermissionState.Unrestricted );	
           		runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup, permissionSet, null);
			}
			else
#endif
            	runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup);

			// HACK: Only pass down our AddinRegistry one level so that tests of NUnit
			// itself start without any addins defined.
			if ( !IsTestDomain( AppDomain.CurrentDomain ) )
				runnerDomain.SetData("AddinRegistry", Services.AddinRegistry);

            // Inject DomainInitializer into the remote domain - there are other
            // approaches, but this works for all CLR versions.
            DomainInitializer initializer = DomainInitializer.CreateInstance(runnerDomain);

            // HACK: Under nunit-console, direct use of the enum fails
            int traceLevel = IsTestDomain(AppDomain.CurrentDomain)
                ? (int)InternalTraceLevel.Off : (int)InternalTrace.Level;

            initializer.InitializeDomain(traceLevel);

			return runnerDomain;
		}
Exemplo n.º 32
0
		public void CreateDomain_StringEvidence ()
		{
			Evidence e = new Evidence ();
			ad = AppDomain.CreateDomain ("CreateDomain_StringEvidence", e);
			Assert.IsNotNull (ad.Evidence, "Evidence");
			Assert.AreEqual (0, ad.Evidence.Count, "Evidence.Count");

			e.AddHost (new Zone (SecurityZone.MyComputer));
			Assert.AreEqual (0, ad.Evidence.Count, "Evidence.Count");
			// evidence isn't copied but referenced
		}