Example #1
0
        static VmHelperGenerator()
        {
            var assembly = WindowsAssembly.FromFile(typeof(VmHelper).Assembly.Location);
            var image    = assembly.NetDirectory.MetadataHeader.LockMetadata();

            VmHelperType = image.Assembly.Modules[0].TopLevelTypes.First(x => x.Name == nameof(VmHelper));
        }
Example #2
0
 public override void AddDllsToLoad(WindowsAssembly PE)
 {
     foreach (ImageModuleImport mi in PE.ImportDirectory.ModuleImports)
     {
         _cryptedDllNames.Add(xorCrypt(mi.Name));
     }
 }
Example #3
0
        public static WindowsAssembly CreateAssembly(string name, bool isDll)
        {
            var assembly = new WindowsAssembly();

            assembly.RelocationDirectory = new ImageRelocationDirectory();
            InitializeNtHeaders(assembly.NtHeaders, isDll);
            InitializeNetDirectory(assembly.NetDirectory = new ImageNetDirectory());
            assembly.ImportDirectory.ModuleImports.Add(CreateMscoreeImport(isDll));

            var image = assembly.NetDirectory.MetadataHeader.LockMetadata();

            image.Assembly.Name    = name;
            image.Assembly.Version = new Version(1, 0, 0, 0);

            var mainModule = new ModuleDefinition(name + (isDll ? ".dll" :".exe"));

            mainModule.Mvid = Guid.NewGuid();
            image.Assembly.Modules.Add(mainModule);

            mainModule.TopLevelTypes.Add(new TypeDefinition(null, "<Module>"));

            assembly.NetDirectory.MetadataHeader.UnlockMetadata();

            return(assembly);
        }
Example #4
0
        /// <summary>
        /// Reads a windows assembly image from the specified file path.
        /// </summary>
        /// <param name="filePath">The file path to the assembly to read.</param>
        /// <returns>The assembly that was read.</returns>
        protected virtual WindowsAssembly ReadAssembly(string filePath)
        {
            var windowsAssembly = WindowsAssembly.FromBytes(File.ReadAllBytes(filePath), new ReadingParameters());

            windowsAssembly.NetDirectory.MetadataHeader.LockMetadata();
            return(windowsAssembly);
        }
Example #5
0
        public static WindowsAssembly CreateAssembly(string name, bool isDll)
        {
            var assembly = new WindowsAssembly();

            assembly.RelocationDirectory = new ImageRelocationDirectory();
            InitializeNtHeaders(assembly.NtHeaders);
            InitializeNetDirectory(assembly.NetDirectory = new ImageNetDirectory());

            assembly.ImportDirectory.ModuleImports.Add(CreateMscoreeImport(isDll));

            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream <TableStream>();

            tableStream.GetTable <ModuleDefinition>().Add(new ModuleDefinition(name + (isDll ? ".dll" : ".exe"))
            {
                Mvid = Guid.NewGuid()
            });
            tableStream.GetTable <AssemblyDefinition>().Add(new AssemblyDefinition(name, new Version(1, 0, 0, 0)));

            var moduleTypeDef = new TypeDefinition(string.Empty, "<Module>", null);

            moduleTypeDef.MetadataRow.Column5 = 1; // TODO: remove MethodList setter.
            moduleTypeDef.MetadataRow.Column6 = 1; // TODO: remove MethodList setter.
            tableStream.GetTable <TypeDefinition>().Add(moduleTypeDef);

            return(assembly);
        }
