Ejemplo n.º 1
0
        private static QuickCacheEntryType GenerateQuickCache(PolicyLevel level)
        {
            if (PolicyManager.FullTrustMap == null)
            {
                PolicyManager.FullTrustMap = new QuickCacheEntryType[5]
                {
                    QuickCacheEntryType.FullTrustZoneMyComputer,
                    QuickCacheEntryType.FullTrustZoneIntranet,
                    QuickCacheEntryType.FullTrustZoneTrusted,
                    QuickCacheEntryType.FullTrustZoneInternet,
                    QuickCacheEntryType.FullTrustZoneUntrusted
                }
            }
            ;
            QuickCacheEntryType quickCacheEntryType = (QuickCacheEntryType)0;
            Evidence            evidence1           = new Evidence();

            try
            {
                if (level.Resolve(evidence1).PermissionSet.IsUnrestricted())
                {
                    quickCacheEntryType |= QuickCacheEntryType.FullTrustAll;
                }
            }
            catch (PolicyException ex)
            {
            }
            foreach (SecurityZone zone in Enum.GetValues(typeof(SecurityZone)))
            {
                if (zone != SecurityZone.NoZone)
                {
                    Evidence evidence2 = new Evidence();
                    evidence2.AddHostEvidence <Zone>(new Zone(zone));
                    try
                    {
                        if (level.Resolve(evidence2).PermissionSet.IsUnrestricted())
                        {
                            quickCacheEntryType |= PolicyManager.FullTrustMap[(int)zone];
                        }
                    }
                    catch (PolicyException ex)
                    {
                    }
                }
            }
            return(quickCacheEntryType);
        }
    }
Ejemplo n.º 2
0
        public AppDomain CreateSandboxDomain(Plugin plugin, SecurityZone zone = SecurityZone.Untrusted)
        {
            var setup = new AppDomainSetup
            {
                ApplicationName = plugin.Name,
                ApplicationBase = Path.GetFullPath(Application.StartupPath),
                DynamicBase     = Path.GetFullPath((plugin.EntryType as Type).Assembly.Location)
            };
            var evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(zone));
            var permissions = GetPermissions(plugin, SecurityManager.GetStandardSandbox(evidence));
            var strongName  = typeof(PluginSandbox).Assembly.Evidence.GetHostEvidence <StrongName>();

            return(AppDomain.CreateDomain(plugin.Name, null, setup, permissions, strongName));
        }
        private static AppDomain CreateSandbox()
        {
            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.º 4
0
        private static AppDomain CreateDomain(string id, string assemblyPath)
        {
            var permSet = new PermissionSet(PermissionState.None);

            permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, assemblyPath));
            permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.PathDiscovery, assemblyPath));
            permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.PathDiscovery, Environment.CurrentDirectory));
            permSet.AddPermission(new EnvironmentPermission(EnvironmentPermissionAccess.Read, "InsideSandbox"));

            /*
             * Permissions for NUnit: see https://github.com/nunit/nunit/blob/master/src/NUnitFramework/tests/Assertions/LowTrustFixture.cs#L166
             * and https://github.com/nunit/nunit/issues/2792 for details
             */
            permSet.AddPermission(new ReflectionPermission(
                                      ReflectionPermissionFlag.MemberAccess));      // Required to instantiate classes that contain test code and to get cross-appdomain communication to work.
            permSet.AddPermission(new SecurityPermission(
                                      SecurityPermissionFlag.Execution |            // Required to execute test code
                                      SecurityPermissionFlag.SerializationFormatter // Required to support cross-appdomain test result formatting by NUnit TestContext
                                      ));

            /* In .NET <= 3.5 add following EnvironmentPermission:
             * permSet.AddPermission(new EnvironmentPermission(PermissionState.Unrestricted)); // Required for NUnit.Framework.Assert.GetStackTrace()
             */

            var evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.Untrusted));
            var fullyTrustAssemblies = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence <StrongName>();

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

            /* Copy CsSandboxer.exe to destination folder, because it's needed them to set domain.UnhandledException handler below. */
            var sandboxAssembly = typeof(Sandboxer).Assembly.Location;

            File.Copy(sandboxAssembly, Path.Combine(applicationBase, Path.GetFileName(sandboxAssembly)), overwrite: true);

            var domain = AppDomain.CreateDomain(id, evidence, adSetup, permSet, fullyTrustAssemblies);

            domain.UnhandledException += HandleException;
            return(domain);
        }
