예제 #1
0
        public static AppDomain CreateSandbox(string sandboxName)
        {
            //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 = "NOT_A_PATH";
            // Do not search the application base directory at all
            adSetup.DisallowApplicationBaseProbing = true;

            // With the restrictions we have this should never work anyway.
            // But let's set it in case future versions allow some sort of network access...
            adSetup.DisallowCodeDownload = true;

            //Setting the permissions for the AppDomain. We give the permission to execute and to
            //read/discover the location where the untrusted code is loaded.
            PermissionSet permSet = new PermissionSet(PermissionState.None);

            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

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

            //Now we have everything we need to create the AppDomain, so let's create it.
            AppDomain domain = AppDomain.CreateDomain(sandboxName, null, adSetup, permSet, fullTrustAssembly);

            AppDomain.MonitoringIsEnabled = true;

            return(domain);
        }
예제 #2
0
        /// <summary>
        /// Initialise the app domain.
        /// </summary>
        /// <param name="path">The path to the assemblies.</param>
        /// <param name="configurationFile">The configuration file name.</param>
        public override void Initialise(string path, string configurationFile = null)
        {
            // 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 = Path.GetFullPath(path);

            // Get the configuration file.
            if (!String.IsNullOrEmpty(configurationFile))
            {
                adSetup.ConfigurationFile = configurationFile;
            }

            // Setting the permissions for the AppDomain. We give the permission to execute and to
            // read/discover the location where the untrusted code is loaded.
            PermissionSet permSet = new PermissionSet(PermissionState.None);

            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

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

            // Create the application loader.
            AppDomianLoader loader = new AppDomianLoader()
                                     .DomainFriendlyName(DateTime.Now.ToString(DateTimeFormatInfo.InvariantInfo).GetHashCode().ToString("x"))
                                     .AppDomainSetup(adSetup)
                                     .PermissionSet(permSet);

            // Create the app domain.
            base.AppDomain = loader.CreateAppDomain();

            // Load the domain.
            base.Instance = AppDomianLoader.Load <Sandbox>(base.AppDomain);
        }
예제 #3
0
        static int Main()
        {
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
//				Console.WriteLine("Switching to secound AppDomain, for RazorEngine...");
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var current = AppDomain.CurrentDomain;
                // You only need to add strongnames when your appdomain is not a full trust environment.
                var strongNames = new StrongName[0];

                var domain = AppDomain.CreateDomain(
                    "MyMainDomain", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
                    strongNames);
                return(domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location));
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var generator = new Generator();

            generator.Initialize();

            var frm = new frmCodeGen();

            frm.Generator = generator;

            Application.Run(frm);

            return(0);
        }
예제 #4
0
        public void ApplicationInitialise(string txtAppPath, string txtAppParam, PermissionSet permSet)
        {
            string appFilePath = Path.GetDirectoryName(txtAppPath);

            string[] appFileParam    = txtAppParam.Split(' ');
            string   appAssemblyName = Path.GetFileNameWithoutExtension(txtAppPath);

            // Application Domain Setup
            AppDomainSetup adSetup = new AppDomainSetup();

            adSetup.ApplicationBase = appFilePath;

            // Strong Name using 'Sandboxer_Key.snk'
            StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence <StrongName>();

            // Create Application Domain with a random 'ID' value so not all sandbox domains are the same
            Random    rnd       = new Random();
            AppDomain newDomain = AppDomain.CreateDomain("Sandbox" + rnd.Next().ToString(), null, adSetup, permSet, fullTrustAssembly);

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

            // Execute Application code
            Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();

            Console.WriteLine("--- {0} STARTED ---", appAssemblyName);
            newDomain.ExecuteAssembly(txtAppPath, appFileParam);
            Console.WriteLine("--- {0} FINISHED ---\n", appAssemblyName);
        }
