public static Evidence CreateEvidenceForUrl(string securityUrl) {
#if !DISABLE_CAS_USE
            Evidence evidence = new Evidence();
            if (securityUrl != null && securityUrl.Length > 0) {
                evidence.AddHostEvidence(new Url(securityUrl));
                evidence.AddHostEvidence(Zone.CreateFromUrl(securityUrl));
                Uri uri = new Uri(securityUrl, UriKind.RelativeOrAbsolute);
                if (uri.IsAbsoluteUri && !uri.IsFile) {
                    evidence.AddHostEvidence(Site.CreateFromUrl(securityUrl));
                }

                // Allow same directory access for UNCs (SQLBUDT 394535)
                if (uri.IsAbsoluteUri && uri.IsUnc) {
                    string uncDir = System.IO.Path.GetDirectoryName(uri.LocalPath);
                    if (uncDir != null && uncDir.Length != 0) {
                        evidence.AddHostEvidence(new UncDirectory(uncDir));
                    }
                }
            }

            return evidence;
#else
            return null;
#endif
        }
Ejemplo n.º 2
0
        /*!*/
        private static PermissionSet CreatePermissionSet()
        {
            #if CLR2
            string name = "Internet";
            bool foundName = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator e = SecurityManager.PolicyHierarchy();
            while (e.MoveNext()) {
                PolicyLevel level = (PolicyLevel)e.Current;
                PermissionSet levelSet = level.GetNamedPermissionSet(name);
                if (levelSet != null) {
                    foundName = true;
                    setIntersection = setIntersection.Intersect(levelSet);
                }
            }

            if (setIntersection == null || !foundName) {
                setIntersection = new PermissionSet(PermissionState.None);
            } else {
                setIntersection = new NamedPermissionSet(name, setIntersection);
            }

            return setIntersection;
            #else
            // this functionality is not available on Mono (AddHostEvidence is undefined), use dynamic to resolve it at runtime
            dynamic e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.Internet));
            return SecurityManager.GetStandardSandbox((Evidence)e);
            #endif
        }
Ejemplo n.º 3
0
        protected void LoadInAppDomain(string fullTypeName, ASCOMClient ascomClient)
        {
            string[] tokens = fullTypeName.Split(new char[] { ',' }, 2);
            m_AssemblyName = new AssemblyName(tokens[1]);

            var appSetup = new AppDomainSetup()
            {
                ApplicationName = "OccuRec",
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
            };

            m_DomainName = string.Format("{0}{1}.v{2}", APP_DOMAIN_PREFIX, m_AssemblyName.Name, m_AssemblyName.Version != null ? m_AssemblyName.Version.ToString() : "XX");

            var e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.MyComputer));
            PermissionSet pset = SecurityManager.GetStandardSandbox(e);

            m_HostDomain = AppDomain.CreateDomain(m_DomainName, AppDomain.CurrentDomain.Evidence, appSetup, pset, null);
            m_HostDomain.AssemblyResolve += m_HostDomain_AssemblyResolve;
            m_HostDomain.ReflectionOnlyAssemblyResolve += m_HostDomain_AssemblyResolve;
            m_HostDomain.UnhandledException += m_HostDomain_UnhandledException;
            m_HostDomain.DomainUnload += m_HostDomain_DomainUnload;

            object obj = m_HostDomain.CreateInstanceAndUnwrap(tokens[1], tokens[0]);

            ascomClient.RegisterLifetimeService(obj as MarshalByRefObject);

            m_Instance = (IIsolatedDevice)obj;
            m_Instance.Initialise(new OccuRecHostDelegate(tokens[0], ascomClient));
        }
        public static AppDomain SandboxCreator()
        {
            CheckMono();
            #if RAZOR4
            Assert.Ignore("IsolatedRazorEngineServiceTestFixture is not tested with razor 4 as it is not signed!");
            #endif

            #if MONO
            // Mono has no AddHostEvidence or GetHostEvidence.
            // We do not run the tests anyway.
            return null;
            #else
            Evidence ev = new Evidence();
            ev.AddHostEvidence(new Zone(SecurityZone.Internet));
            PermissionSet permSet = SecurityManager.GetStandardSandbox(ev);
            // We have to load ourself with full trust
            StrongName razorEngineAssembly = typeof(RazorEngineService).Assembly.Evidence.GetHostEvidence<StrongName>();
            // We have to load Razor with full trust (so all methods are SecurityCritical)
            // This is because we apply AllowPartiallyTrustedCallers to RazorEngine, because
            // We need the untrusted (transparent) code to be able to inherit TemplateBase.
            // Because in the normal environment/appdomain we run as full trust and the Razor assembly has no security attributes
            // it will be completely SecurityCritical.
            // This means we have to mark a lot of our members SecurityCritical (which is fine).
            // However in the sandbox domain we have partial trust and because razor has no Security attributes that means the
            // code will be transparent (this is where we get a lot of exceptions, because we now have different security attributes)
            // To work around this we give Razor full trust in the sandbox as well.
            StrongName razorAssembly = typeof(RazorTemplateEngine).Assembly.Evidence.GetHostEvidence<StrongName>();
            // We trust ourself as well
            StrongName testAssembly = typeof(IsolatedRazorEngineServiceTestFixture).Assembly.Evidence.GetHostEvidence<StrongName>();
            AppDomainSetup adSetup = new AppDomainSetup();
            adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, razorEngineAssembly, razorAssembly, testAssembly);
            return newDomain;
            #endif
        }
        protected override void Arrange()
        {
            base.Arrange();

            var fullyTrustedAssemblies = this.GetFullyTrustedAssemblies().ToArray();
            var unsignedAssemblies = fullyTrustedAssemblies.Where(sn => sn.PublicKey.ToString() == "");
            if (unsignedAssemblies.Any())
            {
                Assert.Inconclusive("Full trust assemblies must be signed. This test will be ignored. Unsigned assemblies: " + unsignedAssemblies.Aggregate("", (a, sn) => a + sn.Name + " "));
            }

            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Intranet));
            var set = SecurityManager.GetStandardSandbox(evidence);
            this.AddPermissions(set);
            this.appDomain =
                AppDomain.CreateDomain(
                    "partial trust",
                    null,
                    AppDomain.CurrentDomain.SetupInformation,
                    set,
                    fullyTrustedAssemblies);

            this.loggerProxy = ((LoggerProxy)this.appDomain.CreateInstanceAndUnwrap(typeof(LoggerProxy).Assembly.FullName, typeof(LoggerProxy).FullName));
            this.loggerProxy.Setup();
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AppDomainProxy"/> class.
 /// </summary>
 AppDomainProxy()
 {
     var evidence = new Evidence ();
     evidence.AddHostEvidence (new Zone (SecurityZone.MyComputer));
     var setup = new AppDomainSetup ();
     domain = AppDomain.CreateDomain (Guid.NewGuid ().ToString ("N"), evidence, setup);
     domain.AssemblyResolve += ResolveAssembly;
 }
        public AppDomain CreateSandboxDomain(string name, string path, SecurityZone zone)
        {
            var setup = new AppDomainSetup { ApplicationBase = Common.ApiPath, PrivateBinPath = Path.GetFullPath(path) };

            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(zone));
            var permissions = SecurityManager.GetStandardSandbox(evidence);

            var strongName = typeof(ClientService).Assembly.Evidence.GetHostEvidence<StrongName>();

            return AppDomain.CreateDomain(name, null, setup);
        }