Ejemplo n.º 5
0
        internal void InitStore(IsolatedStorageScope scope, object domain, object assem, object app)
        {
            PermissionSet psAllowed = (PermissionSet)null;
            PermissionSet psDenied  = (PermissionSet)null;
            Evidence      domainEv  = (Evidence)null;
            Evidence      assemEv   = (Evidence)null;
            Evidence      appEv     = (Evidence)null;

            if (System.IO.IsolatedStorage.IsolatedStorage.IsApp(scope))
            {
                EvidenceBase evidence = app as EvidenceBase ?? (EvidenceBase) new LegacyEvidenceWrapper(app);
                appEv = new Evidence();
                appEv.AddHostEvidence <EvidenceBase>(evidence);
            }
            else
            {
                EvidenceBase evidence1 = assem as EvidenceBase ?? (EvidenceBase) new LegacyEvidenceWrapper(assem);
                assemEv = new Evidence();
                assemEv.AddHostEvidence <EvidenceBase>(evidence1);
                if (System.IO.IsolatedStorage.IsolatedStorage.IsDomain(scope))
                {
                    EvidenceBase evidence2 = domain as EvidenceBase ?? (EvidenceBase) new LegacyEvidenceWrapper(domain);
                    domainEv = new Evidence();
                    domainEv.AddHostEvidence <EvidenceBase>(evidence2);
                }
            }
            this._InitStore(scope, domainEv, (Type)null, assemEv, (Type)null, appEv, (Type)null);
            if (!System.IO.IsolatedStorage.IsolatedStorage.IsRoaming(scope))
            {
                RuntimeAssembly caller = System.IO.IsolatedStorage.IsolatedStorage.GetCaller();
                System.IO.IsolatedStorage.IsolatedStorage.GetControlEvidencePermission().Assert();
                // ISSUE: explicit reference operation
                // ISSUE: variable of a reference type
                PermissionSet& newGrant = @psAllowed;
                // ISSUE: explicit reference operation
                // ISSUE: variable of a reference type
                PermissionSet& newDenied = @psDenied;
                caller.GetGrantSet(newGrant, newDenied);
                if (psAllowed == null)
                {
                    throw new IsolatedStorageException(Environment.GetResourceString("IsolatedStorage_AssemblyGrantSet"));
                }
            }
            this.SetQuota(psAllowed, psDenied);
        }
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            if (args.Length > 0 && args[0] == "startui")
            {
                Application.Run(new Form1());
            }
            else
            {
                PermissionSet              permissions          = new PermissionSet(PermissionState.Unrestricted);
                string                     AppName              = Assembly.GetEntryAssembly().GetName().Name;
                string                     AppExe               = $"{AppName}.exe";
                string                     DebugSecurityZoneURL = $"{AppExe}.manifest";
                string                     AppManifestPath      = $"{AppName}.application";
                string                     appType              = "win32";
                AssemblyIdentity           ca = AssemblyIdentity.FromManifest(AppManifestPath);
                string                     appIdentitySubString = $"Version={ca.Version}, Culture={ca.Culture}, PublicKeyToken={ca.PublicKeyToken}, ProcessorArchitecture={ca.ProcessorArchitecture}";
                string                     assemblyIdentity     = $"http://tempuri.org/{AppManifestPath}#{AppManifestPath}, {appIdentitySubString}/{AppExe}, {appIdentitySubString},Type={appType}";
                System.ApplicationIdentity applicationIdentity  = new System.ApplicationIdentity(assemblyIdentity);

                ApplicationTrust appTrust = new ApplicationTrust();
                appTrust.DefaultGrantSet           = new PolicyStatement(permissions, PolicyStatementAttribute.Nothing);
                appTrust.IsApplicationTrustedToRun = true;
                appTrust.ApplicationIdentity       = applicationIdentity;

                AppDomainSetup adSetup = new AppDomainSetup
                {
                    ApplicationBase     = AppDomain.CurrentDomain.BaseDirectory,
                    ActivationArguments = new ActivationArguments(
                        ActivationContext.CreatePartialActivationContext(
                            applicationIdentity,
                            new string[] { AppManifestPath, DebugSecurityZoneURL })
                        ),
                    ApplicationTrust = appTrust
                };

                Evidence e = new Evidence();
                e.AddHostEvidence(appTrust);

                AppDomain a = AppDomain.CreateDomain("Internet Security Zone AppDomain", e, adSetup, permissions);
                a.ExecuteAssembly(AppExe, e, new string[] { "startui" });
            }
        }