예제 #5
0
        static int Main(string[] args)
        {
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
                Console.WriteLine("Switching to secound AppDomain, for RazorEngine...");
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var current = AppDomain.CurrentDomain;
                // You only need to add strongnames when your appdomain is not a full trust environment.
                var strongNames = new StrongName[0];

                var razorEngineDomain = AppDomain.CreateDomain("MyRazorEngineDomain", null, current.SetupInformation, new PermissionSet(PermissionState.Unrestricted), strongNames);
                var exitCode          = razorEngineDomain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);

                // RazorEngine will cleanup.
                AppDomain.Unload(razorEngineDomain);

                return(exitCode);
            }

            // int returnCode = SimpleWelcomeTemplate();
            // int returnCode = WelcomeWithViewModelTemplate();
            int returnCode = WelcomeWithLinkedViewModelTemplate();

            //int returnCode = RunMultipleTimes(WelcomeWithViewModelTemplate, 10, 20);
            //Console.WriteLine("====== ===== ==== ===== ===== ===== ===== ===== ===== ==== =====");
            //Thread.Sleep(1000);
            //returnCode = RunMultipleTimes(WelcomeWithLinkedViewModelTemplate, 10, 20);

            Console.ReadLine();

            return(returnCode);
        }
예제 #6
0
            //------------------------------------------------------------------
            //----------Implementation Code-------------------------------------
            //------------------------------------------------------------------

            /// <summary>
            /// Initialise session, execution is deffered.
            /// </summary>
            /// <param name="permissions"></param>
            /// <param name="ex_path"></param>
            /// <param name="arguments"></param>
            public Session(PermissionSet permissions, string ex_path,
                           string[] arguments, string jail_path = null)
            {
                mPermissions    = permissions;
                mExecutablePath = ex_path;
                mArgumentList   = arguments;

                if (jail_path == null)
                {
                    mAppDomainSetup.ApplicationBase = cdDotDot(mExecutablePath);
                }
                else
                {
                    mAppDomainSetup.ApplicationBase = jail_path;
                }

                StrongName fullTrustAssembly = typeof(Session)
                                               .Assembly.Evidence.GetHostEvidence <StrongName>();

                mDomain = AppDomain.CreateDomain(
                    "Sandbox",
                    null,
                    mAppDomainSetup,
                    mPermissions,
                    fullTrustAssembly);
            }
예제 #7
0
        public void AddFullTrustAssembly_NullStrongName()
        {
            PolicyLevel pl = Load(minimal, PolicyLevelType.Machine);
            StrongName  sn = null;

            pl.AddFullTrustAssembly(sn);
        }
예제 #8
0
        public static IUnloadablePluginContainer <TPlugin> Load <TPlugin>(
            string domainName,
            string assemblyFullPath,
            AppDomainSetup setup,
            PermissionSet permissions)
        {
            StrongName fullTrustAssembly = typeof(PluginLoader).Assembly.Evidence.GetHostEvidence <StrongName>();

            AppDomain domain = AppDomain.CreateDomain(
                domainName,
                null,
                setup,
                permissions,
                fullTrustAssembly);

            string       assemblyPath = typeof(PluginLoader).Assembly.ManifestModule.FullyQualifiedName;
            PluginLoader loader       = (PluginLoader)Activator.CreateInstanceFrom(domain, assemblyPath, typeof(PluginLoader).FullName).Unwrap();

            TPlugin      instance = (TPlugin)loader.LoadPlugin(assemblyFullPath, typeof(TPlugin).AssemblyQualifiedName);
            AssemblyName name     = loader.GetPluginAssemblyName();

            var container = new PluginContainer <TPlugin>(domain, loader, name, instance);

            return(container);
        }
