Ejemplo n.º 1
0
        private static void SerializeImageToDisk(
            DevirtualisationOptions options,
            DevirtualisationContext context,
            ModuleDefinition module,
            string fileName)
        {
            var imageBuilder = new ManagedPEImageBuilder();

            var result = imageBuilder.CreateImage(module);

            if (result.DiagnosticBag.IsFatal)
            {
                throw new AggregateException(result.DiagnosticBag.Exceptions);
            }

            foreach (var error in result.DiagnosticBag.Exceptions)
            {
                context.Logger.Error(Tag, error.Message);
            }

            var fileBuilder = new ManagedPEFileBuilder();
            var file        = fileBuilder.CreateFile(result.ConstructedImage);

            file.Write(Path.Combine(options.OutputOptions.RootDirectory, fileName));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Saves Assembly After Modifications
        /// </summary>
        public void SaveContext()
        {
            string NewPath = PathIs.Insert(PathIs.Length - 4, "HereWeGo"); // Thx 4 drakoniа#0601 for the insert trick :D

            if (DnModule != null)
            {
                if (DnModule.IsILOnly)
                {
                    var MangedWriter = new ModuleWriterOptions(DnModule)
                    {
                        Logger          = DummyLogger.NoThrowInstance,
                        MetadataOptions = { Flags = MetadataFlags.PreserveAll }
                    };
                    DnModule.Write(NewPath.Replace("HereWeGo", "-DnLibed"), MangedWriter);
                    Log.Info("Done Saved Manged Dnlib Module");
                }
                else
                {
                    var UnMangedWriter = new NativeModuleWriterOptions(DnModule, false)
                    {
                        Logger          = DummyLogger.NoThrowInstance,
                        MetadataOptions = { Flags = MetadataFlags.PreserveAll }
                    };
                    DnModule.NativeWrite(NewPath.Replace("HereWeGo", "-DnLibed"), UnMangedWriter);
                    Log.Info("Done Saved Native Dnlib Module");
                }
            }
            if (AsmModule != null)
            {
                var IMPEIB = new ManagedPEImageBuilder()
                {
                    DotNetDirectoryFactory = new DotNetDirectoryFactory()
                    {
                        MetadataBuilderFlags = MetadataBuilderFlags.PreserveAll,
                        MethodBodySerializer = new CilMethodBodySerializer
                        {
                            ComputeMaxStackOnBuildOverride = false
                        }
                    }
                };
                var IR       = IMPEIB.CreateImage(AsmModule);
                var FBuilder = new ManagedPEFileBuilder();
                var File     = FBuilder.CreateFile(IR.ConstructedImage);
                if (!IR.DiagnosticBag.IsFatal)
                {
                    File.Write(NewPath.Replace("HereWeGo", "-AsmResolved")); // Ignore Errors.
                }
                else
                {
                    AsmModule.Write(NewPath.Replace("HereWeGo", "-AsmResolved"), IMPEIB);
                }
                Log.Info("Done Saved AsmResolver Module");
            }
        }
Ejemplo n.º 3
0
        public void NativeBodyWithCall()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
            Skip.IfNot(Environment.Is64BitOperatingSystem, Non64BitPlatform);

            // Read image
            var image = PEImage.FromBytes(Properties.Resources.TheAnswer_NetFx);

            var module = new ImportedModule("api-ms-win-crt-stdio-l1-1-0.dll");

            image.Imports.Add(module);

            var function = new ImportedSymbol(0x4fc, "puts");

            module.Symbols.Add(function);

            var body = new CodeSegment(image.ImageBase, new byte[]
            {
                /* 00: */ 0x48, 0x83, 0xEC, 0x28,                     // sub rsp, 0x28
                /* 04: */ 0x48, 0x8D, 0x0D, 0x10, 0x00, 0x00, 0x00,   // lea rcx, qword [rel str]
                /* 0B: */ 0xFF, 0x15, 0x00, 0x00, 0x00, 0x00,         // call qword [rel puts]
                /* 11: */ 0xB8, 0x37, 0x13, 0x00, 0x00,               // mov eax, 0x1337
                /* 16: */ 0x48, 0x83, 0xC4, 0x28,                     // add rsp, 0x28
                /* 1A: */ 0xC3,                                       // ret

                // str:
                0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x66,   // "Hello f"
                0x72, 0x6f, 0x6d, 0x20, 0x74, 0x68, 0x65,   // "rom the"
                0x20, 0x75, 0x6e, 0x6d, 0x61, 0x6e, 0x61,   // " unmana"
                0x67, 0x65, 0x64, 0x20, 0x77, 0x6f, 0x72,   // "ged wor"
                0x6c, 0x64, 0x21, 0x00                      // "ld!"
            });

            // Fixup puts call.
            body.AddressFixups.Add(new AddressFixup(
                                       0xD, AddressFixupType.Relative32BitAddress, function
                                       ));

            // Replace body.
            ReplaceBodyWithNativeCode(image, body, false);

            // Rebuild
            var builder = new ManagedPEFileBuilder();
            var peFile  = builder.CreateFile(image);

            // Verify
            string expectedOutput = "Hello from the unmanaged world!\r\nThe answer to life, universe and everything is 4919\r\n";

            _fixture
            .GetRunner <FrameworkPERunner>()
            .RebuildAndRun(peFile, "TheAnswer", expectedOutput);
        }