Ejemplo n.º 8
0
        private static void RunScenario(SecurityZone zone, bool fullyTrustEventSource, bool grantUnmanagedCodePermission)
        {
            Console.Write("Running scenario for zone '{0}', fully trusted EventSource {1}, unmanaged permission {2}: ", zone, fullyTrustEventSource, grantUnmanagedCodePermission);

            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(zone));
            var permissionSet = SecurityManager.GetStandardSandbox(evidence);
            if (!permissionSet.IsUnrestricted() && grantUnmanagedCodePermission)
            {
                permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
            }

            var eventSourceAssemblyName = typeof(EventSource).Assembly.GetName();
            var fullyTrustedAssemblies =
                fullyTrustEventSource
                    ? new StrongName[]  
                    {
                        new StrongName(new StrongNamePublicKeyBlob(eventSourceAssemblyName.GetPublicKey()), eventSourceAssemblyName.Name, eventSourceAssemblyName.Version)
                    }
                    : new StrongName[0];

            var info = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory };
            info.ApplicationTrust = new ApplicationTrust(permissionSet, fullyTrustedAssemblies);

            var appDomain =
                AppDomain.CreateDomain(
                    "partial trust",
                    evidence,
                    info);
            try
            {
                var tester = (LttADEventSourceTester)appDomain
                    .CreateInstanceAndUnwrap(
                        typeof(LttADEventSourceTester).Assembly.GetName().Name,
                        typeof(LttADEventSourceTester).FullName);
                tester.IsEventSourceAssmFullyTrusted = fullyTrustEventSource;
                tester.DoStuff(1);
                tester.DoStuff(2);
                tester.DoStuff(3);

                Assert.IsTrue(tester.IsStateValid, "EventSource ConstructionException as expected");
                Console.WriteLine("SUCCESS");
                Console.WriteLine();
            }
            finally
            {
                AppDomain.Unload(appDomain);
            }

            Console.WriteLine("==================================================================");
            Console.WriteLine();
        }
 public override void GetRestrictedPermissions(IInternalConfigRecord configRecord, out PermissionSet permissionSet, out bool isHostReady)
 {
     string streamName;
     bool flag = this.IsFile(configRecord.StreamName);
     if (flag)
     {
         streamName = UrlPath.ConvertFileNameToUrl(configRecord.StreamName);
     }
     else
     {
         streamName = configRecord.StreamName;
     }
     Evidence evidence = new Evidence();
     evidence.AddHostEvidence<Url>(new Url(streamName));
     evidence.AddHostEvidence<Zone>(Zone.CreateFromUrl(streamName));
     if (!flag)
     {
         evidence.AddHostEvidence<Site>(Site.CreateFromUrl(streamName));
     }
     permissionSet = SecurityManager.GetStandardSandbox(evidence);
     isHostReady = true;
 }
 public static Evidence CreateEvidenceForUrl(string securityUrl)
 {
     Evidence evidence = new Evidence();
     if ((securityUrl != null) && (securityUrl.Length > 0))
     {
         evidence.AddHostEvidence<Url>(new Url(securityUrl));
         evidence.AddHostEvidence<Zone>(Zone.CreateFromUrl(securityUrl));
         Uri uri = new Uri(securityUrl, UriKind.RelativeOrAbsolute);
         if (uri.IsAbsoluteUri && !uri.IsFile)
         {
             evidence.AddHostEvidence<Site>(Site.CreateFromUrl(securityUrl));
         }
         if (uri.IsAbsoluteUri && uri.IsUnc)
         {
             string directoryName = Path.GetDirectoryName(uri.LocalPath);
             if ((directoryName != null) && (directoryName.Length != 0))
             {
                 evidence.AddHostEvidence<UncDirectory>(new UncDirectory(directoryName));
             }
         }
     }
     return evidence;
 }