Ejemplo n.º 7
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.º 8
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.º 9
0
        /// <summary>
        /// Creates a sandbox for testing.
        /// </summary>
        /// <param name="permissions">Additional permissions</param>
        /// <returns></returns>
        public static AppDomain SandboxCreator(IEnumerable <IPermission> permissions)
        {
            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);
            if (permissions != null)
            {
                foreach (IPermission permission in permissions)
                {
                    permSet.AddPermission(permission);
                }
            }
            // 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
        }
Ejemplo n.º 10
0
        static DotNetScriptHandler()
        {
            cParams = new CompilerParameters
            {
                GenerateExecutable      = false,
                GenerateInMemory        = false,
                IncludeDebugInformation = false,
                OutputAssembly          = ScriptOutputPath
            };
            cParams.ReferencedAssemblies.Add(Framework.DLLPath);
            cParams.ReferencedAssemblies.Add("System.dll");
            cParams.ReferencedAssemblies.Add("System.IO.dll");
            cParams.ReferencedAssemblies.Add("System.Drawing.dll");
            cParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            cParams.ReferencedAssemblies.Add("System.Xml.dll");

            var evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
        }
Ejemplo n.º 11
0
        private static TResult ExecuteInPartialTrust <TResult>(
            Func <MappingHelper, TResult> testFunc,
            Action <PermissionSet> permissionsSetup = null)
        {
            AppDomain partialTrustDomain = null;

            try
            {
                var evidence = new Evidence();
                evidence.AddHostEvidence(new Zone(SecurityZone.Internet));

                var permissions = new NamedPermissionSet(
                    "PartialTrust",
                    SecurityManager.GetStandardSandbox(evidence));

                permissionsSetup?.Invoke(permissions);

                partialTrustDomain = AppDomain.CreateDomain(
                    "PartialTrust",
                    evidence,
                    new AppDomainSetup {
                    ApplicationBase = "."
                },
                    permissions);

                var helperType = typeof(MappingHelper);

                // ReSharper disable once AssignNullToNotNullAttribute
                var helper = (MappingHelper)partialTrustDomain
                             .CreateInstanceAndUnwrap(helperType.Assembly.FullName, helperType.FullName);

                return(testFunc.Invoke(helper));
            }
            finally
            {
                if (partialTrustDomain != null)
                {
                    AppDomain.Unload(partialTrustDomain);
                }
            }
        }
Ejemplo n.º 12
0
        public void CannotGetThreadIdAndProcessidOnPartialTrustIfFullyTrusted()
        {
            var slabAssemblyName = typeof(EventEntry).Assembly.GetName();

            if (slabAssemblyName.GetPublicKeyToken().Length == 0)
            {
                Assert.Inconclusive("Can only be run if assemblies are signed");
            }

            var evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.Intranet));
            var permissionSet = SecurityManager.GetStandardSandbox(evidence);

            var appDomain =
                AppDomain.CreateDomain(
                    "partial trust",
                    evidence,
                    new AppDomainSetup {
                ApplicationBase = Environment.CurrentDirectory
            },
                    permissionSet,
                    new StrongName(new StrongNamePublicKeyBlob(slabAssemblyName.GetPublicKey()), slabAssemblyName.Name, slabAssemblyName.Version));

            try
            {
                var tester = (ProcessIdAndThreadIdTester)appDomain
                             .CreateInstanceAndUnwrap(
                    typeof(ProcessIdAndThreadIdTester).Assembly.GetName().Name,
                    typeof(ProcessIdAndThreadIdTester).FullName);

                var result = tester.GetProcessIdAndThreadIdThoughEvent();

                Assert.AreEqual(0, result.Item1);
                Assert.AreEqual(0, result.Item2);
            }
            finally
            {
                AppDomain.Unload(appDomain);
            }
        }
        private void DoTestWithPartialTrust(CrossAppDomainDelegate test)
        {
            var appDomainSetUp = new AppDomainSetup()
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };
            var evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
            var       permisions   = SecurityManager.GetStandardSandbox(evidence);
            AppDomain workerDomain = AppDomain.CreateDomain("PartialTrust", evidence, appDomainSetUp, permisions, GetStrongName(this.GetType()));

            try
            {
                workerDomain.DoCallBack(test);
            }
            finally
            {
                AppDomain.Unload(workerDomain);
            }
        }
        static DotNetScriptHandler()
        {
            Params = new CompilerParameters
            {
                GenerateExecutable      = false,
                GenerateInMemory        = false,
                IncludeDebugInformation = false,
                OutputAssembly          = ScriptOutputPath,
                ReferencedAssemblies    =
                {
                    Framework.Settings.DllPath,
                    "System.dll",
                    "System.Drawing.dll",
                    "System.Windows.Forms.dll",
                    "System.Xml.dll"
                }
            };

            Evidence = new Evidence();
            Evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
        }