예제 #9
0
        /// <summary>
        ///     Create a homogenous AppDomain rooted at the specified AppBase, which has an optional
        ///     collection of full trust assemblies
        /// </summary>
        /// <param name="applicationBase">location where the application to be sandboxed lives</param>
        /// <param name="grantSet">permissions to grant the sandbox</param>
        /// <param name="fullTrustAssemblies">optional list of assemblies to grant full trust in the sandbox</param>
        /// <exception cref="ArgumentNullException">
        ///     if <paramref name="applicationBase"/> or <paramref name="grantSet"/> are null
        /// </exception>
        public static AppDomain CreateSandbox(string applicationBase,
                                              PermissionSet grantSet,
                                              params Assembly[] fullTrustAssemblies)
        {
            if (applicationBase == null)
            {
                throw new ArgumentNullException("applicationBase");
            }
            if (grantSet == null)
            {
                throw new ArgumentNullException("grantSet");
            }

            IEnumerable <StrongName> fullTrustStrongNames = null;

            if (fullTrustAssemblies != null)
            {
                fullTrustStrongNames = from assembly in fullTrustAssemblies
                                       select assembly.GetStrongName();
            }
            else
            {
                fullTrustStrongNames = new StrongName[0];
            }

            AppDomainSetup setupInfo = new AppDomainSetup();

            setupInfo.ApplicationBase = applicationBase;

            return(AppDomain.CreateDomain("Sandbox", null, setupInfo, grantSet, fullTrustStrongNames.ToArray()));
        }
예제 #10
0
        /// <summary>
        /// return the appdomain with permission set in medium trust level
        /// </summary>
        /// <returns> appdomain</returns>
        private AppDomain GetCustomizedAppDomain()
        {
            AppDomainSetup setup = new AppDomainSetup {
                ApplicationBase = Environment.CurrentDirectory
            };

            setup.AppDomainInitializer = SetupAppDomain;
            var          ps      = new PermissionSet(PermissionState.None);
            StreamReader fs      = new StreamReader("AstoriaClientTest_MediumTrustPermissionSet.xml");
            string       strPerm = fs.ReadToEnd();

            strPerm = strPerm.Replace("$AppDir$", Environment.CurrentDirectory);
            ps.FromXml(SecurityElement.FromString(strPerm));
            AddPermissionByTest(ps);

            StrongName framework  = Assembly.GetExecutingAssembly().Evidence.GetHostEvidence <StrongName>();
            StrongName moduleCore = typeof(TestItem).Assembly.Evidence.GetHostEvidence <StrongName>();
            StrongName kokomo     = typeof(ModelEngineOptions).Assembly.Evidence.GetHostEvidence <StrongName>();

            StrongName[] sn = { framework, moduleCore, kokomo };

            AppDomain myDomain = AppDomain.CreateDomain("myDomain", null, setup, ps, sn);

            return(myDomain);
        }
예제 #11
0
        private static PluginSandBox GetPluginSandBox()
        {
            AppDomainSetup adSetup     = new AppDomainSetup();
            var            sandBoxPath = Path.GetFullPath(pathToPlugin);

            adSetup.ApplicationBase = sandBoxPath;

            //Setting the permissions for the AppDomain. We give the permission to execute and to
            //read/discover the location where the untrusted code is loaded.
            PermissionSet permSet = new PermissionSet(PermissionState.None);

            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

            FileIOPermission fp = new FileIOPermission(
                FileIOPermissionAccess.Read |
                FileIOPermissionAccess.PathDiscovery, sandBoxPath);        //read permissions set only to plugin directory


            permSet.AddPermission(fp);
            StrongName fullTrustAssembly = typeof(PluginSandBox).Assembly.Evidence.GetHostEvidence <StrongName>();
            AppDomain  sandBoxDomain     = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);

            //TODO this way we could pass the path right to the constructor
            //var pSandBox = (PluginSandBox)sandBoxDomain.CreateInstanceAndUnwrap(typeof(PluginSandBox).Assembly.ManifestModule.FullyQualifiedName,
            //typeof(PluginSandBox).FullName, new[] { sandBoxPath });

            ObjectHandle handle = Activator.CreateInstanceFrom(sandBoxDomain, typeof(PluginSandBox).Assembly.ManifestModule.FullyQualifiedName,
                                                               typeof(PluginSandBox).FullName);
            PluginSandBox pSandBox = (PluginSandBox)handle.Unwrap();

            pSandBox.InitPlugin(sandBoxPath);
            return(pSandBox);
        }