Ejemplo n.º 11
0
    static ScriptCompiler()
    {
      cParams = new CompilerParameters();
      cParams.GenerateExecutable = false;
      cParams.GenerateInMemory = false;
      cParams.IncludeDebugInformation = false;
      cParams.ReferencedAssemblies.Add(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.AddHostEvidence(new Zone(SecurityZone.Internet));
    }
Ejemplo n.º 12
0
		private static AppDomain CreateDomain(string id, string assemblyPath)
		{
			var permSet = new PermissionSet(PermissionState.None);
			permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
			var evidence = new Evidence();
			evidence.AddHostEvidence(new Zone(SecurityZone.Untrusted));
			var fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>();

			var adSetup = new AppDomainSetup
			{
				ApplicationBase = Path.GetDirectoryName(assemblyPath),
			};

			var domain = AppDomain.CreateDomain(id, evidence, adSetup, permSet, fullTrustAssembly);
			return domain;
		}
Ejemplo n.º 13
0
		private AppDomain Create()
		{
			Evidence internetEvidence = new Evidence();
			internetEvidence.AddHostEvidence(new Zone(SecurityZone.MyComputer));

			PermissionSet internetPermissions = SecurityManager.GetStandardSandbox(internetEvidence);

			AppDomainSetup setup = new AppDomainSetup();
			setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

			if (internetPermissions != null)
			{
				return AppDomain.CreateDomain("Add-In Domain", internetEvidence, setup, internetPermissions);
			}
			
			return AppDomain.CreateDomain("Add-in Domain", internetEvidence, setup);
		}
Ejemplo n.º 14
0
        public void ShouldWorkEvenWithLowestPossiblePermissions()
        {
            // based on: https://msdn.microsoft.com/en-us/library/bb384237(v=vs.110).aspx
            Evidence evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
            PermissionSet permissionSet = new NamedPermissionSet("Internet", SecurityManager.GetStandardSandbox(evidence));
            permissionSet.SetPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));
            AppDomainSetup appDomainSetup = new AppDomainSetup
            {
                ApplicationBase = "."
            };

            AppDomain sandbox = AppDomain.CreateDomain("Sandbox", evidence, appDomainSetup, permissionSet, null);
            CrossDomain crossDomain = (CrossDomain)sandbox.CreateInstanceAndUnwrap(typeof(CrossDomain).Assembly.FullName, typeof(CrossDomain).FullName);

            Assert.AreEqual(3, crossDomain.RunArrayProvider());
        }
Ejemplo n.º 15
0
        public Sandbox(string name = DefaultName)
        {
            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));

            var permissions = SecurityManager.GetStandardSandbox(evidence);
            permissions.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            permissions.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));

            var setup = new AppDomainSetup
                        {
                            ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                            ApplicationName = name,
                            DisallowBindingRedirects = true,
                            DisallowCodeDownload = true,
                            DisallowPublisherPolicy = true
                        };

            domain = AppDomain.CreateDomain(name, null, setup, permissions);
        }