Ejemplo n.º 15
0
        private void TestSerializationOnPartialTrust()
        {
            var appDomainSetUp = new AppDomainSetup()
            {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };
            var evidence = new Evidence();

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

                var target = workerDomain.GetData("MsgPack.GenericExceptionTester.Target") as T;
                Assert.That(target, Is.Not.Null);
                Assert.That(target.Message, Is.EqualTo(target.Message));
                Assert.That(target.InnerException, Is.Not.Null.And.TypeOf(typeof(Exception)));
                Assert.That(target.InnerException.Message, Is.EqualTo(target.InnerException.Message));
            }
            finally
            {
                AppDomain.Unload(workerDomain);
            }
        }
Ejemplo n.º 16
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;

            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);
            return(restrictedDomain);
        }
Ejemplo n.º 17
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.º 18
0
        /// <summary>We have to create seperate domain shizzle to prevent hackers from beeing able abuse our templating power. I would like to understand better how this works, just doing as told by this page now: https://antaris.github.io/RazorEngine/Isolation.html </summary>
        /// <returns>An AppDomain that you should use to execute the sandbox stuff.</returns>
        private static AppDomain SandboxCreator()
        {
            var evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.Internet));
            var permissionSet = SecurityManager.GetStandardSandbox(evidence);

            // You have to sign your assembly in order to get strong names (http://stackoverflow.com/questions/8349573/getting-null-from-gethostevidence)
            // But doing this results in:
            // Error	1	Assembly generation failed -- Referenced assembly 'RazorEngine' does not have a strong name	D:\git\presence-engine\RazorExperiment\CSC	RazorExperiment
            // Error	2	Assembly generation failed -- Referenced assembly 'Microsoft.AspNet.Razor' does not have a strong name	D:\git\presence-engine\RazorExperiment\CSC	RazorExperiment
            var razorEngineAssembly = typeof(RazorEngineService).Assembly.Evidence.GetHostEvidence <StrongName>();
            var razorAssembly       = typeof(RazorTemplateEngine).Assembly.Evidence.GetHostEvidence <StrongName>();

            var appDomainSetup = new AppDomainSetup();

            appDomainSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            var result = AppDomain.CreateDomain("Sandbox", null, appDomainSetup, permissionSet, razorEngineAssembly, razorAssembly);

            return(result);
        }
Ejemplo n.º 19
0
        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.º 20
0
        private static AppDomain CreateAppDomain(string name)
        {
            var evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.MyComputer));

            var securityManager = SecurityManager.GetStandardSandbox(evidence);

            securityManager.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
            securityManager.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.MemberAccess));
            securityManager.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, @"C:\"));

            var appDomainSetup = new AppDomainSetup()
            {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
            };
            var fullTrustAssemblies = SurfaceArea
                                      .GetAssemblies()
                                      .Select(x => x.Evidence.GetHostEvidence <StrongName>())
                                      .ToArray();

            return(AppDomain.CreateDomain(name + ":" + Guid.NewGuid(), null, appDomainSetup, securityManager, fullTrustAssemblies));
        }