Example #6
0
        public void ExtensionMethodTest()
        {
            var sourceAssembly = WindowsAssembly.FromFile(typeof(StaticClass).Assembly.Location);
            var sourceImage    = sourceAssembly.NetDirectory.MetadataHeader.LockMetadata();

            var assembly = NetAssemblyFactory.CreateAssembly("SomeAssembly", false);
            var header   = assembly.NetDirectory.MetadataHeader;
            var image    = header.LockMetadata();
            var importer = new ReferenceImporter(image);
            var cloner   = new MemberCloner(image);

            var staticClass = sourceImage.Assembly.Modules[0].TopLevelTypes.First(x => x.Name == "StaticClass");
            var clonedType  = cloner.CloneType(staticClass);

            var main = new MethodDefinition("Main", MethodAttributes.Public | MethodAttributes.Static,
                                            new MethodSignature(image.TypeSystem.Void));

            main.CilMethodBody = new CilMethodBody(main);
            var instructions = main.CilMethodBody.Instructions;

            instructions.Add(CilInstruction.Create(CilOpCodes.Ldc_I4_1));
            instructions.Add(CilInstruction.Create(CilOpCodes.Call,
                                                   clonedType.Methods.First(x => x.Name == "SomeExtension")));
            instructions.Add(CilInstruction.Create(CilOpCodes.Call,
                                                   importer.ImportMethod(typeof(Console).GetMethod("WriteLine", new[] { typeof(int) }))));
            instructions.Add(CilInstruction.Create(CilOpCodes.Ret));

            image.Assembly.Modules[0].TopLevelTypes.Add(clonedType);
            image.Assembly.Modules[0].TopLevelTypes[0].Methods.Add(main);
            image.ManagedEntrypoint = main;

            header.UnlockMetadata();

            _context.VerifyOutput(assembly, "4");
        }
Example #7
0
        private static void TestFieldRva(WindowsAssembly assembly, TypeSignature fieldType, byte[] fieldRvaData, bool saveToDisk)
        {
            const string fieldName = "MyField";

            // set up temp assembly.
            var tableStream   = assembly.NetDirectory.MetadataHeader.GetStream <TableStream>();
            var fieldTable    = tableStream.GetTable <FieldDefinition>();
            var fieldRvaTable = tableStream.GetTable <FieldRva>();

            // create temp field.
            var field = new FieldDefinition(fieldName,
                                            FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.HasFieldRva,
                                            new FieldSignature(fieldType));

            fieldTable.Add(field);

            // create field rva.
            var fieldRva = new FieldRva(field, fieldRvaData);

            field.FieldRva = fieldRva;
            fieldRvaTable.Add(fieldRva);

            assembly    = Utilities.RebuildNetAssembly(assembly, saveToDisk);
            tableStream = assembly.NetDirectory.MetadataHeader.GetStream <TableStream>();
            fieldTable  = tableStream.GetTable <FieldDefinition>();

            field = fieldTable.FirstOrDefault(x => x.Name == fieldName);
            Assert.IsNotNull(field);
            Assert.IsNotNull(field.FieldRva);
            Utilities.ValidateByteArrays(fieldRvaData, field.FieldRva.Data);
        }
        public void VerifyOutput(WindowsAssembly assembly, string expectedOutput)
        {
            string path = GenerateRandomFileName();

            assembly.Write(path, new CompactNetAssemblyBuilder(assembly));

            string contents = null;
            string error    = null;

            using (var process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = path,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    ErrorDialog = false
                }
            })
            {
                process.Start();

                contents = process.StandardOutput.ReadToEnd().Trim();
                error    = process.StandardError.ReadToEnd();
                process.WaitForExit();
            }

            Assert.Empty(error);
            Assert.Equal(expectedOutput, contents);
        }