Ejemplo n.º 16
0
        private void LoadAddinInAppDomain(string assemblyName, string typeName, AddinManager addinManager)
        {
            var appSetup = new AppDomainSetup()
            {
                ApplicationName = "Tangra 3",
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
                PrivateBinPath = @"Addins",
            };

            m_DomainName = string.Format("Tangra.Addins.{0}.v{1}", m_AssemblyName.Name, m_AssemblyName.Version.ToString());

            var e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.MyComputer));
            PermissionSet pset = SecurityManager.GetStandardSandbox(e);

            m_HostDomain = AppDomain.CreateDomain(m_DomainName, AppDomain.CurrentDomain.Evidence, appSetup, pset, null);
            m_HostDomain.AssemblyResolve += m_HostDomain_AssemblyResolve;
            m_HostDomain.ReflectionOnlyAssemblyResolve += m_HostDomain_AssemblyResolve;
            m_HostDomain.UnhandledException += m_HostDomain_UnhandledException;

            object obj = m_HostDomain.CreateInstanceAndUnwrap(assemblyName, typeName);

            ILease lease = (ILease)(obj as MarshalByRefObject).GetLifetimeService();
            if (lease != null)
                lease.Register(addinManager.RemotingClientSponsor);

            m_Instance = (ITangraAddin)obj;
            m_Instance.Initialise(new TangraHostDelegate(typeName, addinManager));

            foreach (object actionInstance in m_Instance.GetAddinActions())
            {
                var mbrObj = actionInstance as MarshalByRefObject;
                if (mbrObj != null)
                {
                    lease = (ILease)mbrObj.GetLifetimeService();
                    if (lease != null)
                        lease.Register(addinManager.RemotingClientSponsor);
                }
            }
        }
        public void FlatFileListenerReplacedEnviromentVariablesWillFallBackIfNotPrivilegesToRead()
        {
            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
            var set = SecurityManager.GetStandardSandbox(evidence);
            set.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            set.RemovePermission(typeof(EnvironmentPermission));

            var domain = AppDomain.CreateDomain("partial trust", null, AppDomain.CurrentDomain.SetupInformation, set);

            try
            {
                domain.DoCallBack(CheckListener);
            }
            catch
            {
                throw;
            }
            finally
            {
                AppDomain.Unload(domain);
            }
        }
Ejemplo n.º 18
0
        public override void BeforeTest(TestDetails testDetails)
        {
            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Intranet));
            var permissions = SecurityManager.GetStandardSandbox(evidence);
            // var permissions = new PermissionSet(PermissionState.Unrestricted);

            var setup = new AppDomainSetup
            {
                ApplicationBase = Path.GetDirectoryName(Assembly.GetAssembly(typeof(SandboxHost)).Location)
            };

            var fullTrustAssemblies = new StrongName[]
            {
                typeof(SandboxHost).Assembly.Evidence.GetHostEvidence<StrongName>(),
                typeof(Entity).Assembly.Evidence.GetHostEvidence<StrongName>(),
                testDetails.Method.DeclaringType.Assembly.Evidence.GetHostEvidence<StrongName>()
            };

            var domain = AppDomain.CreateDomain(testDetails.FullName, evidence, setup, permissions, fullTrustAssemblies);

            var type = typeof(SandboxHost);

            var handle = Activator.CreateInstanceFrom(domain, type.Assembly.ManifestModule.FullyQualifiedName, type.FullName);

            var sandbox = (SandboxHost)handle.Unwrap();

            var exception = sandbox.Execute(new SandboxTest(testDetails));

            if (exception == null)
            {
                Assert.Pass();
            }

            throw exception;
        }
        public void CanGetExistingSectionInAppConfigEvenIfTheAppDomainDoesNotHaveFileIOPermission()
        {
            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
            var set = SecurityManager.GetStandardSandbox(evidence);
            set.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            set.AddPermission(new ConfigurationPermission(PermissionState.Unrestricted));
            set.RemovePermission(typeof(FileIOPermission));

            var domain = AppDomain.CreateDomain("partial trust", null, AppDomain.CurrentDomain.SetupInformation, set);

            try
            {
                domain.DoCallBack(CheckSource);
            }
            catch
            {
                throw;
            }
            finally
            {
                AppDomain.Unload(domain);
            }
        }
Ejemplo n.º 20
0
        private static QuickCacheEntryType GenerateQuickCache(PolicyLevel level)
        {
            if (FullTrustMap == null)
            {
                // This mapping must stay in [....] with the SecurityZone enumeration in SecurityZone.cs
                FullTrustMap = new QuickCacheEntryType[]
                {
                    QuickCacheEntryType.FullTrustZoneMyComputer,
                  QuickCacheEntryType.FullTrustZoneIntranet,
                    QuickCacheEntryType.FullTrustZoneTrusted,
                  QuickCacheEntryType.FullTrustZoneInternet,
                    QuickCacheEntryType.FullTrustZoneUntrusted
                };
            }

            QuickCacheEntryType accumulator = (QuickCacheEntryType)0;

            Evidence noEvidence = new Evidence();

            PermissionSet policy = null;

            try
            {
                policy = level.Resolve( noEvidence ).PermissionSet;
                if (policy.IsUnrestricted())
                    accumulator |= QuickCacheEntryType.FullTrustAll;
            }
            catch (PolicyException)
            {
            }

            foreach (SecurityZone zone in Enum.GetValues(typeof(SecurityZone)))
            {
                if (zone == SecurityZone.NoZone)
                    continue;

                Evidence zoneEvidence = new Evidence();
                zoneEvidence.AddHostEvidence(new Zone(zone));

                PermissionSet zonePolicy = null;

                try
                {
                    zonePolicy = level.Resolve( zoneEvidence ).PermissionSet;
                    if (zonePolicy.IsUnrestricted())
                    {
                        Contract.Assert(0 <= (int)zone && (int)zone < FullTrustMap.Length, "FullTrustMap does not contain a mapping for this zone.");
                        accumulator |= FullTrustMap[(int)zone];
                    }
                }
                catch (PolicyException)
                {
                }
            }

            return accumulator;
        }
