/// <summary>
        /// Attempts to load a managed assembly from the specified raw bytes asynchronously.
        /// Use <see cref="SecurityResult"/> of <see cref="AsyncLoadOperation.LoadDomain"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="assemblyBytes">A byte array containing the managed assembly imagae data</param>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        /// <returns>An awaitable async operation object that contains state information for the load request</returns>
        public AsyncLoadOperation LoadAssemblyAsync(byte[] assemblyBytes, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            return(new AsyncLoadOperation(this, assemblyBytes, securityMode));
        }
        /// <summary>
        /// Attempts to load a managed assembly with the specified name asynchronously.
        /// Use <see cref="SecurityResult"/> of <see cref="AsyncLoadOperation.LoadDomain"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="name">The name of the assembly to load</param>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        /// <returns>An awaitable async operation object that contains state information for the load request</returns>
        public AsyncLoadOperation LoadAssemblyAsync(AssemblyName name, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            return(new AsyncLoadOperation(this, name, securityMode));
        }
 internal AsyncLoadOperation(ScriptDomain domain, byte[] assemblyBytes, ScriptSecurityMode securityMode)
 {
     this.loadDomain   = domain;
     this.asmBytes     = assemblyBytes;
     this.loadType     = AssemblyLoadType.LoadFromBytes;
     this.securityMode = securityMode;
 }
 internal AsyncLoadOperation(ScriptDomain domain, string assemblyPath, ScriptSecurityMode securityMode)
 {
     this.loadDomain   = domain;
     this.asmPath      = assemblyPath;
     this.loadType     = AssemblyLoadType.LoadByPath;
     this.securityMode = securityMode;
 }
 // Constructor
 internal AsyncLoadOperation(ScriptDomain domain, AssemblyName assemblyName, ScriptSecurityMode securityMode)
 {
     this.loadDomain   = domain;
     this.asmName      = assemblyName;
     this.loadType     = AssemblyLoadType.LoadByName;
     this.securityMode = securityMode;
 }
        /// <summary>
        /// Attempts to load a managed assembly from the specified filepath asynchronously.
        /// Use <see cref="SecurityResult"/> of <see cref="AsyncLoadOperation.LoadDomain"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="fullPath">The filepath to the managed assembly</param>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        /// <returns>An awaitable async operation object that contains state information for the load request</returns>
        public AsyncLoadOperation LoadAssemblyAsync(string fullPath, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            return(new AsyncLoadOperation(this, fullPath, securityMode));
        }
 // Constructor
 internal AsyncCompileOperation(ScriptDomain domain, bool isCSharpSource, ScriptSecurityMode securityMode, string[] sourceOrFiles, IMetadataReferenceProvider[] additionalReferenceAssemblies = null)
 {
     this.compileDomain        = domain;
     this.sourceCompileType    = (isCSharpSource == true) ? CompileType.CompileSource : CompileType.CompileFile;
     this.securityMode         = securityMode;
     this.sourceOrFiles        = sourceOrFiles;
     this.additionalReferences = additionalReferenceAssemblies;
 }
        /// <summary>
        /// Compile and load the specified C# source files asynchronously.
        /// Use <see cref="CompileResult"/> of <see cref="AsyncCompileOperation.CompileDomain"/> to get the output from the compile request.
        /// Use <see cref="SecurityResult"/> of <see cref="AsyncCompileOperation.CompileDomain"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="cSharpFiles">An array of filepaths to C# source files</param>
        /// <param name="securityMode">The code validation used to verify the code</param>
        /// <returns>An awaitable async operation object containing state information about the compile request</returns>
        public AsyncCompileOperation CompileAndLoadFilesAsync(string[] cSharpFiles, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings, IMetadataReferenceProvider[] additionalReferenceAssemblies = null)
        {
            // Make sure the compiler is initialized and the domain is valid
            CheckDisposed();
            CheckCompiler();

            return(new AsyncCompileOperation(this, false, securityMode, cSharpFiles, additionalReferenceAssemblies));
        }
        private ScriptAssembly RegisterAssembly(Assembly assembly, ScriptSecurityMode securityMode, CodeSecurityEngine securityEngine, bool isRuntimeCompiled, CompilationResult compileResult = null)
        {
            // Check for error
            if (assembly == null)
            {
                return(null);
            }

            // Reset report
            securityResult = null;

            // Create script assembly
            ScriptAssembly scriptAssembly = new ScriptAssembly(this, assembly, securityEngine, compileResult);

            // Check for ensure security mode
            bool performSecurityCheck = (securityMode == ScriptSecurityMode.EnsureSecurity);

            // Get value from settings
            if (securityMode == ScriptSecurityMode.UseSettings)
            {
                performSecurityCheck = RoslynCSharp.Settings.SecurityCheckCode;
            }

            // Check for security checks
            if (performSecurityCheck == true)
            {
                // Perform code validation
                if (scriptAssembly.SecurityCheckAssembly(RoslynCSharp.Settings.SecurityRestrictions, out securityResult) == false)
                {
                    // Log the error
                    RoslynCSharp.LogError(securityResult.GetSummaryText());
                    RoslynCSharp.LogError(securityResult.GetAllText(true));
                    // Dont load the assembly
                    return(null);
                }
                else
                {
                    RoslynCSharp.Log(securityResult.GetSummaryText());
                }
            }

            // Mark as runtime compiled
            if (isRuntimeCompiled == true)
            {
                scriptAssembly.MarkAsRuntimeCompiled();
            }

            lock (this)
            {
                // Register with domain
                this.loadedAssemblies.Add(scriptAssembly);
            }

            // Return result
            return(scriptAssembly);
        }
        /// <summary>
        /// Attempts to load a managed assembly from the specified raw bytes.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="assemblyBytes">The raw data representing the file structure of the managed assembly, The result of <see cref="File.ReadAllBytes(string)"/> for example.</param>
        /// <returns>An instance of <see cref="ScriptAssembly"/> representing the loaded assembly or null if an error occurs</returns>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        public ScriptAssembly LoadAssembly(byte[] assemblyBytes, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            // Load the assembly
            Assembly assembly = sandbox.Load(assemblyBytes);

            // Create script assembly
            return(RegisterAssembly(assembly, null, assemblyBytes, securityMode, false));
        }
        /// <summary>
        /// Attempts to load the specified managed assembly into the sandbox app domain.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="name">The <see cref="AssemblyName"/> representing the assembly to load</param>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        /// <returns>An instance of <see cref="ScriptAssembly"/> representing the loaded assembly or null if an error occurs</returns>
        public ScriptAssembly LoadAssembly(AssemblyName name, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            // Load the assembly
            Assembly assembly = sandbox.Load(name);

            // Create script assembly
            return(RegisterAssembly(assembly, assembly.Location, null, securityMode, false));
        }