예제 #12
0
        static void Main(string[] args)
        {
            // perfTest(); return;

            // https://github.com/Antaris/RazorEngine/issues/244#issuecomment-85507351
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
                Console.WriteLine("Switching to second AppDomain, for RazorEngine");
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var current = AppDomain.CurrentDomain;
                // You only need to add strongnames when your appdomain is not a full trust environment.
                var strongNames = new StrongName[0];

                var domain = AppDomain.CreateDomain(
                    "MyMainDomain", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
                    strongNames);
                domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);
                return;
            }

            try
            {
                mainImpl(makeCppWrappers);
                Console.WriteLine("Press any key to continue.");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed: {0}", ex.Message);
                Console.WriteLine(ex.ToString());
            }
        }
예제 #13
0
        // -strong -file filename [name | -noname] [version | -noversion]
        static IMembershipCondition ProcessStrongNameMembership(string[] args, ref int i)
        {
            if (args [++i] != "-file")
            {
                Console.WriteLine("Missing -file parameter.");
                return(null);
            }

            StrongName sn = GetStrongName(args [++i]);

            string name = args [++i];

            if (name == "-noname")
            {
                name = null;
            }

            Version v       = null;
            string  version = args [++i];

            if (version != "-noversion")
            {
                v = new Version(version);
            }

            return(new StrongNameMembershipCondition(sn.PublicKey, name, v));
        }
예제 #14
0
        static void Main(string[] args)
        {
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
                Console.WriteLine("Switching to second AppDomain, for RazorEngine...");
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var current = AppDomain.CurrentDomain;
                // You only need to add strongnames when your appdomain is not a full trust environment.
                var strongNames = new StrongName[0];

                var domain = AppDomain.CreateDomain(
                    "ConsoleTest", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
                    strongNames);

                var exitCode = domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location);

                // RazorEngine will cleanup.
                AppDomain.Unload(domain);
            }

            SendTestMail();
            Console.ReadLine();
        }
예제 #15
0
        // modified copy from sn
        private static VerificationResult VerifyStrongName(AssemblyName an, string assemblyFile)
        {
            byte [] publicKey = StrongNameManager.GetMappedPublicKey(an.GetPublicKeyToken());
            if ((publicKey == null) || (publicKey.Length < 12))
            {
                // no mapping
                publicKey = an.GetPublicKey();
                if ((publicKey == null) || (publicKey.Length < 12))
                {
                    return(VerificationResult.WeakNamed);
                }
            }

            // Note: MustVerify is based on the original token (by design). Public key
            // remapping won't affect if the assembly is verified or not.
            if (StrongNameManager.MustVerify(new System.Reflection.AssemblyName(an.FullName)))
            {
                RSA        rsa = CryptoConvert.FromCapiPublicKeyBlob(publicKey, 12);
                StrongName sn  = new StrongName(rsa);
                if (sn.Verify(assemblyFile))
                {
                    return(VerificationResult.StrongNamed);
                }
                else
                {
                    return(VerificationResult.DelaySigned);
                }
            }
            else
            {
                return(VerificationResult.Skipped);
            }
        }
예제 #16
0
파일: Host.cs 프로젝트: mikh/527_Project
    static void Main()
    {
        //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 = Path.GetFullPath(pathToUntrusted);

        //Setting the permissions for the AppDomain. We give the permission to execute and to
        //read/discover the location where the untrusted code is loaded.
        PermissionSet permSet = new PermissionSet(PermissionState.None);

        permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

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

        //Now we have everything we need to create the AppDomain, so let's create it.
        AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);

        //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 a reference in this domain and use it to execute the
        //untrusted code.
        Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();

        newDomainInstance.ExecuteUntrustedCode(untrustedAssembly, untrustedClass, entryPoint, parameters);
    }
예제 #17
0
        private static Assembly LoadAndVerifyAssemblyInternal(byte[] assemblyData)
        {
            Assembly assembly = Assembly.Load(assemblyData);

            byte[] publicKey = assembly.GetName().GetPublicKey();
            if (publicKey == null || publicKey.Length == 0)
            {
                return(null);
            }
            RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider();

            rSACryptoServiceProvider.ImportCspBlob(publicKey);
            StrongName strongName = new StrongName(rSACryptoServiceProvider);
            Assembly   result;

            using (MemoryStream memoryStream = new MemoryStream(assemblyData))
            {
                if (strongName.Verify(memoryStream))
                {
                    Security._verifiedAssemblies.Add(assembly);
                    result = assembly;
                }
                else
                {
                    result = null;
                }
            }
            return(result);
        }