Ejemplo n.º 21
0
        protected override void ProcessRecord()
        {
            if (MyInvocation.InvocationName.ToLower() == "save-pnpprovisioninghierarchy")
            {
                WriteWarning("Save-PnPProvisioningHierarchy has been deprecated. Use Save-PnPTenantTemplate instead.");
            }
            // Determine the output file name and path
            string outFileName = Path.GetFileName(Out);

            if (!Path.IsPathRooted(Out))
            {
                Out = Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Out);
            }

            bool proceed = false;

            if (System.IO.File.Exists(Out))
            {
                if (Force || ShouldContinue(string.Format(Properties.Resources.File0ExistsOverwrite, Out),
                                            Properties.Resources.Confirm))
                {
                    System.IO.File.Delete(Out);
                    proceed = true;
                }
            }
            else
            {
                proceed = true;
            }

            string outPath = new FileInfo(Out).DirectoryName;

            // Determine if it is an .XML or a .PNP file
            var extension = "";

            if (proceed && outFileName != null)
            {
                if (outFileName.IndexOf(".", StringComparison.Ordinal) > -1)
                {
                    extension = outFileName.Substring(outFileName.LastIndexOf(".", StringComparison.Ordinal)).ToLower();
                }
                else
                {
                    extension = ".pnp";
                }
            }

            var fileSystemConnector = new FileSystemConnector(outPath, "");

            ITemplateFormatter formatter = XMLPnPSchemaFormatter.LatestFormatter;

            if (extension == ".pnp")
            {
                var useNewEvidence = false;
                try
                {
                    var usfdAttempt1 = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForDomain(); // this will fail when the current AppDomain Evidence is instantiated via COM or in PowerShell
                }
                catch (Exception e)
                {
                    useNewEvidence = true;
                }

                if (useNewEvidence)
                {
                    var replacementEvidence = new System.Security.Policy.Evidence();
                    replacementEvidence.AddHostEvidence(new System.Security.Policy.Zone(System.Security.SecurityZone.MyComputer));

                    var currentAppDomain      = System.Threading.Thread.GetDomain();
                    var securityIdentityField = currentAppDomain.GetType().GetField("_SecurityIdentity", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                    securityIdentityField.SetValue(currentAppDomain, replacementEvidence);
                }

                var templateFileName = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(
                    Out, fileSystemConnector, templateFileName: templateFileName);
                WriteObject("Processing template");
                provider.SaveAs(Template, templateFileName);
                ProcessFiles(Out, fileSystemConnector, provider.Connector);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(outPath, "");
                provider.SaveAs(Template, Out);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// create a permission set
        /// </summary>
        private PermissionSet GetPermissionSet()
        {
            // create an evidence of type zone
            var ev = new Evidence();
            ev.AddHostEvidence(new Zone(SecurityZone.MyComputer));

            // return the PermissionSets specific to the type of zone
            return SecurityManager.GetStandardSandbox(ev);
        }
        public void CannotCreateInstanceFromConfigurationFileInPartialTrustIfLoggingIsFullyTrusted()
        {
            LoggingSettings loggingSettings = new LoggingSettings();
            loggingSettings.Formatters.Add(new FormatterData(formatterName, typeof(BinaryLogFormatter)));
            loggingSettings.TraceListeners.Add(new MsmqTraceListenerData("listener", CommonUtil.MessageQueuePath, formatterName));
            var source = CommonUtil.SaveSectionsAndGetConfigurationSource(loggingSettings);

            var commonAssembly = typeof(Guard).Assembly.GetName();
            var loggingAssembly = typeof(LogWriter).Assembly.GetName();

            var fullyTrustedAssemblies = new[] { 
                    new StrongName(new StrongNamePublicKeyBlob(commonAssembly.GetPublicKey()), commonAssembly.Name, commonAssembly.Version),
                    new StrongName(new StrongNamePublicKeyBlob(loggingAssembly.GetPublicKey()), loggingAssembly.Name, loggingAssembly.Version)
                };
            var unsignedAssemblies = fullyTrustedAssemblies.Where(sn => sn.PublicKey.ToString() == "");
            if (unsignedAssemblies.Any())
            {
                Assert.Inconclusive("Full trust assemblies must be signed. This test will be ignored. Unsigned assemblies: " + unsignedAssemblies.Aggregate("", (a, sn) => a + sn.Name + " "));
            }

            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Intranet));
            var set = SecurityManager.GetStandardSandbox(evidence);
            set.AddPermission(new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy | SecurityPermissionFlag.SerializationFormatter));
            set.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            set.AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            var appDomain =
                AppDomain.CreateDomain(
                    "partial trust",
                    null,
                    AppDomain.CurrentDomain.SetupInformation,
                    set,
                    fullyTrustedAssemblies);

            try
            {
                appDomain.DoCallBack(LoadConfiguration);

                Assert.Fail("Should have thrown");
            }
            catch (ConfigurationErrorsException)
            {
            }
            finally
            {
                AppDomain.Unload(appDomain);
            }
        }