Example #9
0
        public void CloneParameterReferences()
        {
            var sourceAssembly = WindowsAssembly.FromFile(typeof(SimpleClass).Assembly.Location);
            var sourceImage    = sourceAssembly.NetDirectory.MetadataHeader.LockMetadata();

            var assembly = NetAssemblyFactory.CreateAssembly("SomeAssembly", false);
            var header   = assembly.NetDirectory.MetadataHeader;
            var image    = header.LockMetadata();
            var cloner   = new MemberCloner(image);

            var variablesClass = sourceImage.Assembly.Modules[0].TopLevelTypes.First(x => x.Name == "Variables");
            var clonedClass    = cloner.CloneType(variablesClass);

            image.Assembly.Modules[0].TopLevelTypes.Add(clonedClass);

            foreach (var clonedMethod in clonedClass.Methods.Where(x => x.CilMethodBody != null))
            {
                var body       = clonedMethod.CilMethodBody;
                var parameters = clonedMethod.Signature.Parameters;

                var originalBody       = variablesClass.Methods.First(x => x.Name == clonedMethod.Name).CilMethodBody;
                var originalParameters = originalBody.Method.Signature.Parameters;

                foreach (var instruction in body.Instructions.Where(x =>
                                                                    x.OpCode.OperandType == CilOperandType.InlineArgument ||
                                                                    x.OpCode.OperandType == CilOperandType.ShortInlineArgument))
                {
                    var originalInstruction = originalBody.Instructions.GetByOffset(instruction.Offset);
                    Assert.NotNull(instruction.Operand);
                    Assert.Equal(originalParameters.IndexOf((ParameterSignature)originalInstruction.Operand),
                                 parameters.IndexOf((ParameterSignature)instruction.Operand));
                }
            }
        }
        public void ReadFatMethodBodyVariables()
        {
            var assembly = WindowsAssembly.FromFile(typeof(Class1).Assembly.Location);
            var header   = assembly.NetDirectory.MetadataHeader;

            const string methodName = "MyFatMethodVariables";

            var methodToken = new MetadataToken((uint)typeof(Class1).GetMethod(methodName).MetadataToken);
            var methodRow   = header.GetStream <TableStream>().GetTable <MethodDefinitionTable>()[(int)(methodToken.Rid - 1)];

            Assert.IsType <CilRawFatMethodBody>(methodRow.Column1);

            var fatBody = (CilRawFatMethodBody)methodRow.Column1;

            Assert.NotEqual(0u, fatBody.LocalVarSigToken);

            var image  = header.LockMetadata();
            var method = image.Assembly.Modules[0].TopLevelTypes.First(x => x.Name == nameof(Class1)).Methods
                         .First(x => x.Name == methodName);

            var body = method.CilMethodBody;

            Assert.NotNull(body);
            Assert.True(body.IsFat);
            Assert.NotNull(body.Signature);
            Assert.IsType <LocalVariableSignature>(body.Signature.Signature);
            Assert.Contains(((LocalVariableSignature)body.Signature.Signature).Variables,
                            x => x.VariableType.FullName == typeof(string).FullName);
        }
        public void ReadSmallMethodBody()
        {
            var assembly = WindowsAssembly.FromFile(typeof(Class1).Assembly.Location);
            var header   = assembly.NetDirectory.MetadataHeader;

            var methodToken = new MetadataToken((uint)typeof(Class1).GetMethod("MyMethod").MetadataToken);
            var methodRow   = header.GetStream <TableStream>().GetTable <MethodDefinitionTable>()[(int)(methodToken.Rid - 1)];

            Assert.IsType <CilRawSmallMethodBody>(methodRow.Column1);

            var image  = header.LockMetadata();
            var method = image.Assembly.Modules[0].TopLevelTypes.First(x => x.Name == "Class1").Methods
                         .First(x => x.Name == "MyMethod");

            var body = method.CilMethodBody;

            Assert.NotNull(body);
            Assert.False(body.IsFat);
            Assert.False(body.InitLocals);
            Assert.Equal(0, body.ExceptionHandlers.Count);
            Assert.Null(body.Signature);

            var instructions = body.Instructions;

            Assert.Contains(instructions, x => x.OpCode.Code == CilCode.Ldstr);
            Assert.Contains(instructions, x => x.OpCode.Code == CilCode.Call);
            Assert.Contains(instructions, x => x.OpCode.Code == CilCode.Ret);
        }
        public void ReadFatMethodBodyExceptionhandlers()
        {
            var assembly = WindowsAssembly.FromFile(typeof(Class1).Assembly.Location);
            var header   = assembly.NetDirectory.MetadataHeader;

            const string methodName = "MyFatMethodExceptionHandlers";

            var methodToken = new MetadataToken((uint)typeof(Class1).GetMethod(methodName).MetadataToken);
            var methodRow   = header.GetStream <TableStream>().GetTable <MethodDefinitionTable>()[(int)(methodToken.Rid - 1)];

            Assert.IsType <CilRawFatMethodBody>(methodRow.Column1);

            var fatBody = (CilRawFatMethodBody)methodRow.Column1;

            Assert.True(fatBody.HasSections);

            var image  = header.LockMetadata();
            var method = image.Assembly.Modules[0].TopLevelTypes.First(x => x.Name == nameof(Class1)).Methods
                         .First(x => x.Name == methodName);

            var body = method.CilMethodBody;

            Assert.NotNull(body);
            Assert.True(body.IsFat);
            Assert.Equal(1, body.ExceptionHandlers.Count);
            Assert.Equal(typeof(Exception).FullName, body.ExceptionHandlers[0].CatchType.FullName);
        }