Ejemplo n.º 21
0
        private AppDomain CreateSandboxedAppDomain(SandboxSecurityParameters securityParameters, string sandboxName)
        {
            PermissionSet securityManager = null;

            if (securityParameters.UseZoneSecurity)
            {
                var evidence = new Evidence();
                evidence.AddHostEvidence(securityParameters.ZoneSecurityEvidence);
                securityManager = SecurityManager.GetStandardSandbox(evidence);
            }
            else
            {
                //Use explicit permission security
                securityManager = securityParameters.AppDomainPermissions;
            }

            var appDomainSetup = new AppDomainSetup()
            {
                ApplicationBase = AppDomain.CurrentDomain.BaseDirectory
            };

            return(AppDomain.CreateDomain(sandboxName, null, appDomainSetup, securityManager, securityParameters.FullTrustAssemblies));
        }
Ejemplo n.º 22
0
        private AppDomain BuildSandbox()
        {
            //Setting the AppDomainSetup. It is very important to set the ApplicationBase to a folder
            //other than the one in which the sandboxer resides.
            AppDomainSetup adSetup = new AppDomainSetup();

            adSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
            adSetup.ApplicationName = "FrEee";
            adSetup.DynamicBase     = "ScriptEngine";

            //Setting the permissions for the AppDomain. We give the permission to execute and to
            //read/discover the location where the untrusted code is loaded.
            var evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.MyComputer));
            var permissions = SecurityManager.GetStandardSandbox(evidence);
            var reflection  = new ReflectionPermission(PermissionState.Unrestricted);

            permissions.AddPermission(reflection);

            //Now we have everything we need to create the AppDomain, so let's create it.
            return(AppDomain.CreateDomain("Test", null, adSetup, permissions, AppDomain.CurrentDomain.GetAssemblies().Select(a => a.Evidence.GetHostEvidence <StrongName>()).Where(sn => sn != null).ToArray()));
        }
        private static void ExecuteInPartialTrust(Action <TranslationHelper> testAction)
        {
            AppDomain partialTrustDomain = null;

            try
            {
                var evidence = new Evidence();
                evidence.AddHostEvidence(new Zone(SecurityZone.Internet));

                var permissions = new NamedPermissionSet(
                    "PartialTrust",
                    SecurityManager.GetStandardSandbox(evidence));

                partialTrustDomain = AppDomain.CreateDomain(
                    "PartialTrust",
                    evidence,
                    new AppDomainSetup {
                    ApplicationBase = "."
                },
                    permissions);

                var helperType = typeof(TranslationHelper);

                // ReSharper disable once AssignNullToNotNullAttribute
                var helper = (TranslationHelper)partialTrustDomain
                             .CreateInstanceAndUnwrap(helperType.Assembly.FullName, helperType.FullName);

                testAction.Invoke(helper);
            }
            finally
            {
                if (partialTrustDomain != null)
                {
                    AppDomain.Unload(partialTrustDomain);
                }
            }
        }
Ejemplo n.º 24
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.º 25
0
        public object executeAssembly(string assemblyName, Loader codeLoader, object param)
        {
            Evidence e = new Evidence();

            e.AddHostEvidence(new Zone(SecurityZone.Intranet));
            PermissionSet permSet = SecurityManager.GetStandardSandbox(e);

            AppDomainSetup ads = new AppDomainSetup();

            ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
            AppDomain tempDomain = AppDomain.CreateDomain(assemblyName + new Random().NextDouble(), e, ads, permSet, null);

            tempDomain.Load("CodeInterface");

            ObjectHandle handle = Activator.CreateInstanceFrom(tempDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandboxer).FullName);

            Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();

            byte[] assemblyBinary = codeLoader.codeDictionary.ReadAssembly(assemblyName);

            object output = newDomainInstance.ExecuteNewAssembly(assemblyBinary, param);

            return(output);
        }