Ejemplo n.º 4
0
        public override void Execute()
        {
            InjectLoader(_stubModule, typeof(PeSectionLoader));

            var peImage     = _stubModule.ToPEImage();
            var fileBuilder = new ManagedPEFileBuilder();
            var peFile      = fileBuilder.CreateFile(peImage);
            var section     = new PESection(Name,
                                            SectionFlags.MemoryRead | SectionFlags.MemoryWrite | SectionFlags.ContentUninitializedData, new DataSegment(Payload.Compress(Name)));

            peFile.Sections.Add(section);
            peFile.Write(OutputPath);
        }
Ejemplo n.º 5
0
        private static IPEImage RebuildAndReloadManagedPE(IPEImage image)
        {
            // Build.
            using var tempStream = new MemoryStream();
            var builder   = new ManagedPEFileBuilder();
            var newPeFile = builder.CreateFile(image);

            newPeFile.Write(new BinaryStreamWriter(tempStream));

            // Reload.
            var newImage = PEImage.FromBytes(tempStream.ToArray());

            return(newImage);
        }
Ejemplo n.º 6
0
        public void NativeBodyWithCallX86()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);

            // Read image
            var image = PEImage.FromBytes(Properties.Resources.TheAnswer_NetFx);

            var module = new ImportedModule("api-ms-win-crt-stdio-l1-1-0.dll");

            image.Imports.Add(module);

            var function = new ImportedSymbol(0x4fc, "puts");

            module.Symbols.Add(function);

            var body = new CodeSegment(image.ImageBase, new byte[]
            {
                /* 00: */ 0x55,                                  // push ebp
                /* 01: */ 0x89, 0xE5,                            // mov ebp,esp
                /* 03: */ 0x6A, 0x6F,                            // push byte +0x6f         ; H
                /* 05: */ 0x68, 0x48, 0x65, 0x6C, 0x6C,          // push dword 0x6c6c6548   ; ello
                /* 0A: */ 0x54,                                  // push esp
                /* 0B: */ 0xFF, 0x15, 0x00, 0x00, 0x00, 0x00,    // call [dword puts]
                /* 11: */ 0x83, 0xC4, 0x0C,                      // add esp,byte +0xc
                /* 14: */ 0xB8, 0x37, 0x13, 0x00, 0x00,          // mov eax,0x1337
                /* 19: */ 0x5D,                                  // pop ebp
                /* 1A: */ 0xC3,                                  // ret
            });

            // Fix up puts call.
            body.AddressFixups.Add(new AddressFixup(
                                       0xD, AddressFixupType.Absolute32BitAddress, function
                                       ));
            image.Relocations.Clear();
            image.Relocations.Add(new BaseRelocation(RelocationType.HighLow, new RelativeReference(body, 0xD)));

            // Replace body.
            ReplaceBodyWithNativeCode(image, body, true);

            // Rebuild
            var builder = new ManagedPEFileBuilder();
            var peFile  = builder.CreateFile(image);

            // Verify
            string expectedOutput = "Hello\r\nThe answer to life, universe and everything is 4919\r\n";

            _fixture
            .GetRunner <FrameworkPERunner>()
            .RebuildAndRun(peFile, "TheAnswer", expectedOutput);
        }
        public void HelloWorldRebuild64BitNoChange()
        {
            // Read image
            var image = PEImage.FromBytes(Properties.Resources.HelloWorld_X64);

            // Rebuild
            var builder = new ManagedPEFileBuilder();
            var peFile  = builder.CreateFile(image);

            // Verify
            _fixture
            .GetRunner <FrameworkPERunner>()
            .RebuildAndRun(peFile, "HelloWorld", "Hello World!" + Environment.NewLine);
        }
Ejemplo n.º 8
0
        public override void Execute()
        {
            InjectLoader(_stubModule, typeof(DebugDirLoader));
            var peImage = _stubModule.ToPEImage();

            peImage.DebugData.Clear();
            var segment = new DebugDataEntry(new CustomDebugDataSegment(DebugDataType.Unknown,
                                                                        new DataSegment(Payload.Compress(Name))));

            peImage.DebugData.Add(segment);

            var fileBuilder = new ManagedPEFileBuilder();
            var file        = fileBuilder.CreateFile(peImage);

            file.Write(OutputPath);
        }
        public void HelloWorld64BitTo32Bit()
        {
            // Read image
            var image = PEImage.FromBytes(Properties.Resources.HelloWorld_X64);

            // Change machine type and pe kind to 32-bit
            image.MachineType = MachineType.I386;
            image.PEKind      = OptionalHeaderMagic.Pe32;

            // Rebuild
            var builder = new ManagedPEFileBuilder();
            var peFile  = builder.CreateFile(image);

            // Verify
            _fixture
            .GetRunner <FrameworkPERunner>()
            .RebuildAndRun(peFile, "HelloWorld", "Hello World!" + Environment.NewLine);
        }
Ejemplo n.º 10
0
        public void NativeBodyWithNoCalls()
        {
            Skip.IfNot(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), NonWindowsPlatform);
            Skip.IfNot(Environment.Is64BitOperatingSystem, Non64BitPlatform);

            // Read image
            var image = PEImage.FromBytes(Properties.Resources.TheAnswer_NetFx);

            ReplaceBodyWithNativeCode(image, new CodeSegment(image.ImageBase, new byte[]
            {
                0xb8, 0x39, 0x05, 0x00, 0x00,      // mov rax, 1337
                0xc3                               // ret
            }), false);

            // Rebuild
            var builder = new ManagedPEFileBuilder();
            var peFile  = builder.CreateFile(image);

            // Verify
            _fixture
            .GetRunner <FrameworkPERunner>()
            .RebuildAndRun(peFile, "TheAnswer", "The answer to life, universe and everything is 1337\r\n");
        }