Ejemplo n.º 24
0
        internal static Evidence MergeApplicationEvidence(Evidence evidence,
                                                          ApplicationIdentity applicationIdentity,
                                                          ActivationContext activationContext,
                                                          string[] activationData,
                                                          ApplicationTrust applicationTrust)
        {
            Evidence appEvidence = new Evidence();

            ActivationArguments activationArgs = (activationContext == null ? new ActivationArguments(applicationIdentity, activationData) : new ActivationArguments(activationContext, activationData));
            appEvidence = new Evidence();
            appEvidence.AddHostEvidence(activationArgs);

            if (applicationTrust != null)
                appEvidence.AddHostEvidence(applicationTrust);

            if (activationContext != null)
            {
                Evidence asiEvidence = new ApplicationSecurityInfo(activationContext).ApplicationEvidence;
                if (asiEvidence != null)
                    appEvidence.MergeWithNoDuplicates(asiEvidence);
            }

            if (evidence != null)
                appEvidence.MergeWithNoDuplicates(evidence);

            return appEvidence;
        }
Ejemplo n.º 25
0
		private static Evidence CreateAppDomainEvidence(string assemblyName, string assemblyVersion, string assemblyUrl, bool hasStrongName)
		{
			var evidence = new Evidence();
			evidence.AddHostEvidence(new Url(assemblyUrl));
			if (hasStrongName) evidence.AddHostEvidence(new StrongName(new StrongNamePublicKeyBlob(new byte[160]), assemblyName, new Version(assemblyVersion)));
			return evidence;
		}
Ejemplo n.º 26
0
        /// From MRMModule.cs by Adam Frisby
        /// <summary>
        ///   Create an AppDomain that contains policy restricting code to execute
        ///   with only the permissions granted by a named permission set
        /// </summary>
        /// <param name = "permissionSetName">name of the permission set to restrict to</param>
        /// <param name = "appDomainName">'friendly' name of the appdomain to be created</param>
        /// <exception cref = "ArgumentNullException">
        ///   if <paramref name = "permissionSetName" /> is null
        /// </exception>
        /// <exception cref = "ArgumentOutOfRangeException">
        ///   if <paramref name = "permissionSetName" /> is empty
        /// </exception>
        /// <returns>AppDomain with a restricted security policy</returns>
        /// <remarks>
        ///   Substantial portions of this function from: http://blogs.msdn.com/shawnfa/archive/2004/10/25/247379.aspx
        ///   Valid permissionSetName values are:
        ///   * FullTrust
        ///   * SkipVerification
        ///   * Execution
        ///   * Nothing
        ///   * LocalIntranet
        ///   * Internet
        ///   * Everything
        /// </remarks>
        public AppDomain CreateRestrictedDomain(string permissionSetName, string appDomainName, AppDomainSetup ads)
        {
            if (permissionSetName == null)
                throw new ArgumentNullException("permissionSetName");
            if (permissionSetName.Length == 0)
                throw new ArgumentOutOfRangeException("permissionSetName", permissionSetName,
                                                      "Cannot have an empty permission set name");

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

#if NET_3_5

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

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

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

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

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

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

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

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

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

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

            return restrictedDomain;
        }
Ejemplo n.º 27
0
        private static AppDomain CreateSandbox()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en");
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
            var e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.Internet));

            var ps = SecurityManager.GetStandardSandbox(e);
            var security = new SecurityPermission(SecurityPermissionFlag.Execution);

            ps.AddPermission(security);

            var setup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) };
            return AppDomain.CreateDomain("Sandbox", null, setup, ps);
        }
Ejemplo n.º 28
0
        private static PermissionSet/*!*/ CreatePermissionSet() {
#if CLR2
            string name = "Internet";
            bool foundName = false;
            PermissionSet setIntersection = new PermissionSet(PermissionState.Unrestricted);

            // iterate over each policy level
            IEnumerator e = SecurityManager.PolicyHierarchy();
            while (e.MoveNext()) {
                PolicyLevel level = (PolicyLevel)e.Current;
                PermissionSet levelSet = level.GetNamedPermissionSet(name);
                if (levelSet != null) {
                    foundName = true;
                    setIntersection = setIntersection.Intersect(levelSet);
                }
            }

            if (setIntersection == null || !foundName) {
                setIntersection = new PermissionSet(PermissionState.None);
            } else {
                setIntersection = new NamedPermissionSet(name, setIntersection);
            }

            return setIntersection;
#else
            Evidence e = new Evidence();
            e.AddHostEvidence(new Zone(SecurityZone.Internet));
            return SecurityManager.GetStandardSandbox(e);
#endif
        }       
        private static AppDomain GetSandboxedAppDomain(params IPermission[] permissionsToUpdate)
        {
            var evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Intranet));
            var set = SecurityManager.GetStandardSandbox(evidence);
            set.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            set.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, Path.GetDirectoryName(typeof(LogFormatter).Assembly.Location)));

            foreach (var permission in permissionsToUpdate)
            {
                set.RemovePermission(permission.GetType());
                set.AddPermission(permission);
            }

            var sandbox =
                AppDomain.CreateDomain(
                    "test",
                    AppDomain.CurrentDomain.Evidence,
                    new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase },
                    set);
            return sandbox;
        }