Ejemplo n.º 26
0
        public HandlerDataEngine(GameHandlerMetadata metadata, string jsCode)
        {
            this.metadata = metadata;
            this.jsCode   = jsCode;

            string tempPath = GameManager.GetTempFolder(metadata.GameID);

            Assembly platform = Assembly.GetExecutingAssembly();

            Evidence evidence = new Evidence();

            evidence.AddHostEvidence(new Zone(SecurityZone.Untrusted));

            PermissionSet permissionSet = new PermissionSet(PermissionState.None);

            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Write, tempPath));
            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, metadata.RootDirectory));
            permissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, AssemblyUtil.GetStartFolder()));
            permissionSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            AppDomainSetup setup = new AppDomainSetup {
                ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase
            };

            domain = AppDomain.CreateDomain("JSENGINE", evidence, setup, permissionSet);

            string enginePath = GetLibraryPath();

            byte[] engineData = File.ReadAllBytes(enginePath);
            domain.Load(engineData);

            ObjectHandle jsobj = domain.CreateInstance("Nucleus.Gaming.Coop.Engine", "Nucleus.Gaming.Coop.Engine.AppDomainEngine");

            jsEngine = jsobj.Unwrap();
            // TODO: strong typing on dynamic object (cache the fields/use reflection)
        }
Ejemplo n.º 27
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()), GetStrongName(typeof(Assert)));
            try
            {
                workerDomain.DoCallBack(TestEqualsWorker);

#if !MONO
                // P/Invoke is not disabled on Mono even if in the InternetZone.
                Assert.That(( bool )workerDomain.GetData("MessagePackString.IsFastEqualsDisabled"), Is.True);
#endif // if !MONO
                Console.WriteLine("TestEqualsPartialTrust");
                ShowResult(workerDomain.GetData("TestEqualsWorker.Performance") as Tuple <double, double, double, double>);
            }
            finally
            {
                AppDomain.Unload(workerDomain);
            }
        }
Ejemplo n.º 28
0
        public static void ExecuteInMediumTrust(MethodInfo methodInfo, object parameter)
        {
#if !MEDIUM_TRUST
            Assert.Inconclusive("Medium trust is only valid for signed builds");
#endif

            Type type = methodInfo.DeclaringType;

            // Instance methods are not supported because in common use, caller is in full trust
            if (!methodInfo.IsStatic)
            {
                throw new ArgumentException("The method " + type.Name + "." + methodInfo.Name + " must be static");
            }

            if (methodInfo.GetParameters().Length > 1)
            {
                throw new ArgumentException("The method " + type.Name + "." + methodInfo.Name + " accepts an unexpected number of parameters");
            }

            string methodName     = methodInfo.Name;
            string typeName       = methodInfo.DeclaringType.FullName;
            string assemblyName   = methodInfo.DeclaringType.Assembly.FullName;
            string pathToAssembly = methodInfo.DeclaringType.Assembly.Location;

            // TODO (wilcob, roncain): Parse web_mediumtrust.config for a 100% correct sandboxed appdomain.
            // Use Intranet permission because that is how our framework is run in ASP.NET
            Evidence evidence = new Evidence();
            evidence.AddHostEvidence(new Zone(SecurityZone.Intranet));

            PermissionSet permSet = SecurityManager.GetStandardSandbox(evidence);

            // We want the sandboxer assembly's strong name, so that we can add it to the full trust list
            StrongName sandBoxAssembly = typeof(SandBoxer).Assembly.Evidence.GetHostEvidence <StrongName>();

            AppDomainSetup adSetup = new AppDomainSetup();
            adSetup.ApplicationBase = Path.GetFullPath(pathToAssembly);

            // We need the following to be fully trusted:
            //  SandBoxer: does Reflection to invoke down to partial trust
            StrongName[] fullTrustAssemblies = new StrongName[] {
                sandBoxAssembly,
            };

            // DataAnnotations is in the GAC and will run full trust unless we ask otherwise
            string[] partialTrustAssemblies = new string[] {
                typeof(System.ComponentModel.DataAnnotations.ValidationAttribute).Assembly.FullName,
            };

            adSetup.PartialTrustVisibleAssemblies = partialTrustAssemblies;

            AppDomain newDomain = AppDomain.CreateDomain("SandBox", null, adSetup, permSet, fullTrustAssemblies);

            // Use CreateInstanceFrom to load an instance of the Sandboxer class into the new AppDomain.
            ObjectHandle handle = Activator.CreateInstanceFrom(
                newDomain, typeof(SandBoxer).Assembly.ManifestModule.FullyQualifiedName,
                typeof(SandBoxer).FullName
                );

            // Unwrap the new domain instance into an reference in this domain and use it to
            // execute the untrusted code
            SandBoxer newDomainInstance = handle.Unwrap() as SandBoxer;
            Exception exception         = null;

            try
            {
                newDomainInstance.ExecuteUntrustedCode(assemblyName, typeName, methodName, parameter);
            }
            catch (TargetInvocationException tie)
            {
                exception = tie.InnerException == null ? tie : tie.InnerException;
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                throw (exception is AssertFailedException)
                          ? exception
                          : new AssertFailedException(exception.Message, exception);
            }
        }