예제 #18
0
        public void CreateMembershipConditionTest()
        {
            StrongName[] strongNames = new StrongName[]
            {
                typeof(object).Assembly.GetStrongName(),
                typeof(System.Security.Cryptography.AesManaged).Assembly.GetStrongName(),
                typeof(System.Security.Cryptography.Xml.SignedXml).Assembly.GetStrongName()
            };

            for (int i = 0; i < strongNames.Length; ++i)
            {
                StrongNameMembershipCondition mc = strongNames[i].CreateMembershipCondition();

                for (int j = 0; j < strongNames.Length; ++j)
                {
                    Evidence evidence = new Evidence(new object[] { strongNames[j] }, new object[0]);

                    if (i == j)
                    {
                        Assert.IsTrue(mc.Check(evidence));
                    }
                    else
                    {
                        Assert.IsFalse(mc.Check(evidence));
                    }
                }
            }
        }
예제 #19
0
        public void RemoveFullTrustAssembly_UnknownStrongName()
        {
            PolicyLevel pl = Load(minimal, PolicyLevelType.Machine);
            StrongName  sn = new StrongName(new StrongNamePublicKeyBlob(snPublicKey), "First", new Version(1, 2, 3, 4));

            pl.RemoveFullTrustAssembly(sn);
        }
예제 #20
0
        public static SandboxInstance CreateSandbox(string applicationBase, SecurityZone securityZone)
        {
            Type           typeOfSandbox  = typeof(SandboxInstance);
            AppDomainSetup appDomainSetup = ObjectFactory.GetInstance <AppDomainSetup>();
            Evidence       evidence       = ObjectFactory.GetInstance <Evidence>();
            Zone           zone           = new Zone(securityZone);

            appDomainSetup.ApplicationBase = applicationBase;
            evidence.AddHostEvidence(zone);

            PermissionSet permissionSet     = SecurityManager.GetStandardSandbox(evidence);
            StrongName    fullTrustAssembly = typeOfSandbox.Assembly.Evidence.GetHostEvidence <StrongName>();
            AppDomain     appDomain         = AppDomain.CreateDomain(
                FrienldyName,
                evidence,
                appDomainSetup,
                permissionSet,
                fullTrustAssembly);

            ObjectHandle handle = Activator.CreateInstanceFrom(
                appDomain,
                typeOfSandbox.Assembly.ManifestModule.FullyQualifiedName,
                typeOfSandbox.FullName);

            return(handle.Unwrap() as SandboxInstance);
        }
예제 #21
0
        static void Main(string[] args)
        {
            if (AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                // RazorEngine cannot clean up from the default appdomain...
                AppDomainSetup adSetup = new AppDomainSetup();
                adSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                var current = AppDomain.CurrentDomain;
                // You only need to add strongnames when your appdomain is not a full trust environment.
                var strongNames = new StrongName[0];

                var domain = AppDomain.CreateDomain(
                    "MyMainDomain", null,
                    current.SetupInformation, new PermissionSet(PermissionState.Unrestricted),
                    strongNames);
                var exitCode = domain.ExecuteAssembly(Assembly.GetExecutingAssembly().Location, args);
                // RazorEngine will cleanup.
                AppDomain.Unload(domain);
                //return exitCode;
            }
            else
            {
                MainAsync(args).GetAwaiter().GetResult();
            }
        }