Пример #12
0
        public ScriptAssembly RegisterAssembly(ScriptAssembly scriptAssembly, ScriptSecurityMode securityMode)
        {
            // Check for error
            if (scriptAssembly == null)
            {
                return(null);
            }

            // Reset report
            securityResult = null;

            // Check for ensure security mode
            bool performSecurityCheck = (securityMode == ScriptSecurityMode.EnsureSecurity);

            // Get value from settings
            if (securityMode == ScriptSecurityMode.UseSettings)
            {
                performSecurityCheck = RoslynCSharp.Settings.SecurityCheckCode;
            }

            // Check for security checks
            if (performSecurityCheck == true)
            {
                CodeSecurityRestrictions restrictions = RoslynCSharp.Settings.SecurityRestrictions;

                // Use pinvoke option
                restrictions.AllowPInvoke = RoslynCSharp.Settings.AllowPInvoke;

                // Perform code validation
                if (scriptAssembly.SecurityCheckAssembly(restrictions, out securityResult) == false)
                {
                    // Log the error
                    RoslynCSharp.LogError(securityResult.GetSummaryText());
                    RoslynCSharp.LogError(securityResult.GetAllText(true));
                    // Dont load the assembly
                    return(null);
                }
                else
                {
                    RoslynCSharp.Log(securityResult.GetSummaryText());
                }
            }

            lock (this)
            {
                // Register with domain
                this.loadedAssemblies.Add(scriptAssembly);
            }

            // Return result
            return(scriptAssembly);
        }
        /// <summary>
        /// Compile and load the specified C# source file.
        /// Use <see cref="CompileResult"/> to get the output from the compile request.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// This does the same as <see cref="CompileAndLoadFileAsync(string, ScriptSecurityMode)"/> but returns the main type of the <see cref="ScriptAssembly"/> for convenience.
        /// </summary>
        /// <param name="cSharpFile">The filepath to a file containing C# code</param>
        /// <param name="securityMode">The code validation used to verify the code</param>
        /// <returns>The main type of the compiled assembly or null if the compile failed, security validation failed or there was no main type</returns>
        public ScriptType CompileAndLoadMainFile(string cSharpFile, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings, IMetadataReferenceProvider[] additionalReferenceAssemblies = null)
        {
            // Send compile request
            ScriptAssembly assembly = CompileAndLoadFile(cSharpFile, securityMode, additionalReferenceAssemblies);

            // Try to get main type
            if (assembly != null && assembly.MainType != null)
            {
                return(assembly.MainType);
            }

            return(null);
        }
        /// <summary>
        /// Called by Unity.
        /// </summary>
        public void Start()
        {
            // Create domain
            domain = ScriptDomain.CreateDomain("Example Domain");

            // Security load mode
            // ScriptSecurityMode.EnsureLoad - Do not perform and code validation and just load the assembly
            // ScriptSecurityMode.EnsureSecurity - Perform full code validation and discard the assembly if verification fails
            // ScriptSecurityMode.UseSettings - Use the RoslynC# settings to determine which action to take
            ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings;

            // Load an assembly - The assembly may be verified using active security restriction depending upon the security mod specified
            // If an assembly fails verification then it will not be loaded and the load method will return null
            ScriptAssembly assembly = domain.LoadAssembly("path/to/assembly.dll", securityMode);
        }
        /// <summary>
        /// Attempts to load the specified managed assembly into the sandbox app domain.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="fullPath">The full path the the .dll file</param>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        /// <returns>An instance of <see cref="ScriptAssembly"/> representing the loaded assembly or null if an error occurs</returns>
        public ScriptAssembly LoadAssembly(string fullPath, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            // Create an assembly name object
            AssemblyName name = AssemblyName.GetAssemblyName(fullPath);// new AssemblyName();
            //name.CodeBase = fullPath;

            // Load the assembly
            Assembly assembly = sandbox.Load(name);

            // Create script assembly
            return(RegisterAssembly(assembly, fullPath, null, securityMode, false));
        }
        /// <summary>
        /// Attempts to load a managed assembly from the raw assembly data.
        /// Any exceptions thrown while loading will be caught.
        /// </summary>
        /// <param name="data">The raw data representing the file structure of the managed assembly, The result of <see cref="File.ReadAllBytes(string)"/> for example.</param>
        /// <param name="result">An instance of <see cref="ScriptAssembly"/> representing the loaded assembly or null if the load failed</param>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        /// <returns>True if the assembly was loaded successfully or false if an error occured</returns>
        public bool TryLoadAssembly(byte[] data, out ScriptAssembly result, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Even though this method is safe we cannot allow access to a disposed domain
            CheckDisposed();

            try
            {
                // Call through
                result = LoadAssembly(data, securityMode);
                return(true);
            }
            catch (Exception)
            {
                result = null;
                return(false);
            }
        }
        // Methods
        #region AssemblyLoad
        /// <summary>
        /// Attempts to load a managed assembly from the specified resources path into the sandbox app domain.
        /// The target asset must be a <see cref="TextAsset"/> in order to be loaded successfully.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="resourcePath">The file name of path relative to the 'Resources' folder without the file extension</param>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        /// <returns>An instance of <see cref="ScriptAssembly"/> representing the loaded assembly or null if an error occurs</returns>
        /// <exception cref="SecurityException">The assembly breaches the imposed security restrictions</exception>
        public ScriptAssembly LoadAssemblyFromResources(string resourcePath, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            // Try to load resource
            TextAsset asset = Resources.Load <TextAsset>(resourcePath);

            // Check for error
            if (asset == null)
            {
                throw new DllNotFoundException(string.Format("Failed to load dll from resources path '{0}'", resourcePath));
            }

            // Get the asset bytes and call through
            return(LoadAssembly(asset.bytes, securityMode));
        }
        /// <summary>
        /// Attempts to load the specified managed assembly into the sandbox app domain.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="name">The <see cref="AssemblyName"/> representing the assembly to load</param>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        /// <returns>An instance of <see cref="ScriptAssembly"/> representing the loaded assembly or null if an error occurs</returns>
        public ScriptAssembly LoadAssembly(AssemblyName name, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            // Load the assembly
            Assembly           assembly       = sandbox.Load(name);
            CodeSecurityEngine securityEngine = null;

            // Initialize security engine
            if (assembly != null)
            {
                securityEngine = new CodeSecurityEngine(assembly.Location);
            }

            // Create script assembly
            return(RegisterAssembly(assembly, securityMode, securityEngine, false));
        }
        /// <summary>
        /// Compile and load the specified C# source files.
        /// Use <see cref="CompileResult"/> to get the output from the compile request.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="cSharpFiles">An array of filepaths to C# source files</param>
        /// <param name="securityMode">The code validation used to verify the code</param>
        /// <returns>The compiled and loaded assembly or null if the compil or security verification failed</returns>
        public ScriptAssembly CompileAndLoadFiles(string[] cSharpFiles, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings, IMetadataReferenceProvider[] additionalReferenceAssemblies = null)
        {
            // Make sure the compiler is initialized and the domain is valid
            CheckDisposed();
            CheckCompiler();

            lock (this)
            {
                // Compile from file
                compileResult = sharedCompiler.CompileFromFiles(cSharpFiles, additionalReferenceAssemblies);

                // Log to console
                LogCompilerOutputToConsole();

                // Security check
                return(RegisterAssembly(compileResult.OutputAssembly, compileResult.OutputFile, compileResult.OutputAssemblyImage, securityMode, true, compileResult));
            }
        }
        /// <summary>
        /// Attempts to load a managed assembly from the specified raw bytes.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="assemblyBytes">The raw data representing the file structure of the managed assembly, The result of <see cref="File.ReadAllBytes(string)"/> for example.</param>
        /// <returns>An instance of <see cref="ScriptAssembly"/> representing the loaded assembly or null if an error occurs</returns>
        /// <param name="securityMode">The security mode which determines whether code validation will run</param>
        public ScriptAssembly LoadAssembly(byte[] assemblyBytes, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings)
        {
            // Check for disposed
            CheckDisposed();

            // Load the assembly
            Assembly           assembly       = sandbox.Load(assemblyBytes);
            CodeSecurityEngine securityEngine = null;

            // Create the security engine
            if (assembly != null)
            {
                securityEngine = new CodeSecurityEngine(assemblyBytes);
            }

            // Create script assembly
            return(RegisterAssembly(assembly, securityMode, securityEngine, false));
        }