Ejemplo n.º 29
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>
        /// <param name="ads"></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 LINUX
        #pragma warning disable 612, 618
            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);
        #pragma warning restore 612, 618
#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.º 30
0
    // The entry point for the code example.
    static void Main()
    {
        // Get the display name of the executing assembly, to use when
        // creating objects to run code in application domains.
        //<Snippet14>
        String asmName = typeof(Worker).Assembly.FullName;
        //</Snippet14>

        // Create the permission set to grant to other assemblies. In this
        // case they are the permissions found in the Internet zone.
        //<Snippet2>
        Evidence ev = new Evidence();

        ev.AddHostEvidence(new Zone(SecurityZone.Internet));
        PermissionSet pset = new NamedPermissionSet("Internet", SecurityManager.GetStandardSandbox(ev));
        //</Snippet2>

        // For simplicity, set up the application domain to use the
        // current path as the application folder, so the same executable
        // can be used in both trusted and untrusted scenarios. Normally
        // you would not do this with real untrusted code.
        //<Snippet3>
        AppDomainSetup adSetup = new AppDomainSetup();

        adSetup.ApplicationBase = ".";
        //</Snippet3>

        // Create an application domain in which all code that executes is
        // granted the permissions of an application run from the Internet.
        //<Snippet5>
        AppDomain ad = AppDomain.CreateDomain("Sandbox", ev, adSetup, pset, null);
        //</Snippet5>

        // Create an instance of the Worker class in the partially trusted
        // domain. Note: If you build this code example in Visual Studio,
        // you must change the name of the class to include the default
        // namespace, which is the project name. For example, if the project
        // is "AnonymouslyHosted", the class is "AnonymouslyHosted.Worker".
        //<Snippet12>
        Worker w = (Worker)ad.CreateInstanceAndUnwrap(asmName, "Worker");

        //</Snippet12>

        // Emit a simple dynamic method that prints "Hello, World!"
        //<Snippet13>
        w.SimpleEmitDemo();
        //</Snippet13>

        // Emit and invoke a dynamic method that calls a private method
        // of Worker, with JIT visibility checks enforced. The call fails
        // when the delegate is invoked.
        w.AccessPrivateMethod(false);

        // Emit and invoke a dynamic method that calls a private method
        // of Worker, skipping JIT visibility checks. The call fails when
        // the method is invoked.
        w.AccessPrivateMethod(true);


        // Unload the application domain. Add RestrictedMemberAccess to the
        // grant set, and use it to create an application domain in which
        // partially trusted code can call private members, as long as the
        // trust level of those members is equal to or lower than the trust
        // level of the partially trusted code.
        AppDomain.Unload(ad);
        //<Snippet7>
        pset.SetPermission(
            new ReflectionPermission(
                ReflectionPermissionFlag.RestrictedMemberAccess));
        //</Snippet7>
        //<Snippet8>
        ad = AppDomain.CreateDomain("Sandbox2", ev, adSetup, pset, null);
        //</Snippet8>

        // Create an instance of the Worker class in the partially trusted
        // domain.
        w = (Worker)ad.CreateInstanceAndUnwrap(asmName, "Worker");

        // Again, emit and invoke a dynamic method that calls a private method
        // of Worker, skipping JIT visibility checks. This time compilation
        // succeeds because of the grant for RestrictedMemberAccess.
        w.AccessPrivateMethod(true);

        // Finally, emit and invoke a dynamic method that calls an internal
        // method of the String class. The call fails, because the trust level
        // of the assembly that contains String is higher than the trust level
        // of the assembly that emits the dynamic method.
        w.AccessPrivateMethod();
    }