예제 #22
0
    static void Main(String[] args)
    {
        if (args.Length < 2)
        {
            Console.WriteLine("Usage: sandbox <directory> <assembly> [allowed_files ...]");
            return;
        }

        AppDomainSetup adSetup = new AppDomainSetup();

        adSetup.ApplicationBase = Path.GetFullPath(args[0]);

        PermissionSet permSet = new PermissionSet(PermissionState.None);

        permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
        permSet.AddPermission(new ReflectionPermission(ReflectionPermissionFlag.RestrictedMemberAccess));
        permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, Path.GetFullPath(args[1])));

        for (int i = 2; i < args.Length; ++i)
        {
            permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.PathDiscovery, args[i]));
        }

        StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence <StrongName>();

        AppDomain    newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);
        ObjectHandle handle    = Activator.CreateInstanceFrom(
            newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName,
            typeof(Sandboxer).FullName
            );
        Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();

        Environment.Exit(newDomainInstance.ExecuteUntrustedCode(Path.GetFullPath(args[1])));
    }
        /// <summary>
        /// Creates a sandbox for testing.
        /// </summary>
        /// <returns></returns>
        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
        }
예제 #24
0
        //[SecurityCritical]
        public static void TesteNoGAC()
        {
            //create the AppDomainSetup
            AppDomainSetup info = new AppDomainSetup();

            //set the path to the assembly to load.
            info.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            Assembly   a     = Assembly.LoadFile(Path.Combine(info.ApplicationBase, "CAS_01.dll"));
            StrongName sName = a.Evidence.GetHostEvidence <StrongName>();
            //StrongName fullTrustAssembly = typeof(AssemblyInfo).Assembly.Evidence.GetHostEvidence<StrongName>();
            //create the domain
            AppDomain domain = AppDomain.CreateDomain(
                "CasHostDemo", null, info, GetPermissionSet(), new StrongName[] { sName });

            //create an instance of the AseemblyInfo class
            Type         t      = typeof(AssemblyInfo);
            ObjectHandle handle = Activator.CreateInstanceFrom(
                domain,
                t.Assembly.ManifestModule.FullyQualifiedName,
                t.FullName);
            AssemblyInfo ai = (AssemblyInfo)handle.Unwrap();

            Console.WriteLine("DOMAIN INFO:\n");
            //get the domain info
            Console.WriteLine(GetDomainInfo(domain));

            Console.WriteLine("ASSEMBLY INFO:\n");
            //get the assembly info form the sandboxed assembly
            Console.WriteLine(ai.GetCasSecurityAttributes());
        }
예제 #25
0
        public void AddFullTrustAssembly_DuplicateStrongName()
        {
            PolicyLevel pl = Load(minimal, PolicyLevelType.Machine);
            StrongName  sn = new StrongName(new StrongNamePublicKeyBlob(snPublicKey), "First", new Version(1, 2, 3, 4));

            pl.AddFullTrustAssembly(sn);
            pl.AddFullTrustAssembly(sn);
        }
예제 #26
0
 public void AddFullTrustModuleInSandboxAppDomain(StrongName assemblyName)
 {
     if (assemblyName == null)
     {
         throw new ArgumentNullException("assemblyName");
     }
     this.m_reportRuntimeSetupHandler.AddFullTrustModuleInSandboxAppDomain(assemblyName);
 }
예제 #27
0
 public void AddFullTrustAssembly(StrongName assemblyName)
 {
     if (this.m_fullTrustAssemblies == null)
     {
         this.m_fullTrustAssemblies         = new List <StrongName>();
         this.m_fullTrustAssembliesReadOnly = new ReadOnlyCollection <StrongName>(this.m_fullTrustAssemblies);
     }
     this.m_fullTrustAssemblies.Add(assemblyName);
 }