Пример #21
0
        /// <summary>
        /// Called by Unity.
        /// </summary>
        public IEnumerator Start()
        {
            // Create domain
            domain = ScriptDomain.CreateDomain("Example Domain");

            // Security load mode
            // ScriptSecurityMode.EnsureLoad - Do not perform and code validation and just load the assembly
            // ScriptSecurityMode.EnsureSecurity - Perform full code validation and discard the assembly if verification fails
            // ScriptSecurityMode.UseSettings - Use the RoslynC# settings to determine which action to take
            ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings;

            // Load an assembly async - The assembly may be verified using active security restriction depending upon the security mod specified
            // If an assembly fails verification then it will not be loaded and the load operation will contain failure information
            AsyncLoadOperation assemblyLoad = domain.LoadAssemblyAsync("path/to/assembly.dll", securityMode);

            // Wait for request to complete
            yield return(assemblyLoad);

            // Get the loaded assembly - This will be null if the load or security validation failed
            ScriptAssembly assembly = assemblyLoad.LoadedAssembly;
        }
        /// <summary>
        /// Compile and load the specified C# source code string.
        /// Use <see cref="CompileResult"/> to get the output from the compile request.
        /// Use <see cref="SecurityResult"/> to get the output from the code validation request.
        /// </summary>
        /// <param name="cSharpSource">The string containing C# source code</param>
        /// <param name="securityMode">The code validation used to verify the code</param>
        /// <returns>The compiled and loaded assembly or null if the compile or security verification failed</returns>
        public ScriptAssembly CompileAndLoadSource(string cSharpSource, ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings, IMetadataReferenceProvider[] additionalReferenceAssemblies = null)
        {
            // Make sure the compiler is initialized and the domain is valid
            CheckDisposed();
            CheckCompiler();

            lock (this)
            {
                // Compile from source
                compileResult = sharedCompiler.CompileFromSource(cSharpSource, additionalReferenceAssemblies);

                // Log to console
                LogCompilerOutputToConsole();

                // Create the security engine
                CodeSecurityEngine securityEngine = CreateSecurityEngine(compileResult);

                // Security check
                return(RegisterAssembly(compileResult.OutputAssembly, securityMode, securityEngine, true, compileResult));
            }
        }