Ejemplo n.º 30
0
        private static Object Setup(Object arg)
        {
            Contract.Requires(arg != null && arg is Object[]);
            Contract.Requires(((Object[])arg).Length >= 8);

            Object[] args=(Object[])arg;
            String           friendlyName               = (String)args[0];
            AppDomainSetup   setup                      = (AppDomainSetup)args[1];
            IntPtr           parentSecurityDescriptor   = (IntPtr)args[2];
            bool             generateDefaultEvidence    = (bool)args[3];
            byte[]           serializedEvidence         = (byte[])args[4];
            AppDomainInitializerInfo initializerInfo    = (AppDomainInitializerInfo)args[5];
            string           sandboxName                = (string)args[6];
            string[]         propertyNames              = (string[])args[7]; // can contain null elements
            string[]         propertyValues             = (string[])args[8]; // can contain null elements           
            // extract evidence
            Evidence providedSecurityInfo = null;
            Evidence creatorsSecurityInfo = null;


            AppDomain ad = AppDomain.CurrentDomain;
            AppDomainSetup newSetup=new AppDomainSetup(setup,false);

            if(propertyNames!=null && propertyValues != null)
            {
#if FEATURE_CORECLR
                StringBuilder normalisedAppPathList = null;
#endif // FEATURE_CORECLR
                for (int i=0; i<propertyNames.Length; i++)
                {
                    if(propertyNames[i]=="APPBASE") // make sure in sync with Fusion
                    {
                        if(propertyValues[i]==null)
                            throw new ArgumentNullException("APPBASE");
                            
                        if (Path.IsRelative(propertyValues[i]))
                            throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );

                        newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);

                    }
#if FEATURE_CAS_POLICY
                    else if(propertyNames[i]=="LOCATION_URI" && providedSecurityInfo==null)
                    {
                        providedSecurityInfo=new Evidence();
                        providedSecurityInfo.AddHostEvidence(new Url(propertyValues[i]));
                        ad.SetDataHelper(propertyNames[i],propertyValues[i],null);
                    }
#endif // FEATURE_CAS_POLICY
#if FEATURE_LOADER_OPTIMIZATION
                    else
                    if(propertyNames[i]=="LOADER_OPTIMIZATION")
                    {
                        if(propertyValues[i]==null)
                            throw new ArgumentNullException("LOADER_OPTIMIZATION");

                        switch(propertyValues[i])
                        {
                            case "SingleDomain": newSetup.LoaderOptimization=LoaderOptimization.SingleDomain;break;
                            case "MultiDomain": newSetup.LoaderOptimization=LoaderOptimization.MultiDomain;break;
                            case "MultiDomainHost": newSetup.LoaderOptimization=LoaderOptimization.MultiDomainHost;break;
                            case "NotSpecified": newSetup.LoaderOptimization=LoaderOptimization.NotSpecified;break;
                            default: throw new ArgumentException(Environment.GetResourceString("Argument_UnrecognizedLoaderOptimization"), "LOADER_OPTIMIZATION");
                        }
                    }
#endif // FEATURE_LOADER_OPTIMIZATION
#if FEATURE_CORECLR
                    else
                    if(propertyNames[i]=="NATIVE_DLL_SEARCH_DIRECTORIES")
                    {
                        if(propertyValues[i]==null)
                            throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES");
                        ad.SetDataHelper(propertyNames[i],propertyValues[i],null);
                        string paths = (string)propertyValues[i];
                        if( paths.Length==0 )
                            continue;
                        nSetNativeDllSearchDirectories(paths);
                    }
                    else
                    if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" ||
                       propertyNames[i]=="PLATFORM_RESOURCE_ROOTS" ||
                       propertyNames[i]=="APP_PATHS" ||
                       propertyNames[i]=="APP_NI_PATHS")
                    {
                        string values = propertyValues[i];
                        if(values==null)
                            throw new ArgumentNullException(propertyNames[i]);

                        int estimatedLength = values.Length + 1; // +1 for extra separator temporarily added at end
                        if (normalisedAppPathList == null) {
                            normalisedAppPathList = new StringBuilder(estimatedLength);
                        }
                        else {
                            normalisedAppPathList.Clear();
                            if (normalisedAppPathList.Capacity < estimatedLength)
                                normalisedAppPathList.Capacity = estimatedLength;
                        }

                        for (int pos = 0; pos < values.Length; pos++)
                        {
                            string path;

                            int nextPos = values.IndexOf(Path.PathSeparator, pos);
                            if (nextPos == -1)
                            {
                                path = values.Substring(pos);
                                pos = values.Length - 1;
                            }
                            else
                            {
                                path = values.Substring(pos, nextPos - pos);
                                pos = nextPos;
                            }

                            if( path.Length==0 )                  // skip empty dirs
                                continue;

                            if (Path.IsRelative(path))
                                throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );

                            string appPath = NormalizePath(path, fullCheck: true);
                            normalisedAppPathList.Append(appPath);
                            normalisedAppPathList.Append(Path.PathSeparator);
                        }
                        // Strip the last separator
                        if (normalisedAppPathList.Length > 0)
                        {
                            normalisedAppPathList.Remove(normalisedAppPathList.Length - 1, 1);
                        }
                        ad.SetDataHelper(propertyNames[i],normalisedAppPathList.ToString(),null);        // not supported by fusion, so set explicitly
                    }
                    else
                    if(propertyNames[i]!= null)
                    {
                        ad.SetDataHelper(propertyNames[i],propertyValues[i],null);     // just propagate
                    }