Example #13
0
 public static WindowsAssembly RebuildNetAssembly(WindowsAssembly assembly, bool saveToDesktop)
 {
     if (saveToDesktop)
         return RebuildNetAssembly(assembly,
             Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.exe"));
     return RebuildNetAssembly(assembly);
 }
Example #14
0
        private DevirtualisationContext CreateDevirtualisationContext(DevirtualisationOptions options)
        {
            // Open target file.
            Logger.Log(Tag, $"Opening target file {options.InputFile}...");
            var assembly = WindowsAssembly.FromFile(options.InputFile);
            var header   = assembly.NetDirectory?.MetadataHeader;

            if (header == null)
            {
                throw new BadImageFormatException("Assembly does not contain a valid .NET header.");
            }

            // Hook into md stream parser.
            var parser = new KoiVmAwareStreamParser(options.KoiStreamName, Logger);

            if (options.OverrideKoiStreamData)
            {
                string path = Path.IsPathRooted(options.KoiStreamDataFile)
                    ? options.KoiStreamDataFile
                    : Path.Combine(Path.GetDirectoryName(options.InputFile), options.KoiStreamDataFile);

                Logger.Log(Tag, $"Opening external Koi stream data file {path}...");
                parser.ReplacementData = File.ReadAllBytes(path);

                var streamHeader = header.StreamHeaders.FirstOrDefault(h => h.Name == options.KoiStreamName);
                if (streamHeader == null)
                {
                    streamHeader = new MetadataStreamHeader(options.KoiStreamName)
                    {
                        Stream = KoiStream.FromReadingContext(
                            new ReadingContext()
                        {
                            Reader = new MemoryStreamReader(parser.ReplacementData)
                        }, Logger)
                    };
                    header.StreamHeaders.Add(streamHeader);
                }
            }

            header.StreamParser = parser;

            // Ignore invalid / encrypted method bodies when specified.
            if (options.IgnoreInvalidMethodBodies)
            {
                var table = header.GetStream <TableStream>().GetTable <MethodDefinitionTable>();
                table.MethodBodyReader = new DefaultMethodBodyReader {
                    ThrowOnInvalidMethodBody = false
                };
            }

            // Lock image and set custom md resolver.
            var image = header.LockMetadata();

            image.MetadataResolver = new DefaultMetadataResolver(
                new DefaultNetAssemblyResolver(Path.GetDirectoryName(options.InputFile)));

            var runtimeImage = ResolveRuntimeImage(options, image);

            return(new DevirtualisationContext(options, image, runtimeImage, Logger));
        }
Example #15
0
        private ImageSectionHeader WriteSectionHeader(WindowsAssembly pE)
        {
            int newSectionHeaderOffset = (int)pE.SectionHeaders.Last().StartOffset + 0x28;

            if (newSectionHeaderOffset + 0x28 > pE.SectionHeaders.First().PointerToRawData)
            {
                throw new Exception("Not ehought space in header to add a new section");
            }

            byte[]             stubSectionHeader;
            ImageSectionHeader section = PrepareNewSection(pE, out stubSectionHeader);

            pE.SectionHeaders.Add(section);

            dataStream.Seek(newSectionHeaderOffset, SeekOrigin.Begin);
            if (stubSectionHeader != null)
            {
                dataStream.Write(stubSectionHeader, 0, stubSectionHeader.Length);
            }
            else
            {
                throw new Exception("Can't generate IMAGE_SECTION_HEADER");
            }

            return(section);
        }
        protected override IList <Subtitle> GetSubtitles()
        {
            var result = new List <Subtitle>();

            var peInfo = WindowsAssembly.FromFile(Path);

            using (var fs = new FileStream(Path, FileMode.Open))
                using (var input = new ExtendedBinaryReader(fs, FileEncoding, Endianness.LittleEndian))
                {
                    var pointerSection      = peInfo.GetSectionByName(PointerSectionName);
                    var pointerSectionStart = pointerSection.Header.PointerToRawData;
                    var pointerCount        = pointerSection.GetPhysicalLength() / 8;

                    var stringsSection     = peInfo.GetSectionByName(StringsSectionName);
                    var stringsSectionBase = (long)(peInfo.NtHeaders.OptionalHeader.ImageBase +
                                                    (stringsSection.Header.VirtualAddress - stringsSection.Header.PointerToRawData));
                    for (var i = 0; i < pointerCount; i++)
                    {
                        input.Seek(pointerSectionStart + i * 8, SeekOrigin.Begin);
                        var value = input.ReadInt64();
                        if (value != 0)
                        {
                            var possibleStringOffset = value - stringsSectionBase;

                            bool allowed;

                            if (AllowedStringOffsets != null)
                            {
                                allowed = AllowedStringOffsets.Any(x =>
                                                                   x.Item1 <= possibleStringOffset && x.Item2 >= possibleStringOffset);
                            }
                            else
                            {
                                allowed = (stringsSection.Header.PointerToRawData <= possibleStringOffset) &&
                                          (possibleStringOffset < (stringsSection.Header.PointerToRawData + stringsSection.Header.SizeOfRawData));
                            }

                            if (allowed)
                            {
                                var exists = result.Any(x => x.Offset == possibleStringOffset);

                                if (!exists)
                                {
                                    var sub = ReadSubtitle(input, possibleStringOffset, false);
                                    sub.PropertyChanged += SubtitlePropertyChanged;

                                    result.Add(sub);
                                }
                            }
                        }
                    }

                    result.Sort();
                }

            LoadChanges(result);

            return(result);
        }
Example #17
0
 public ImportDirectoryBuffer(WindowsAssembly assembly)
     : this(assembly, assembly.NtHeaders.OptionalHeader.Magic == OptionalHeaderMagic.Pe32)
 {
     foreach (var import in assembly.ImportDirectory.ModuleImports)
     {
         AddModuleImport(import);
     }
 }
Example #18
0
 public ResourceDirectoryBuffer(WindowsAssembly assembly)
     : this((IOffsetConverter)assembly)
 {
     if (assembly.RootResourceDirectory != null)
     {
         AddDirectory(assembly.RootResourceDirectory, 0);
     }
 }
Example #19
0
 public virtual void DestroyImportDirectory(WindowsAssembly pE)
 {
     foreach (ImageModuleImport im in pE.ImportDirectory.ModuleImports)
     {
         im.Name = "";
         // to complete
     }
 }
Example #20
0
        private static void DebugPatch(string EXE, string CFG, string KeyPath)
        {
            File.Move(EXE, EXE + ".bak");
            byte[]          Executable = File.ReadAllBytes(EXE + ".bak");
            WindowsAssembly Assembly   = WindowsAssembly.FromFile(EXE + ".bak");
            var             Entries    = Assembly.RootResourceDirectory.Entries;

            try {
                UpdateResourceByName(ref Executable, "V_CODE", VCODE, ref Entries);
                UpdateResourceByName(ref Executable, "V_CODE2", VCODE, ref Entries);
                UpdateResourceByName(ref Executable, "KEY_CODE", KEYCODE, ref Entries);
            }
            catch {
                File.Move(EXE + ".bak", EXE);
                Log("Failed to Patch, This is a CT2 Game?");
                return;
            }
            Log("All Resources Patched...");
            File.WriteAllBytes(KeyPath, DBGKEY);
            Log("Debug Key Generated...");

            if (!Patch(ref Executable, Validation, new byte[] { 0xEB }, "BYPASS V1"))
            {
                if (!Patch(ref Executable, Validation2, new byte[] { 0xEB }, "BYPASS V2"))
                {
                    File.Move(EXE + ".bak", EXE);
                    File.Delete(EXE + ".tmp");
                    if (SteamStubPresent(ref Executable))
                    {
                        Log("Failed to Patch, Steam Stub Present in the executable, Remove it before.");
                    }
                    else
                    {
                        Log("Failed to Patch, Unsupported Engine Version");
                    }
                    return;
                }
            }
            File.WriteAllBytes(EXE, Executable);

            string[] XML = File.ReadAllLines(CFG, Encoding.UTF8);
            for (int i = 0; i < XML.Length; i++)
            {
                string Line = XML[i].Trim().ToLower();
                if (Line.Contains("v_code") && !Line.StartsWith("<!--"))
                {
                    XML[i] = "<!-- " + XML[i] + " -->";
                }
            }
            File.WriteAllLines(CFG, XML);
            Log("Successfully patched");

            ConsoleColor bk = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Atention: To works you need decrypt all Int's Packget and delete the \"startup.xml\" into game save directory.");
            Console.ForegroundColor = bk;
        }
Example #21
0
        public static WindowsAssembly RebuildNetAssembly(WindowsAssembly assembly)
        {
            var outputStream = new MemoryStream();
            var writer = new BinaryStreamWriter(outputStream);
            assembly.Write(new BuildingParameters(writer));

            return WindowsAssembly.FromReader(new MemoryStreamReader(outputStream.ToArray()),
                new ReadingParameters());
        }
Example #22
0
 public static WindowsAssembly RebuildNetAssembly(WindowsAssembly assembly, bool saveToDesktop)
 {
     if (saveToDesktop)
     {
         return(RebuildNetAssembly(assembly,
                                   Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.exe")));
     }
     return(RebuildNetAssembly(assembly));
 }
 protected WindowsAssemblyBuilder(WindowsAssembly assembly, BuildingParameters parameters)
 {
     if (assembly == null)
         throw new ArgumentNullException("assembly");
     if (parameters == null)
         throw new ArgumentNullException("parameters");
     Assembly = assembly;
     Parameters = parameters;
 }
Example #24
0
 public override void AddAPIs(WindowsAssembly pE)
 {
     foreach (ImageModuleImport mi in pE.ImportDirectory.ModuleImports)
     {
         foreach (ImageSymbolImport si in mi.SymbolImports)
         {
             _ApiNameApiHashModuleHash[si.HintName.Name] = new Tuple <uint, uint>(Hash(si.HintName.Name), Hash(si.Module.Name));
         }
     }
 }
Example #25
0
        public static WindowsAssembly RebuildNetAssembly(WindowsAssembly assembly)
        {
            var outputStream = new MemoryStream();
            var writer       = new BinaryStreamWriter(outputStream);

            assembly.Write(new BuildingParameters(writer));

            return(WindowsAssembly.FromReader(new MemoryStreamReader(outputStream.ToArray()),
                                              new ReadingParameters()));
        }
Example #26
0
 public override void GenerateRedirectionCode(WindowsAssembly pE)
 {
     foreach (string apiName in _ApiNameApiHashModuleHash.Keys)
     {
         Code += string.Format(RedirectionCodeSnippet,
                               apiName,
                               _ApiNameApiHashModuleHash[apiName].Item1,
                               _ApiNameApiHashModuleHash[apiName].Item2);
     }
 }
Example #27
0
        public static void DynamicLoadTests()
        {
            //string pathToDLL = @"C:\ProFast\Projects\DotNetClassesV3\WinAppComponents\TestprogSystemObjectsDLL\bin\Release\TestprogSystemObjectsDLL.dll";
            string pathToDLL = System.IO.Path.GetFullPath(@"..\..\..\..\..\DotNetClassesV3\WinAppComponents\TestprogSystemObjectsDLL\bin\Release\TestprogSystemObjectsDLL.dll");

            try
            {
                _msg.Length = 0;
                _msg.Append("DynamicLoadTests started ...");
                Program._messageLog.WriteLine(_msg.ToString());

                Type testClass = WindowsAssembly.LoadType(pathToDLL, "TestprogSystemObjectsDLL.PFInitClassExtended");

                WindowsAssembly.InvokeVoidMethodNoArguments(testClass, "DisplayTestMessage");

                //no error will be thrown on this call, even though routine is a void method and no parameters required
                object nores = WindowsAssembly.InvokeMethod(testClass, "DisplayTestMessage", null);

                int x = 5;
                int y = 8;
                int z = -1;

                object[] parms = new object[2] {
                    x, y
                };
                object res = WindowsAssembly.InvokeMethod(testClass, "AddTwoNumbers", parms);
                z = (int)res;

                _msg.Length = 0;
                _msg.Append("Result from AddTwoNumbers is ");
                _msg.Append(z.ToString());
                Program._messageLog.WriteLine(_msg.ToString());

                object obj = WindowsAssembly.InstantiateType(testClass);
                object val = WindowsAssembly.GetPropertyValue(obj, "TestDouble", null);
                _msg.Length = 0;
                _msg.Append("TestDouble value is ");
                _msg.Append(val.ToString());
                Program._messageLog.WriteLine(_msg.ToString());
            }
            catch (System.Exception ex)
            {
                _msg.Length = 0;
                _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex));
                Program._messageLog.WriteLine(_msg.ToString());
                AppMessages.DisplayErrorMessage(_msg.ToString(), _saveErrorMessagesToAppLog);
            }
            finally
            {
                _msg.Length = 0;
                _msg.Append("... DynamicLoadTests finished.");
                Program._messageLog.WriteLine(_msg.ToString());
            }
        }
Example #28
0
        private void WriteNtHeaders(WindowsAssembly pE, ImageSectionHeader section, bool movEP)
        {
            if (movEP)
            {
                pE.NtHeaders.OptionalHeader.AddressOfEntrypoint = section.VirtualAddress + (uint)EPoffset;
            }
            pE.NtHeaders.FileHeader.NumberOfSections++;
            pE.NtHeaders.OptionalHeader.SizeOfImage = GetSizeOfImage(pE);

            dataStream.Seek(pE.NtHeaders.StartOffset, SeekOrigin.Begin);
            pE.NtHeaders.Write(new WritingContext(pE, new BinaryStreamWriter(dataStream), null));
        }
Example #29
0
        public static WindowsAssembly RebuildNetAssembly(WindowsAssembly assembly, string tempPath)
        {
            using (var outputStream = File.Create(tempPath))
            {
                var writer = new BinaryStreamWriter(outputStream);
                assembly.Write(new BuildingParameters(writer));
            }

            var inputStream = new MemoryStreamReader(File.ReadAllBytes(tempPath));
            return WindowsAssembly.FromReader(inputStream,
                new ReadingParameters());
        }
Example #30
0
        public virtual void ImplementRedirection(WindowsAssembly pE, byte[] peData, ProtectionOptions options)
        {
            this.dataStream = new MemoryStream();
            int EOF = EndOfFileOffset(pE.SectionHeaders.Last());

            WriteSetions(peData, EOF);
            WriteStubSection(pE.NtHeaders.OptionalHeader.FileAlignment);
            WriteEndOfFile(peData, EOF);
            WriteHeaders(pE, options.AddDllLoader);

            //File.WriteAllBytes("test.exe", dataStream.ToArray());
        }
Example #31
0
        /// <summary>
        ///     Initializes the PEReader using a byte-array of a given PE
        /// </summary>
        /// <param name="fileBytes">PE's byte-array</param>
        public PEReader(byte[] fileBytes)
        {
            log.Log(LogType.Normal, "PE read using file-bytes...");

            try
            {
                wasm = WindowsAssembly.FromBytes(fileBytes);
            }
            catch (Exception e)
            {
                log.Log(e, "Exception on loading file");
            }
        }
Example #32
0
 protected WindowsAssemblyBuilder(WindowsAssembly assembly, BuildingParameters parameters)
 {
     if (assembly == null)
     {
         throw new ArgumentNullException("assembly");
     }
     if (parameters == null)
     {
         throw new ArgumentNullException("parameters");
     }
     Assembly   = assembly;
     Parameters = parameters;
 }
Example #33
0
        public static WindowsAssembly RebuildNetAssembly(WindowsAssembly assembly, string tempPath)
        {
            using (var outputStream = File.Create(tempPath))
            {
                var writer = new BinaryStreamWriter(outputStream);
                assembly.Write(new BuildingParameters(writer));
            }

            var inputStream = new MemoryStreamReader(File.ReadAllBytes(tempPath));

            return(WindowsAssembly.FromReader(inputStream,
                                              new ReadingParameters()));
        }
        public void ReadFieldRvaArray()
        {
            var assembly = WindowsAssembly.FromFile(typeof(Class1).Assembly.Location);
            var header   = assembly.NetDirectory.MetadataHeader;

            var fieldInitializer = typeof(Class1).Assembly.GetTypes().SelectMany(x => x.GetFields(BindingFlags.Static | BindingFlags.NonPublic))
                                   .First();
            var fieldToken  = new MetadataToken((uint)fieldInitializer.MetadataToken);
            var fieldRvaRow = header.GetStream <TableStream>().GetTable <FieldRvaTable>()
                              .FindFieldRvaOfField(fieldToken.Rid);

            Assert.Equal(Class1.MyArray, fieldRvaRow.Column1.Data);
        }
Example #35
0
        public static WindowsAssembly CreateAssembly(string name, bool isDll)
        {
            var assembly = new WindowsAssembly();
            assembly.RelocationDirectory = new ImageRelocationDirectory();
            InitializeNtHeaders(assembly.NtHeaders);
            InitializeNetDirectory(assembly.NetDirectory = new ImageNetDirectory());

            assembly.ImportDirectory.ModuleImports.Add(CreateMscoreeImport(isDll));

            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            tableStream.GetTable<ModuleDefinition>().Add(new ModuleDefinition(name + (isDll ? ".dll" : ".exe"))
            {
                Mvid = Guid.NewGuid()
            });
            tableStream.GetTable<AssemblyDefinition>().Add(new AssemblyDefinition(name, new Version(1, 0, 0, 0)));

            var moduleTypeDef = new TypeDefinition(string.Empty, "<Module>", null);
            moduleTypeDef.MetadataRow.Column5 = 1; // TODO: remove MethodList setter.
            moduleTypeDef.MetadataRow.Column6 = 1; // TODO: remove MethodList setter.
            tableStream.GetTable<TypeDefinition>().Add(moduleTypeDef);

            return assembly;
        }
Example #36
0
        private static void TestFieldRva(WindowsAssembly assembly, TypeSignature fieldType, byte[] fieldRvaData, bool saveToDisk)
        {
            // set up temp assembly.
            var tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            var fieldTable = tableStream.GetTable<FieldDefinition>();
            var fieldRvaTable = tableStream.GetTable<FieldRva>();

            // create temp field.
            var field = new FieldDefinition(FieldName,
                FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.HasFieldRva,
                new FieldSignature(fieldType));
            fieldTable.Add(field);

            // create field rva.
            var fieldRva = new FieldRva(field, fieldRvaData);
            field.FieldRva = fieldRva;
            fieldRvaTable.Add(fieldRva);

            assembly = Utilities.RebuildNetAssembly(assembly, saveToDisk);
            tableStream = assembly.NetDirectory.MetadataHeader.GetStream<TableStream>();
            fieldTable = tableStream.GetTable<FieldDefinition>();

            field = fieldTable.FirstOrDefault(x => x.Name == FieldName);
            Assert.IsNotNull(field);
            Assert.IsNotNull(field.FieldRva);
            Utilities.ValidateByteArrays(fieldRvaData, field.FieldRva.Data);
        }
Example #37
0
 public NetAssemblyBuilder(WindowsAssembly assembly, BuildingParameters parameters)
     : base(assembly, parameters)
 {
     _sectionsTableBuilder = new SectionsTableBuilder(this);
     InitializeBluePrint();
 }