예제 #28
0
        ///////////////////////////////////////////////////////////////////////

        public static ReturnCode GetStrongName(
            Assembly assembly,
            ref StrongName strongName
            )
        {
            Result error = null;

            return(GetStrongName(assembly, ref strongName, ref error));
        }
        public void StrongName_GetRequiredSize()
        {
            byte[] pk = { 0x00, 0x24, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x94, 0x00, 0x00, 0x00, 0x06, 0x02, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x52, 0x53, 0x41, 0x31, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x3D, 0xBD, 0x72, 0x08, 0xC6, 0x2B, 0x0E, 0xA8, 0xC1, 0xC0, 0x58, 0x07, 0x2B, 0x63, 0x5F, 0x7C, 0x9A, 0xBD, 0xCB, 0x22, 0xDB, 0x20, 0xB2, 0xA9, 0xDA, 0xDA, 0xEF, 0xE8, 0x00, 0x64, 0x2F, 0x5D, 0x8D, 0xEB, 0x78, 0x02, 0xF7, 0xA5, 0x36, 0x77, 0x28, 0xD7, 0x55, 0x8D, 0x14, 0x68, 0xDB, 0xEB, 0x24, 0x09, 0xD0, 0x2B, 0x13, 0x1B, 0x92, 0x6E, 0x2E, 0x59, 0x54, 0x4A, 0xAC, 0x18, 0xCF, 0xC9, 0x09, 0x02, 0x3F, 0x4F, 0xA8, 0x3E, 0x94, 0x00, 0x1F, 0xC2, 0xF1, 0x1A, 0x27, 0x47, 0x7D, 0x10, 0x84, 0xF5, 0x14, 0xB8, 0x61, 0x62, 0x1A, 0x0C, 0x66, 0xAB, 0xD2, 0x4C, 0x4B, 0x9F, 0xC9, 0x0F, 0x3C, 0xD8, 0x92, 0x0F, 0xF5, 0xFF, 0xCE, 0xD7, 0x6E, 0x5C, 0x6F, 0xB1, 0xF5, 0x7D, 0xD3, 0x56, 0xF9, 0x67, 0x27, 0xA4, 0xA5, 0x48, 0x5B, 0x07, 0x93, 0x44, 0x00, 0x4A, 0xF8, 0xFF, 0xA4, 0xCB };
            StrongNamePublicKeyBlob snpkb = new StrongNamePublicKeyBlob(pk);
            StrongName sn = new StrongName(snpkb, "mono", new Version());

            Assert.AreEqual(97, GetRequiredSize(sn, true), "GetRequiredSize-true");
            Assert.AreEqual(93, GetRequiredSize(sn, false), "GetRequiredSize-false");
        }
예제 #30
0
        public decimal runSandboxedGrading()
        {
            if (parameters[0] == "")
            {
                return(5); //no compiled filepath
            }

            pathToUntrusted = Path.Combine(HttpRuntime.AppDomainAppPath, "Grading/");

            //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 = Path.GetFullPath(pathToUntrusted);

            //Setting the permissions for the AppDomain. We give the permission to execute and to
            //read/discover the location where the untrusted code is loaded.
            PermissionSet permSet = new PermissionSet(PermissionState.Unrestricted);

            //permSet.AddPermission(new System.Security.Permissions.FileIOPermission(System.Security.Permissions.FileIOPermissionAccess.Read, "C:/Users/tongliang/Documents/FYP/projectfiles/SPade/SPade/SPade/TestCase"));
            permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));

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

            //Now we have everything we need to create the AppDomain, so let's create it.
            AppDomain newDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet, fullTrustAssembly);

            newDomain.SetData("param1", parameters[0]);
            newDomain.SetData("param2", parameters[1]);
            newDomain.SetData("param3", parameters[2]);
            newDomain.SetData("param4", parameters[3]);
            newDomain.SetData("entryPoint", entryPoint);
            newDomain.SetData("uPath", pathToUntrusted);

            //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 a reference in this domain and use it to execute the
            //untrusted code.
            Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap();

            //retrieve the parameters stored on previous instance of Sandboxer class
            parameters[0]        = newDomain.GetData("param1").ToString();
            parameters[1]        = newDomain.GetData("param2").ToString();
            parameters[2]        = newDomain.GetData("param3").ToString();
            parameters[3]        = newDomain.GetData("param4").ToString();
            this.entryPoint      = newDomain.GetData("entryPoint").ToString();
            this.pathToUntrusted = newDomain.GetData("uPath").ToString();

            return(newDomainInstance.ExecuteUntrustedCode(untrustedAssembly, untrustedClass, entryPoint, parameters));
        }
	public void AddFullTrustAssembly(StrongName sn) {}
	public void RemoveFullTrustAssembly(StrongName sn) {}