#endif

                }
            }

#if !FEATURE_CORECLR
            AppDomainSortingSetupInfo sortingSetup = newSetup._AppDomainSortingSetupInfo;

            if(sortingSetup != null)
            {          
                if(sortingSetup._pfnIsNLSDefinedString == IntPtr.Zero || sortingSetup._pfnCompareStringEx == IntPtr.Zero || sortingSetup._pfnLCMapStringEx == IntPtr.Zero || sortingSetup._pfnFindNLSStringEx == IntPtr.Zero
                    || sortingSetup._pfnCompareStringOrdinal == IntPtr.Zero || sortingSetup._pfnGetNLSVersionEx == IntPtr.Zero) 
                {
             
                    if(!(sortingSetup._pfnIsNLSDefinedString == IntPtr.Zero && sortingSetup._pfnCompareStringEx == IntPtr.Zero && sortingSetup._pfnLCMapStringEx == IntPtr.Zero && sortingSetup._pfnFindNLSStringEx == IntPtr.Zero
                        && sortingSetup._pfnCompareStringOrdinal == IntPtr.Zero && sortingSetup._pfnGetNLSVersionEx == IntPtr.Zero)) 
                    {
                        // Some functions defined but not all of them.
                        throw new ArgumentException(Environment.GetResourceString("ArgumentException_NotAllCustomSortingFuncsDefined"));
                    }

                }
            }
#endif

            ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup
            
            // technically, we don't need this, newSetup refers to the same object as FusionStore 
            // but it's confusing since it isn't immediately obvious whether we have a ref or a copy
            AppDomainSetup adSetup = ad.FusionStore; 

#if FEATURE_CORECLR
            adSetup.InternalSetApplicationTrust(sandboxName);
#endif // FEATURE_CORECLR

#if !FEATURE_CORECLR  // not used by coreclr
            if (serializedEvidence != null) {
                EvidenceCollection evidenceCollection = (EvidenceCollection)
                    CrossAppDomainSerializer.DeserializeObject(new MemoryStream(serializedEvidence));
                providedSecurityInfo  = evidenceCollection.ProvidedSecurityInfo;
                creatorsSecurityInfo  = evidenceCollection.CreatorsSecurityInfo;
            }
#endif
            // set up the friendly name
            ad.nSetupFriendlyName(friendlyName);

#if FEATURE_COMINTEROP
            if (setup != null && setup.SandboxInterop)
            {
                ad.nSetDisableInterfaceCache();
            }
#endif // FEATURE_COMINTEROP

            // set up the AppDomainManager for this domain and initialize security.
            if (adSetup.AppDomainManagerAssembly != null && adSetup.AppDomainManagerType != null)
            {
                ad.SetAppDomainManagerType(adSetup.AppDomainManagerAssembly, adSetup.AppDomainManagerType);
            }

#if FEATURE_APTCA
            // set any conditial-aptca visible assemblies
            ad.PartialTrustVisibleAssemblies = adSetup.PartialTrustVisibleAssemblies;
#endif // FEATURE_APTCA

            ad.CreateAppDomainManager(); // could modify FusionStore's object
            ad.InitializeDomainSecurity(providedSecurityInfo,
                                        creatorsSecurityInfo,
                                        generateDefaultEvidence,
                                        parentSecurityDescriptor,
                                        true);
            
            // can load user code now
            if(initializerInfo!=null)
                adSetup.AppDomainInitializer=initializerInfo.Unwrap();
            RunInitializer(adSetup);

            // Activate the application if needed.
#if FEATURE_CLICKONCE 
            ObjectHandle oh = null;
            if (adSetup.ActivationArguments != null && adSetup.ActivationArguments.ActivateInstance)
                oh = Activator.CreateInstance(ad.ActivationContext);
            return RemotingServices.MarshalInternal(oh, null, null);
#else
            return null;
#endif // FEATURE_CLICKONCE
        }
Ejemplo n.º 31
0
		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() ) );
			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 );
			}
		}