예제 #1
0
        public void CanReadCustomStringSection()
        {
            var loader = new AssemblySystem();

            var dll64   = Path.Combine(loader.BaseDirectory, loader.x64Directory, "RegFreeComResources.dll");
            var stream  = new FileStream(dll64, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            var current = new PeHeaderReader(stream);

            var actual = new List <PeHeaderReader.IMAGE_SECTION_HEADER>();

            for (int headerNo = 0; headerNo < current.ImageSectionHeaders.Length; ++headerNo)
            {
                PeHeaderReader.IMAGE_SECTION_HEADER section = current.ImageSectionHeaders[headerNo];
                actual.Add(section);
            }
            var customSection = actual.Single(x => new String(x.Name).StartsWith(".my_str"));
            var str1          = "MYSTR";

            stream.Seek(customSection.PointerToRawData + str1.Length, SeekOrigin.Begin);
            var reader     = new BinaryReader(stream);
            var customData = reader.ReadChars((int)customSection.SizeOfRawData).Where(x => x != '\0').ToArray();
            var str        = new string(customData);

            StringAssert.Contains(str, "My name is My name is My name is My name name is Last*");
        }
예제 #2
0
        public IMAGE_RESOURCE_DIR_STRING_U(PeHeaderReader pe)
        {
            Length = pe.PeReader.ReadUInt16();

            byte[] arrName = pe.PeReader.ReadBytes(Length * 2);
            NameString = System.Text.Encoding.Unicode.GetString(arrName);
        }
예제 #3
0
        /// <summary>
        /// return the machine type
        /// </summary>
        /// <returns></returns>
        public string GetMachineType(PeHeaderReader reader)
        {
            IMAGE_FILE_HEADER fileHeader = reader.FileHeader;
            UInt16            machine    = fileHeader.Machine;

            //string hexValue = machine.ToString("X");
            switch (machine)
            {
            case 332:
                return("Intel 386");

                break;

            case 512:
                return("Intel 64");

                break;

            case 34404:
                return("AMD 64");

                break;

            default:
                return("Machine type Unknown");

                break;
            }
        }
        public void Pe32BitsLoads64BitsPe()
        {
            var loader = new AssemblySystem();

            var dll64 = Path.Combine(loader.BaseDirectory, loader.x64Directory, "RegFreeComResources.dll");
            var stream = new FileStream(dll64, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            var current = new PeHeaderReader(stream);
        }
예제 #5
0
        public void Pe32BitsLoads64BitsPe()
        {
            var loader = new AssemblySystem();

            var dll64   = Path.Combine(loader.BaseDirectory, loader.x64Directory, "RegFreeComResources.dll");
            var stream  = new FileStream(dll64, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            var current = new PeHeaderReader(stream);
        }
예제 #6
0
        public byte[] GetData(PeHeaderReader pe)
        {
            pe.BaseStream.Position = pe.RVAToFileOffest(resourceInfo.OffsetToData);
            uint length = resourceInfo.Size;

            byte[] buffer = new byte[length];
            pe.BaseStream.Read(buffer, 0, (int)resourceInfo.Size);
            return(buffer);
        }
예제 #7
0
 /// <summary>
 /// check whether the file is 32 bit or not
 /// </summary>
 /// <returns></returns>
 public bool Is32bitFile(PeHeaderReader reader)
 {
     if (GetMachineType(reader) == "Intel 386")
     {
         return(true);
     }
     //     smartSuggestionEngine.readErrorCode(Marshal.GetLastWin32Error());
     return(false);
 }
예제 #8
0
 public TestPage()
 {
     this.DataContext = this;
     InitializeComponent();
     this.Title += " (Build " + PeHeaderReader.GetAssemblyHeader().TimeStamp.ToString() + ")";
     ChartUtilities.AddTestLines(xyLineChart);
     xyLineChart.SubNotes = new string[] { "Right or Middle Mouse Button To Zoom, Left Mouse Button To Pan, Right Double-Click To Reset" };
     copyToClipboard.DoCopyToClipboard = ChartUtilities.CopyChartToClipboard;
     xyLineChart.PointSelected        += xyLineChart_PointSelected;
 }
        public MainWindow()
        {
            _titleSuffix = " - Big CSV File Viewer (Build " + PeHeaderReader.GetAssemblyHeader(typeof(MainWindow)).TimeStamp.ToString() + ") ";
            this.Title   = _titleSuffix;
            InitializeComponent();
            DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(BigTextFileViewer.FilenameProperty, typeof(BigTextFileViewer));

            dpd.AddValueChanged(viewer, (s, e) =>
            {
                this.Title = Path.GetFileName(viewer.Filename) + _titleSuffix;
            });
        }
예제 #10
0
 public CorReader(PeHeaderReader pe)
 {
     var filePath = pe.FilePath;
     using (var mm = MemoryMappedFile.CreateFromFile(filePath, FileMode.Open, Guid.NewGuid().ToString(), 0, MemoryMappedFileAccess.Read))
     {
         using (var view = mm.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read))
         {
             LoadHeaderAndStreams(pe, view);
             LoadMetaTable(pe, view);
         }
     }
 }
        public void Current()
        {
            var current = new PeHeaderReader(typeof(PortableExecutableHeaderReaderTests).Assembly.Location);
            var expected = new List<string> { ".text", ".rsrs", ".reloc" };
            var actual = new List<string>();

            for (int headerNo = 0; headerNo < current.ImageSectionHeaders.Length; ++headerNo)
            {
                PeHeaderReader.IMAGE_SECTION_HEADER section = current.ImageSectionHeaders[headerNo];
               actual.Add(new string(section.Name));
            }
            Assert.AreEqual(expected.Count,actual.Count);
        }
예제 #12
0
        public void Load(PortableExecutable portableExecutable)
        {
            //references to properties of the portableExecutable we are going to load
            String                      FilePath                = portableExecutable.FilePath;
            String                      currentDirectory        = portableExecutable.directoryPath;
            List <string>               listOfBranch            = portableExecutable.listOfBranch;
            List <PortableExecutable>   Dependencies            = portableExecutable.Dependencies;
            List <DependeciesObject>    DependencyNames         = portableExecutable.DependencyNames;
            List <FunctionObject>       ExportedFunctions       = portableExecutable.ExportedFunctions;
            List <ImportFunctionObject> ImportFunctions         = portableExecutable.ImportFunctions;
            List <HeaderObject>         Headers                 = portableExecutable.Headers;
            List <SectionObject>        Sections                = portableExecutable.Sections;
            List <DirectoryObject>      Directories             = portableExecutable.Directories;
            List <string>               ImportNames             = portableExecutable.ImportNames;
            List <string>               importMismatchedFiles   = portableExecutable.importMismatchedFiles;
            List <string>               circularDependencyFiles = portableExecutable.circularDependencyFiles;
            List <ErrorObject>          issues = portableExecutable.issues;
            //the PE Header reader to be used
            PeHeaderReader reader = new PeHeaderReader(FilePath);

            if (Is32bitFile(reader))
            {
                LoadImports(FilePath, true, ImportFunctions, ImportNames);
                LoadExports(FilePath, true, ExportedFunctions);
            }
            else
            {
                Service64Proxy.Service64 proxy = new Service64Proxy.Service64();
                MyObject obj2     = new MyObject();
                MyObject myobject = proxy.Load64Imports(obj2, FilePath, true);
                List <ImportFunctionObject> listOfobj = myobject.FunctionObjectList;
                foreach (ImportFunctionObject importFunctions in listOfobj)
                {
                    ImportFunctions.Add(importFunctions);
                    ImportNames.Add(importFunctions.Dependency);
                }
                ExportObject          exportObject = new ExportObject();
                ExportObject          exports      = proxy.Load64Exports(exportObject, FilePath, true);
                List <FunctionObject> exportList   = exports.ExportFunctionObjectList;
                ExportedFunctions.AddRange(exportList);
            }

            GetHeader(Headers, reader);
            GetAssemblyDependencies(FilePath, ImportFunctions, ImportNames);
            GetAssemblyExports(FilePath, ExportedFunctions);
            GetDirectories(Directories, reader);
            GetSections(Sections, reader);
            LoadDependencies(ImportNames, Dependencies, currentDirectory, FilePath, reader, listOfBranch, this, ImportFunctions, importMismatchedFiles, circularDependencyFiles, issues);
        }
예제 #13
0
        public void Current()
        {
            var current  = new PeHeaderReader(typeof(PortableExecutableHeaderReaderTests).Assembly.Location);
            var expected = new List <string> {
                ".text", ".rsrs", ".reloc"
            };
            var actual = new List <string>();

            for (int headerNo = 0; headerNo < current.ImageSectionHeaders.Length; ++headerNo)
            {
                PeHeaderReader.IMAGE_SECTION_HEADER section = current.ImageSectionHeaders[headerNo];
                actual.Add(new string(section.Name));
            }
            Assert.AreEqual(expected.Count, actual.Count);
        }
예제 #14
0
        public ImageResourceInfo(PeHeaderReader pe, long baseOffest, uint deep)
        {
            this.deep         = deep;
            this.baseOffest   = baseOffest;
            this.pe           = pe;
            resourceDirectory = CommonMethods.RawDeserialize <IMAGE_RESOURCE_DIRECTORY>(pe.BaseStream);

            int count = resourceDirectory.NumberOfNamedEntries + resourceDirectory.NumberOfIdEntries;//资源总数

            lstResourceInfo = new List <ResourceDirectoryEntryInfo>(count);
            for (int i = 0; i < count; i++)
            {
                ResourceDirectoryEntryInfo info = new ResourceDirectoryEntryInfo(pe, baseOffest);
                lstResourceInfo.Add(info);
            }
        }
예제 #15
0
        private void LoadHeaderAndStreams(PeHeaderReader pe, MemoryMappedViewAccessor mm)
        {
            var clrDataDir = pe.DataDirectories[PeHeaderReader.Image_Directory_Entry_Type.COM_DESCRIPTOR];
            if (Marshal.SizeOf(typeof(IMAGE_COR20_HEADER)) != clrDataDir.Size)
                throw new Exception("Size wrong.");

            mm.Read<IMAGE_COR20_HEADER>(pe.GetFileOffset(clrDataDir.VirtualAddress), out mHeader);
            if (mHeader.cb != clrDataDir.Size)
                throw new Exception("Size wrong.");

            var metaLoc = pe.GetFileOffset(mHeader.MetaData.VirtualAddress);
            mm.Read<MetaDataHeaderPart1>(metaLoc, out mMetaHeader);
            var versionBytes = new byte[mMetaHeader.VersionLength];

            metaLoc += Marshal.SizeOf(typeof(MetaDataHeaderPart1));
            mm.ReadArray<byte>(metaLoc, versionBytes, 0, versionBytes.Length);
            int versionSize = 0;
            while (versionSize < versionBytes.Length && versionBytes[versionSize] != 0)
                versionSize++;
            mVersionName = Encoding.ASCII.GetString(versionBytes, 0, versionSize);

            metaLoc += mMetaHeader.VersionLength;
            mMetaDataFlags = mm.ReadUInt16(metaLoc);
            metaLoc += 2;
            uint numberOfMetaStreams = mm.ReadUInt16(metaLoc);
            metaLoc += 2;

            for (int i = 0; i < numberOfMetaStreams; i++)
            {
                MetaDataStream mds;
                mm.Read<MetaDataStream>(metaLoc, out mds);
                metaLoc += Marshal.SizeOf(typeof(MetaDataStream));
                byte b;
                StringBuilder sb = new StringBuilder();
                while ((b = mm.ReadByte(metaLoc++)) != 0)
                {
                    sb.Append((char)b);
                }
                metaLoc += 3;
                metaLoc &= ~3;
                mMetaStreams.Add(sb.ToString(), mds);
            }
        }
예제 #16
0
        internal WardenProcess(string name, int id, string path, ProcessState state, List <string> arguments,
                               ProcessTypes type, List <ProcessFilter> filters)
        {
            Filters   = filters;
            Name      = name;
            Id        = id;
            Path      = path;
            State     = state;
            Arguments = arguments;
            Type      = type;
            Children  = new ObservableCollection <WardenProcess>();
            var epochTicks = new DateTime(1970, 1, 1).Ticks;
            var unixTime   = ((DateTime.UtcNow.Ticks - epochTicks) / TimeSpan.TicksPerSecond);

            TimeStamp = unixTime;
            if (Options.ReadFileHeaders && File.Exists(Path))
            {
                Headers = new PeHeaderReader(Path);
            }
        }
예제 #17
0
        public byte[] GetIconData(PeHeaderReader pe)
        {
            pe.BaseStream.Position = pe.RVAToFileOffest(resourceInfo.OffsetToData);
            uint length = resourceInfo.Size;
            int  star   = 0;

            if (baseItem.Type == ResourceType.Icon)
            {
                length += (uint)arrHead.Length;
                star   += arrHead.Length;
            }
            byte[] buffer = new byte[length];

            if (baseItem.Type == ResourceType.Icon)
            {
                Array.Copy(arrHead, buffer, arrHead.Length);
            }
            pe.BaseStream.Read(buffer, star, (int)resourceInfo.Size);
            return(buffer);
        }
예제 #18
0
        /// <summary>
        /// Loads an assembly from a specific file using the specific reading parameters.
        /// </summary>
        /// <param name="file">The file to read.</param>
        /// <param name="arguments">The reading parameters to use.</param>
        /// <returns></returns>
        /// <exception cref="System.BadImageFormatException"></exception>
        public static Win32Assembly LoadFile(string file, ReadingParameters arguments)
        {
            try
            {
                Win32Assembly a = new Win32Assembly();


                a.path             = file;
                a.ReadingArguments = arguments;
                a.peImage          = PeImage.LoadFromAssembly(a);

                a.headerReader = PeHeaderReader.FromAssembly(a);
                a.ntHeader     = NTHeader.FromAssembly(a);
                a.mzHeader     = MZHeader.FromAssembly(a);
                a.headerReader.LoadData(arguments.IgnoreDataDirectoryAmount);


                if (!arguments.OnlyManaged)
                {
                    a.disassembler            = new x86Disassembler(a);
                    a.assembler               = new x86Assembler(a);
                    a.importExportTableReader = new ImportExportTableReader(a.ntHeader);
                    a.resourcesReader         = new ResourcesReader(a.ntHeader);
                }


                a.netHeader = NETHeader.FromAssembly(a);
                a.peImage.SetOffset(a.ntHeader.OptionalHeader.HeaderSize);

                return(a);
            }
            catch (Exception ex)
            {
                if (ex is AccessViolationException || ex is FileNotFoundException)
                {
                    throw;
                }
                throw new BadImageFormatException("The file is not a valid Portable Executable File.", ex);
            }
        }
예제 #19
0
 /// <summary>
 /// find the directories
 /// </summary>
 /// <returns></returns>
 private void GetDirectories(List <DirectoryObject> Directories, PeHeaderReader reader)
 {
     unsafe
     {
         if (reader.Is32BitHeader)
         {
             PeHeaderReader.IMAGE_OPTIONAL_HEADER32 header32 = reader.OptionalHeader32;
             UInt32 sizeOfHeaders = header32.SizeOfHeaders;
             PeHeaderReader.IMAGE_DATA_DIRECTORY ImportTable       = header32.ImportTable;
             PeHeaderReader.IMAGE_DATA_DIRECTORY ExportTable       = header32.ExportTable;
             PeHeaderReader.IMAGE_DATA_DIRECTORY Resources         = header32.ResourceTable;
             PeHeaderReader.IMAGE_DATA_DIRECTORY loadConfiguration = header32.LoadConfigTable;
             PeHeaderReader.IMAGE_DATA_DIRECTORY delayLoadImport   = header32.DelayImportDescriptor;
             PeHeaderReader.IMAGE_DATA_DIRECTORY Debug             = header32.Debug;
             PeHeaderReader.IMAGE_DATA_DIRECTORY BaseRelocation    = header32.BaseRelocationTable;
             Directories.Add(new DirectoryObject("Import Table", ImportTable.VirtualAddress, ImportTable.Size));
             Directories.Add(new DirectoryObject("Export Table", ExportTable.VirtualAddress, ExportTable.Size));
             Directories.Add(new DirectoryObject("Resource Table", Resources.VirtualAddress, Resources.Size));
             Directories.Add(new DirectoryObject("Load Configuration", loadConfiguration.VirtualAddress, loadConfiguration.Size));
             Directories.Add(new DirectoryObject("Delay Load Import", delayLoadImport.VirtualAddress, delayLoadImport.Size));
         }
         else
         {
             PeHeaderReader.IMAGE_OPTIONAL_HEADER64 header64 = reader.OptionalHeader64;
             UInt64 sizeOfHeaders = header64.SizeOfHeaders;
             PeHeaderReader.IMAGE_DATA_DIRECTORY ImportTable        = header64.ImportTable;
             PeHeaderReader.IMAGE_DATA_DIRECTORY ExportTable        = header64.ExportTable;
             PeHeaderReader.IMAGE_DATA_DIRECTORY Resources          = header64.ResourceTable;
             PeHeaderReader.IMAGE_DATA_DIRECTORY loadConfiguration  = header64.LoadConfigTable;
             PeHeaderReader.IMAGE_DATA_DIRECTORY ImportAddressTable = header64.BoundImport;
             PeHeaderReader.IMAGE_DATA_DIRECTORY delayLoadImport    = header64.DelayImportDescriptor;
             Directories.Add(new DirectoryObject("Import Table", ImportTable.VirtualAddress, ImportTable.Size));
             Directories.Add(new DirectoryObject("Export Table", ExportTable.VirtualAddress, ExportTable.Size));
             Directories.Add(new DirectoryObject("Resource Table", Resources.VirtualAddress, Resources.Size));
             Directories.Add(new DirectoryObject("Load Configuration", loadConfiguration.VirtualAddress, loadConfiguration.Size));
             Directories.Add(new DirectoryObject("Delay Load Import", delayLoadImport.VirtualAddress, delayLoadImport.Size));
         }
     }
     return;
 }
예제 #20
0
        /// <summary>
        /// find the header information
        /// </summary>
        /// <returns></returns>
        private void GetHeader(List <HeaderObject> Headers, PeHeaderReader reader)
        {
            IMAGE_FILE_HEADER fileHeader           = reader.FileHeader;
            UInt16            machine              = fileHeader.Machine;
            UInt16            numberOfSections     = fileHeader.NumberOfSections;
            UInt32            timeDateStamp        = fileHeader.TimeDateStamp;
            UInt32            pointerToSymbolTable = fileHeader.PointerToSymbolTable;
            UInt32            numberOfSymbols      = fileHeader.NumberOfSymbols;
            UInt16            sizeOfOptionalHeader = fileHeader.SizeOfOptionalHeader;
            UInt16            characteristics      = fileHeader.Characteristics;
            string            MachineType          = GetMachineType(reader);
            string            character            = GetCharacterInformation(characteristics);

            Headers.Add(new HeaderObject("Machine", MachineType));
            Headers.Add(new HeaderObject("Number of sections", numberOfSections.ToString()));
            Headers.Add(new HeaderObject("Timestamp", timeDateStamp.ToString()));
            Headers.Add(new HeaderObject("Pointer to symbol table", pointerToSymbolTable.ToString()));
            Headers.Add(new HeaderObject("Number of symbols", numberOfSymbols.ToString()));
            Headers.Add(new HeaderObject("Size of optional header", sizeOfOptionalHeader.ToString()));
            Headers.Add(new HeaderObject("Characteristics", character));
            return;
        }
예제 #21
0
        protected void Read(BinaryReader br)
        {
            // Read initial headers
            PEHeader = PeHeaderReader.Read(br);

            // Read out section information
            SectionHeaders = PeSectionReader.ReadSectionHeaders(PEHeader, br);

            // Read out section data
            CodeSections = PeSectionReader.ReadSections(PEHeader, SectionHeaders,
                                                        br,
                                                        new DebugSectionReader(),
                                                        new ImportSectionReader()
                                                        //new TlsSectionReader()
                                                        //,new ExportSectionReader()
                                                        );

            foreach (var codeSection in CodeSections)
            {
                if (codeSection is CodeViewDebugSection)
                {
                    CodeViewSection = (CodeViewDebugSection)codeSection;

                    // Scan its sections for the sstSrcModule subsection -- in this one, all offset<>line couples are stored
                    var sstSrcModules = new List <sstSrcModule>();
                    foreach (var ss in CodeViewSection.Data.SubsectionDirectory.Sections)
                    {
                        if (ss is sstSrcModule)
                        {
                            sstSrcModules.Add((sstSrcModule)ss);
                        }
                    }
                    sourceModuleSections = sstSrcModules.ToArray();

                    break;
                }
            }
        }
        public void CanReadCustomStringSection()
        {
            var loader = new AssemblySystem();

            var dll64 = Path.Combine(loader.BaseDirectory, loader.x64Directory, "RegFreeComResources.dll");
            var stream = new FileStream(dll64, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            var current = new PeHeaderReader(stream);

            var actual = new List<PeHeaderReader.IMAGE_SECTION_HEADER>();

            for (int headerNo = 0; headerNo < current.ImageSectionHeaders.Length; ++headerNo)
            {
                PeHeaderReader.IMAGE_SECTION_HEADER section = current.ImageSectionHeaders[headerNo];
               actual.Add(section);
            }
            var customSection = actual.Single(x => new String(x.Name).StartsWith(".my_str"));
            var str1 = "MYSTR";
            stream.Seek(customSection.PointerToRawData + str1.Length, SeekOrigin.Begin);
            var reader = new BinaryReader(stream);
            var customData  = reader.ReadChars((int)customSection.SizeOfRawData).Where(x=> x != '\0').ToArray();
            var str = new string(customData);
            StringAssert.Contains(str, "My name is My name is My name is My name name is Last*");
        }
예제 #23
0
        /// <summary>
        /// find the section information for a given file
        /// </summary>
        /// <returns></returns>
        private void GetSections(List <SectionObject> Sections, PeHeaderReader reader)
        {
            PeHeaderReader.IMAGE_SECTION_HEADER[] sections = reader.ImageSectionHeaders;
            IMAGE_FILE_HEADER fileheader      = reader.FileHeader;
            UInt32            numberofSection = fileheader.NumberOfSections;

            foreach (PeHeaderReader.IMAGE_SECTION_HEADER section in sections)
            {
                char[] name                 = section.Name;
                UInt32 virtualAddress       = section.VirtualAddress;
                UInt32 pointerToRawData     = section.PointerToRawData;
                UInt32 virtualSize          = section.VirtualSize;
                UInt32 sizeOFrawData        = section.SizeOfRawData;
                UInt32 pointerToRelocations = section.PointerToRelocations;
                UInt32 pointerToLineNumber  = section.PointerToLinenumbers;
                UInt16 numberOfRelocations  = section.NumberOfRelocations;
                UInt16 NumberOfLineNumbers  = section.NumberOfLinenumbers;
                PeHeaderReader.DataSectionFlags dataSectionFlags = section.Characteristics;
                string nameOfSection = section.Section;

                Sections.Add(new SectionObject(nameOfSection, virtualAddress, virtualSize, pointerToRawData, sizeOFrawData));
            }
            return;
        }
예제 #24
0
 public ImageResourceManager(PeHeaderReader pe, long baseOffest)
 {
     info = new ImageResourceInfo(pe, baseOffest, 0);
     info.LoadInfo();
     FillItems();
 }
예제 #25
0
        public MyObject Load64Imports(MyObject myObject, string filePath, bool mappedAsImage)
        {
            var hLib = LoadLibrary(filePath);

            if (hLib == null)
            {
                var errorCode = GetLastError();
            }
            PeHeaderReader reader = new PeHeaderReader(filePath);

            List <ImportFunctionObject> objList = myObject.FunctionObjectList;

            Console.WriteLine("1st function list");
            unsafe
            {
                void *hMod = (void *)hLib;

                ulong size        = 0;
                ulong BaseAddress = (ulong)hMod;

                if (hMod != null)
                {
                    IMAGE_IMPORT_DESCRIPTOR *pIID = (IMAGE_IMPORT_DESCRIPTOR *)Interop.ImageDirectoryEntryToData((void *)hMod, mappedAsImage, Interop.IMAGE_DIRECTORY_ENTRY_IMPORT, out size);

                    if (pIID != null)
                    {
                        // walk the array until find the end of the array
                        while (pIID->OriginalFirstThunk != 0)
                        {
                            try
                            {
                                //Name contains the RVA to the name of the dll.
                                //Thus convert it to a virtual address first.
                                char *szName = (char *)(BaseAddress + pIID->Name);

                                IntPtr result = new IntPtr(szName);
                                string name   = Marshal.PtrToStringAnsi(result);

                                if (!name.Contains("api-ms-win"))
                                {
                                    // value in OriginalFirstThunk is an RVA.
                                    // convert it to virtual address.
                                    THUNK_DATA64 *pThunkOrg = (THUNK_DATA64 *)(BaseAddress + pIID->OriginalFirstThunk);
                                    while (pThunkOrg->AddressOfData != 0)
                                    {
                                        char *szImportName;
                                        ulong Ord;

                                        if ((pThunkOrg->Ordinal & 0x8000000000000000) > 0)
                                        {
                                            Ord = pThunkOrg->Ordinal & 0xffffffff;
                                        }
                                        else
                                        {
                                            IMAGE_IMPORT_BY_NAME64 *pIBN = (IMAGE_IMPORT_BY_NAME64 *)(BaseAddress + pThunkOrg->AddressOfData);

                                            if (!Interop.IsBadReadPtr((void *)pIBN, (ulong)sizeof(IMAGE_IMPORT_BY_NAME64)))
                                            {
                                                Ord          = pIBN->Hint;
                                                szImportName = (char *)pIBN->Name;
                                                string sImportName = Marshal.PtrToStringAnsi((IntPtr)szImportName);

                                                UInt64 Address = pThunkOrg->Function;

                                                objList.Add(new ImportFunctionObject(sImportName, Address, name));
                                            }
                                            else
                                            {
                                                break;
                                            }
                                        }
                                        pThunkOrg++;
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                System.Diagnostics.Debug.WriteLine("An Access violation occured\n" +
                                                                   "this seems to suggest the end of the imports section\n");
                                System.Diagnostics.Debug.WriteLine(e);
                            }
                            //pIID.size = 40;
                            pIID++;
                        }
                    }
                }
            }
            Console.WriteLine("2nd function list");

            return(myObject);
        }
 public ResourceDirectoryEntryInfo(PeHeaderReader pe, long baseOffest)
 {
     this.pe               = pe;
     this.baseOffest       = baseOffest;
     resourceDirectorEntry = CommonMethods.RawDeserialize <IMAGE_RESOURCE_DIRECTORY_ENTRY>(pe.BaseStream);
 }
예제 #27
0
 private void LoadMetaTable(PeHeaderReader pe, MemoryMappedViewAccessor mm)
 {
     long loc = pe.GetFileOffset(mHeader.MetaData.VirtualAddress + mMetaStreams["#~"].Offset);
     mm.Read<TableHeader>(loc, out mTableHeader);
     Console.WriteLine();
 }
예제 #28
0
        public static void ShowPE(string file)
        {
            using (var fs = new FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read)) {
                // Get the PE timestamp.
                fs.Position = 136;
                byte[] buf = new byte[4];
                fs.Read(buf, 0, 4);
                int t2 = (buf [3] << 24) + (buf [2] << 16) + (buf [1] << 8) + buf [0];
                var d  = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                var d2 = d.AddSeconds(t2);
                fs.Position = 0;

                // Calculate MD5
                var md5  = System.Security.Cryptography.MD5.Create();
                var hash = md5.ComputeHash(fs);
                var sb   = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash [i].ToString("X2"));
                }
                fs.Position = 0;

                var rp       = new ReaderParameters(ReadingMode.Deferred);
                var resolver = new DefaultAssemblyResolver();
                resolver.AddSearchDirectory(Path.GetDirectoryName(file));
                rp.AssemblyResolver = resolver;

                var mod = AssemblyDefinition.ReadAssembly(fs, rp);

                Console.WriteLine("{0} (MD5: {1}) {2}:", file, sb.ToString(), mod.FullName);

                Console.WriteLine("    PE timestamp: {0}", d2);

                // Print the GUID
                Console.WriteLine("    Main module MVID: {0}", mod.MainModule.Mvid);

                Console.WriteLine("    Architecture: {0}", mod.MainModule.Architecture);
                Console.WriteLine("    Runtime: {0}", mod.MainModule.Runtime);
                // Print references
                if (mod.MainModule.HasAssemblyReferences)
                {
                    Console.WriteLine("    References:");
                    foreach (var r in mod.MainModule.AssemblyReferences.OrderBy(v => v.FullName))
                    {
                        Console.WriteLine("        {0}", r.FullName);
                    }
                }
                else
                {
                    Console.WriteLine("    No direct assembly references.");
                }
                if (mod.MainModule.HasCustomAttributes)
                {
                    try {
                        var all_attributes = mod.MainModule.GetCustomAttributes().ToList();
                        var anrs           = new Dictionary <string, List <CustomAttribute> > ();
                        foreach (var ca in all_attributes)
                        {
                            var args = new List <CustomAttributeArgument> ();
                            if (ca.HasConstructorArguments)
                            {
                                args.AddRange(ca.ConstructorArguments);
                            }
                            if (ca.HasFields)
                            {
                                args.AddRange(ca.Fields.Select(v => v.Argument));
                            }
                            if (ca.HasProperties)
                            {
                                args.AddRange(ca.Properties.Select(v => v.Argument));
                            }
                            foreach (var arg in args)
                            {
                                if (arg.Type.Namespace != "System" || arg.Type.Name != "Type")
                                {
                                    continue;
                                }
                                var tr = arg.Value as TypeReference;
                                var ar = tr.Scope as AssemblyNameReference;
                                if (ar == null)
                                {
                                    continue;
                                }
                                if (!anrs.TryGetValue(ar.FullName, out var list))
                                {
                                    anrs [ar.FullName] = list = new List <CustomAttribute> ();
                                }
                                list.Add(ca);
                            }
                        }
                        if (anrs.Count == 0)
                        {
                            Console.WriteLine($"    No assembly references in {all_attributes.Count} custom attributes");
                        }
                        else
                        {
                            Console.WriteLine("    Assembly references in custom attributes:");
                            foreach (var r in anrs.OrderBy(v => v.Key))
                            {
                                Console.WriteLine("        {0}", r.Key);
                                foreach (var ca in r.Value)
                                {
                                    Console.Write($"            {ca.AttributeType.FullName} (");
                                    bool first = true;
                                    if (ca.HasConstructorArguments)
                                    {
                                        foreach (var arg in ca.ConstructorArguments)
                                        {
                                            if (!first)
                                            {
                                                Console.Write(", ");
                                            }
                                            first = false;
                                            Console.Write(arg.Value);
                                        }
                                    }
                                    if (ca.HasFields)
                                    {
                                        foreach (var arg in ca.Fields)
                                        {
                                            if (!first)
                                            {
                                                Console.Write(", ");
                                            }
                                            first = false;
                                            Console.Write($"{arg.Name} = {arg.Argument.Value}");
                                        }
                                    }
                                    if (ca.HasProperties)
                                    {
                                        foreach (var arg in ca.Properties)
                                        {
                                            if (!first)
                                            {
                                                Console.Write(", ");
                                            }
                                            first = false;
                                            Console.Write($"{arg.Name} = {arg.Argument.Value}");
                                        }
                                    }
                                    Console.WriteLine(")");
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine($"    Failed to load custom attributes for '{mod.Name.Name}': {e.Message}");
                    }
                }
                else
                {
                    Console.WriteLine("    No custom attributes.");
                }

                if (mod.MainModule.HasResources)
                {
                    Console.WriteLine($"    {mod.MainModule.Resources.Count} resource(s):");
                    foreach (var res in mod.MainModule.Resources)
                    {
                        switch (res.ResourceType)
                        {
                        case ResourceType.Embedded:
                            var er = (EmbeddedResource)res;
                            Console.WriteLine($"        {res.Name} ({res.ResourceType}) Size: {er.GetResourceData ().Length} bytes");
                            break;

                        default:
                            Console.WriteLine($"        {res.Name} ({res.ResourceType})");
                            break;
                        }
                    }
                }
                else
                {
                    Console.WriteLine("    No embedded resources.");
                }


                if (show_pe_headers)
                {
                    var pe = new PeHeaderReader(file);
                    Console.WriteLine("PE File:");

                    Console.WriteLine("    FileHeader.Machine: {0}", pe.FileHeader.Machine);
                    Console.WriteLine("    FileHeader.NumberOfSections: {0}", pe.FileHeader.NumberOfSections);
                    Console.WriteLine("    FileHeader.TimeDateStamp: {0}", pe.FileHeader.TimeDateStamp);
                    Console.WriteLine("    FileHeader.PointerToSymbolTable: {0}", pe.FileHeader.PointerToSymbolTable);
                    Console.WriteLine("    FileHeader.NumberOfSymbols: {0}", pe.FileHeader.NumberOfSymbols);
                    Console.WriteLine("    FileHeader.SizeOfOptionalHeader: {0}", pe.FileHeader.SizeOfOptionalHeader);
                    Console.WriteLine("    FileHeader.Characteristics: {0}", pe.FileHeader.Characteristics);
                    Console.WriteLine("    Is32BitHeader: {0}", pe.Is32BitHeader);
                    Console.WriteLine("    TimeStamp: {0}", pe.TimeStamp);
                    if (pe.Is32BitHeader)
                    {
                        Console.WriteLine("    OptionalHeader32.Magic: {0}", pe.OptionalHeader32.Magic);
                        Console.WriteLine("    OptionalHeader32.MajorLinkerVersion: {0}", pe.OptionalHeader32.MajorLinkerVersion);
                        Console.WriteLine("    OptionalHeader32.MinorLinkerVersion: {0}", pe.OptionalHeader32.MinorLinkerVersion);
                        Console.WriteLine("    OptionalHeader32.SizeOfCode: {0}", pe.OptionalHeader32.SizeOfCode);
                        Console.WriteLine("    OptionalHeader32.SizeOfInitializedData: {0}", pe.OptionalHeader32.SizeOfInitializedData);
                        Console.WriteLine("    OptionalHeader32.SizeOfUninitializedData: {0}", pe.OptionalHeader32.SizeOfUninitializedData);
                        Console.WriteLine("    OptionalHeader32.AddressOfEntryPoint: {0}", pe.OptionalHeader32.AddressOfEntryPoint);
                        Console.WriteLine("    OptionalHeader32.BaseOfCode: {0}", pe.OptionalHeader32.BaseOfCode);
                        Console.WriteLine("    OptionalHeader32.BaseOfData: {0}", pe.OptionalHeader32.BaseOfData);
                        Console.WriteLine("    OptionalHeader32.ImageBase: {0}", pe.OptionalHeader32.ImageBase);
                        Console.WriteLine("    OptionalHeader32.SectionAlignment: {0}", pe.OptionalHeader32.SectionAlignment);
                        Console.WriteLine("    OptionalHeader32.FileAlignment: {0}", pe.OptionalHeader32.FileAlignment);
                        Console.WriteLine("    OptionalHeader32.MajorOperatingSystemVersion: {0}", pe.OptionalHeader32.MajorOperatingSystemVersion);
                        Console.WriteLine("    OptionalHeader32.MinorOperatingSystemVersion: {0}", pe.OptionalHeader32.MinorOperatingSystemVersion);
                        Console.WriteLine("    OptionalHeader32.MajorImageVersion: {0}", pe.OptionalHeader32.MajorImageVersion);
                        Console.WriteLine("    OptionalHeader32.MinorImageVersion: {0}", pe.OptionalHeader32.MinorImageVersion);
                        Console.WriteLine("    OptionalHeader32.MajorSubsystemVersion: {0}", pe.OptionalHeader32.MajorSubsystemVersion);
                        Console.WriteLine("    OptionalHeader32.MinorSubsystemVersion: {0}", pe.OptionalHeader32.MinorSubsystemVersion);
                        Console.WriteLine("    OptionalHeader32.Win32VersionValue: {0}", pe.OptionalHeader32.Win32VersionValue);
                        Console.WriteLine("    OptionalHeader32.SizeOfImage: {0}", pe.OptionalHeader32.SizeOfImage);
                        Console.WriteLine("    OptionalHeader32.SizeOfHeaders: {0}", pe.OptionalHeader32.SizeOfHeaders);
                        Console.WriteLine("    OptionalHeader32.CheckSum: {0}", pe.OptionalHeader32.CheckSum);
                        Console.WriteLine("    OptionalHeader32.Subsystem: {0}", pe.OptionalHeader32.Subsystem);
                        Console.WriteLine("    OptionalHeader32.DllCharacteristics: {0}", pe.OptionalHeader32.DllCharacteristics);
                        Console.WriteLine("    OptionalHeader32.SizeOfStackReserve: {0}", pe.OptionalHeader32.SizeOfStackReserve);
                        Console.WriteLine("    OptionalHeader32.SizeOfStackCommit: {0}", pe.OptionalHeader32.SizeOfStackCommit);
                        Console.WriteLine("    OptionalHeader32.SizeOfHeapReserve: {0}", pe.OptionalHeader32.SizeOfHeapReserve);
                        Console.WriteLine("    OptionalHeader32.SizeOfHeapCommit: {0}", pe.OptionalHeader32.SizeOfHeapCommit);
                        Console.WriteLine("    OptionalHeader32.LoaderFlags: {0}", pe.OptionalHeader32.LoaderFlags);
                        Console.WriteLine("    OptionalHeader32.NumberOfRvaAndSizes: {0}", pe.OptionalHeader32.NumberOfRvaAndSizes);
                    }
                    else
                    {
                    }

                    foreach (var section in pe.ImageSectionHeaders)
                    {
                        var c = Array.IndexOf(section.Name, (char)0);
                        Console.WriteLine("    ImageSectionHeaders.Name: {0}", new string (section.Name, 0, c == -1 ? section.Name.Length : c));
                        Console.WriteLine("    ImageSectionHeaders.VirtualSize: {0}", section.VirtualSize);
                        Console.WriteLine("    ImageSectionHeaders.VirtualAddress: {0}", section.VirtualAddress);
                        Console.WriteLine("    ImageSectionHeaders.SizeOfRawData: {0}", section.SizeOfRawData);
                        Console.WriteLine("    ImageSectionHeaders.PointerToRawData: {0}", section.PointerToRawData);
                        Console.WriteLine("    ImageSectionHeaders.PointerToRelocations: {0}", section.PointerToRelocations);
                        Console.WriteLine("    ImageSectionHeaders.PointerToLinenumbers: {0}", section.PointerToLinenumbers);
                        Console.WriteLine("    ImageSectionHeaders.NumberOfRelocations: {0}", section.NumberOfRelocations);
                        Console.WriteLine("    ImageSectionHeaders.NumberOfLinenumbers: {0}", section.NumberOfLinenumbers);
                        Console.WriteLine("    ImageSectionHeaders.Characteristics: {0}", section.Characteristics);
                    }
                }
            }
        }
        public string ReadBinaryHash(string binaryFilePath)
        {
            var reader = new PeHeaderReader(binaryFilePath);

            return(reader.FileHeader.TimeDateStamp.ToString("X") + (reader.Is32BitHeader ? reader.OptionalHeader32.SizeOfImage : reader.OptionalHeader64.SizeOfImage).ToString("X"));
        }
예제 #30
0
        public static int Initialize(GameWindow window)
        {
            uint processId;

            GetWindowThreadProcessId(window.Handle, out processId);

            if(processId == 0)
            {
                return -1;
            }

            const int access = ProcessQueryInformation|ProcessVmRead;

            window.OpenHandle = OpenProcess(access, true, (int)processId);

            var process = Process.GetProcessById((int)processId);

            string path = process.MainModule.FileName;

            var reader = new PeHeaderReader(path);

            var processHandle = window.OpenHandle.ToInt32();

            for (int i = 0; i < reader.ImageSectionHeaders.Length; i++ )
            {
                var currentSection = reader.ImageSectionHeaders[i];

                if(!currentSection.HasFlag(PeHeaderReader.DataSectionFlags.MemoryExecute))
                {
                    continue;
                }

                var address = currentSection.VirtualAddress + reader.OptionalHeader32.ImageBase;

                if (window.PositionAddress == 0)
                {
                    short[] pattern = { 0x8B, 0x15, -1, -1, -1, -1, 0x8B, 0x01, 0x8B, 0x40, 0x54, 0x52, 0x8B, 0x15 };

                     // ~6.0.14.4 - 7.x (Stygian Abyss to High Seas+)
                    if (Pattern.PatternSearch(processHandle, address, currentSection.VirtualSize, pattern) > 0)
                    {
                        window.PositionAddress = ((pattern[5] << 24) + (pattern[4] << 16) + (pattern[3] << 8) + pattern[2]) - 4;
                    }
                }

                if (window.CharacterAddress == 0)
                {
                    short[] pattern = { 0xE8, -1, -1, -1, -1, 0x68, -1, -1, -1, -1, 0x68, -1, -1, -1, -1, 0x57, 0xE8, -1, -1, -1, -1, 0x83, 0xC4, -1, 0x68, -1, -1, -1, -1 };

                    if (Pattern.PatternSearch(processHandle, address, currentSection.VirtualSize, pattern) > 0)
                    {
                        window.ServerAddress = ((pattern[9] << 24) + (pattern[8] << 16) + (pattern[7] << 8) + pattern[6]);
                        window.CharacterAddress = ((pattern[28] << 24) + (pattern[27] << 16) + (pattern[26] << 8) + pattern[25]);
                    }
                }

                // 4.0.11d - ~6.0.9.x (Mondain's Legacy to Kingdom Reborn+)
                if (window.PositionAddress == 0)
                {
                    short[] pattern = { 0x8B, 0x0D, -1, -1, -1, -1, 0x53, 0x55, 0x56, 0x8B, 0x35 };

                     // ~6.0.14.4 - 7.x (Stygian Abyss to High Seas+)
                    if (Pattern.PatternSearch(processHandle, address, currentSection.VirtualSize, pattern) > 0)
                    {
                        window.PositionAddress = ((pattern[5] << 24) + (pattern[4] << 16) + (pattern[3] << 8) + pattern[2]) - 4;
                    }
                }

                if (window.CharacterAddress == 0)
                {
                    short[] pattern = { 0x83, 0xC4, -1, 0x68, -1, -1, -1, -1, 0x68, -1, -1, -1, -1, 0x57, 0xE8, -1, -1, -1, -1, 0x83, 0xC4, -1, 0x68, -1, -1, -1, -1, 0x68, -1, -1, -1, -1, 0x57, 0xE8, -1, -1, -1, -1, 0x8B, 0x54, 0x24 };

                    if (Pattern.PatternSearch(processHandle, address, currentSection.VirtualSize, pattern) > 0)
                    {
                        window.ServerAddress = ((pattern[7] << 24) + (pattern[6] << 16) + (pattern[5] << 8) + pattern[4]);
                        window.CharacterAddress = ((pattern[26] << 24) + (pattern[25] << 16) + (pattern[24] << 8) + pattern[23]);
                    }
                }
            }
            return 0;
        }
        public FindGameResult FindGame(string gameName, out String error, bool findUsingTitle = true, bool useContains = false)
        {
            error = "";
            if (findUsingTitle)
            {
                Process[] processes = Process.GetProcesses();
                foreach (Process process in processes)
                {
                    //Sleep to stop Insane CPU Usage:
                    String titleName = process.MainWindowTitle;
                    Thread.Sleep(1);
                    if (String.CompareOrdinal(titleName, gameName) == 0 || (useContains && titleName.Contains(gameName)))
                    {
                        pGame = process;
                        break;
                    }
                }
            }
            else
            {
                Process[] processes = Process.GetProcessesByName(gameName);
                if (processes.Count() != 0)
                {
                    pGame = processes[0];
                }
            }

            if (pGame != null)
            {
                try
                {
                    _processHandle =
                        OpenProcess(ProcessQueryInformation | ProcessCreateThread | ProcessWmRead | ProcessVmOperation | ProcessVmWrite, false,
                                    pGame.Id);

                    //TODO: double check this
                    if (pGame.ProcessName == "dwm")
                    {
                        return(FindGameResult.GameNotFound);
                    }

                    _hThread    = OpenThread(ThreadAccess.SuspendResume | ThreadAccess.GetContext | ThreadAccess.SetContext, false, (uint)pGame.Threads[0].Id);
                    _baseModule = pGame.MainModule.BaseAddress;
                    _moduleSize = pGame.MainModule.ModuleMemorySize;

                    if ((uint)_baseModule == 0xdeadbabe)
                    {
                        PeHeaderReader reader = new PeHeaderReader(pGame.MainModule.FileName);
                        _baseModule = (IntPtr)((uint)pGame.MainModule.EntryPointAddress - reader.OptionalHeader32.AddressOfEntryPoint);
                        _moduleSize = (int)reader.OptionalHeader32.SizeOfImage;
                    }

                    pGame.EnableRaisingEvents = true;
                    pGame.Exited += ProcessExited;
                    return(FindGameResult.GameFound);
                }
                catch (Exception e)
                {
                    error = FlattenException(e);
                    return(FindGameResult.OpenProcessIssue);
                }
            }

            return(FindGameResult.GameNotFound);
        }
예제 #32
0
        private static void Process(PeHeaderReader pe, AssemblyDefinition asm, MemoryMappedFile mappedFile)
        {
            foreach (var m in asm.MainModule.Types.SelectMany(t => t.Methods))
            {
                if (!m.HasBody)
                    continue;
                var body = m.Body;
                //Console.WriteLine("{0,-40}{1:x}{2,10:x}{3,10:x}", m.Name, m.RVA, body.LengthOnDisk, body.IndexAfterCode);

                if (RequiresFatHeader(body))
                {
                    flags.Write(body.Flags);
                    maxStack.Write((UInt16)body.MaxStackSize);
                    codeSize.Write(body.CodeSize);
                    localVar.Write(body.LocalVarToken.ToUInt32());
                }
                else
                {
                    flags.Write((byte)(0x2 | (body.CodeSize << 2)));
                }

                foreach (var instr in body.Instructions)
                {
                    if (instr.OpCode.Size == 1)
                        opcodes.Write(instr.OpCode.Op2);
                    else
                    {
                        opcodes.Write(instr.OpCode.Op1);
                        opcodes.Write(instr.OpCode.Op2);
                    }

                    var operand = instr.Operand;
                    switch (instr.OpCode.OperandType)
                    {
                        case OperandType.InlineSwitch:
                            {
                                var targets = (Instruction[])operand;
                                switches.Write(targets.Length);
                                for (int i = 0; i < targets.Length; i++)
                                    switches.Write(GetTargetOffset(body, targets[i]));
                                break;
                            }
                        case OperandType.ShortInlineBrTarget:
                            {
                                var target = (Instruction)operand;
                                sbyteBranch.Write((sbyte)GetTargetOffset(body, target));
                                break;
                            }
                        case OperandType.InlineBrTarget:
                            {
                                var target = (Instruction)operand;
                                intBranch.Write(GetTargetOffset(body, target));
                                break;
                            }
                        case OperandType.ShortInlineVar:
                            varIndex.Write((byte)((VariableDefinition)operand).Index);
                            break;
                        case OperandType.ShortInlineArg:
                            varIndex.Write((byte)GetParameterIndex(body, (ParameterDefinition)operand));
                            break;
                        case OperandType.InlineVar:
                            varIndex.Write((short)((VariableDefinition)operand).Index);
                            break;
                        case OperandType.InlineArg:
                            varIndex.Write((short)GetParameterIndex(body, (ParameterDefinition)operand));
                            break;
                        case OperandType.InlineSig:
                            sigToken.Write(((CallSite)operand).MetadataToken.ToUInt32());
                            break;
                        case OperandType.ShortInlineI:
                            if (instr.OpCode == OpCodes.Ldc_I4_S)
                                inlineInt.Write((sbyte)operand);
                            else
                                inlineInt.Write((byte)operand);
                            break;
                        case OperandType.InlineI:
                            inlineInt.Write((int)operand);
                            break;
                        case OperandType.InlineI8:
                            inlineInt.Write((long)operand);
                            break;
                        case OperandType.ShortInlineR:
                            inlieFloat.Write((float)operand);
                            break;
                        case OperandType.InlineR:
                            inlieFloat.Write((double)operand);
                            break;
                        case OperandType.InlineString:
                            strTokens.Write(instr.StringOperandToken.ToUInt32());
                            break;
                        case OperandType.InlineType:
                        case OperandType.InlineField:
                        case OperandType.InlineMethod:
                        case OperandType.InlineTok:
                            otherTokens.Write(((IMetadataTokenProvider)operand).MetadataToken.ToUInt32());
                            break;
                        case OperandType.InlineNone:
                            break;
                        default:
                            throw new ArgumentException();
                    }
                    //write some code
                }

                using (var mm = mappedFile.CreateViewAccessor(pe.GetFileOffset(m.RVA), body.LengthOnDisk, MemoryMappedFileAccess.Read))
                {
                    for (int i = body.IndexAfterCode; i < body.LengthOnDisk; i++)
                    {
                        exceptionStuff.Write(mm.ReadByte(i));
                    }

                    //do a full copy of the method
                    for (int i = 0; i < body.LengthOnDisk; i++)
                    {
                        fullMethods.Write(mm.ReadByte(i));
                    }
                }
            }
        }
예제 #33
0
        /// <summary>
        /// return the file path of a given file
        /// input is file name and the current directory name
        /// </summary>
        /// <param name="moduleName"></param>
        /// <param name="currentDirectory"></param>
        /// <returns></returns>


        private List <String> GetModulePath(String moduleName, String currentDirectory, String FilePath, PeHeaderReader reader)
        {
            List <string> files = new List <string>();
            // iteratedDirectoryPath.Clear();
            // 0. Look in well-known dlls list

            // 1. Look in application folder
            string applicationFolder = Path.GetDirectoryName(FilePath);

            files.AddRange(GetFiles(applicationFolder, moduleName));

            Environment.SpecialFolder WindowsSystemFolder;

            // try 32 - bit,64 - bit
            if (Is32bitFile(reader))
            {
                WindowsSystemFolder = Environment.SpecialFolder.SystemX86;
            }
            else
            {
                WindowsSystemFolder = Environment.SpecialFolder.System;
            }

            string WindowsSystemFolderPath = Environment.GetFolderPath(WindowsSystemFolder);

            files.AddRange(GetFiles(WindowsSystemFolderPath, moduleName));



            //try windows folder
            WindowsSystemFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            files.AddRange(GetFiles(WindowsSystemFolderPath, moduleName));

            //try the folders inside PATH Environmental variable
            string        PATH        = Environment.GetEnvironmentVariable("PATH");
            List <String> PATHFolders = new List <string>(PATH.Split(';'));

            foreach (String SystePath in PATHFolders)
            {
                if (SystePath != "" && !SystePath.Contains(WindowsSystemFolderPath))
                {
                    files.AddRange(GetFiles(SystePath, moduleName));
                }
            }

            //check in current directory
            files.AddRange(GetFiles(currentDirectory, moduleName));


            return(files);
        }
예제 #34
0
 internal void Initialize(PeHeaderReader reader)
 {
     //header = assembly.headerreader;
     //
     //fheader.header = header;
     //if (header.Is32BitHeader)
     //    oheader = OptionalHeader32.FromAssembly(assembly);
     //else
     //    oheader = OptionalHeader64.FromAssembly(assembly);
 }
예제 #35
0
        static void Main(string[] args)
        {
            var pe = new PeHeaderReader(FILE);
            var head = new CorReader(pe);

            var asm = AssemblyDefinition.ReadAssembly(FILE);
            using (var mappedFile = MemoryMappedFile.CreateFromFile(FILE, FileMode.Open, Guid.NewGuid().ToString(), 0, MemoryMappedFileAccess.Read))
            {
                Process(pe, asm, mappedFile);
            }

            var fatStream = new MemoryStream(0x1000);

            foreach (var s in typeof(Program).GetFields(BindingFlags.NonPublic | BindingFlags.Static)
                .Where(f => f.Name != "fullMethods")
                .Where(f => f.FieldType == typeof(LilByteStream))
                .Select(f => new { Field = f, Stream = (LilByteStream)f.GetValue(null) }))
            {
                var name = s.Field.Name;
                Console.WriteLine("{0}: {1,-10}", name, s.Stream.Length);
                s.Stream.CloseAndCopy(fatStream);
            }

            Console.WriteLine();

            Console.WriteLine("Full Method Copy size: {0}", fullMethods.Length);
            Console.WriteLine("Squished Together size: {0}", fatStream.Length);

            Console.WriteLine();

            var fullSize = CompressStream(fullMethods.Stream, "Full Copy");
            var compressedSize = CompressStream(fatStream, "Sorted");

            Console.WriteLine("Full size:       {0} ({1})", fullSize, (double)fullSize / fullMethods.Length);
            Console.WriteLine("Compressed size: {0} ({1})", compressedSize, (double)compressedSize / fatStream.Length);
            Console.WriteLine("Ratio: {0}", (double)compressedSize / (double)fullSize);
        }
예제 #36
0
        /// <summary>
        /// Load each of the dependencies as a Portable Executable Object
        /// </summary>
        /// <returns> The Dependencies in a Portable Executable File Format </returns>
        private void LoadDependencies(List <string> ImportNames, List <PortableExecutable> Dependencies, String currentDirectory, String FilePath, PeHeaderReader reader, List <string> listOfBranch, PortableExecutableLoader portableExecutableLoader, List <ImportFunctionObject> importFunctions, List <string> importMismatchedFiles, List <string> circularDependencyFiles, List <ErrorObject> issues)
        {
            PortableExecutable PE;
            string             filePath;

            unsafe
            {
                try
                {
                    ImportNames = ImportNames.Distinct().ToList();
                    foreach (string name in ImportNames)
                    {
                        filePath = null;

                        if (!filePathsTable.ContainsKey(name))
                        {
                            var importedFunction = from import in importFunctions
                                                   where import.Dependency == name
                                                   select import.Function;
                            List <String> importedFunctionNames = new List <string>();
                            importedFunctionNames.AddRange(importedFunction);



                            foreach (String path in GetModulePath(name, currentDirectory, FilePath, reader))
                            {
                                List <FunctionObject> exportsOfFile = new List <FunctionObject>();

                                List <string> exportsFunctionNames = new List <string>();
                                if (path != null)
                                {
                                    LoadExports(path, true, exportsOfFile);
                                    foreach (FunctionObject exports in exportsOfFile)
                                    {
                                        exportsFunctionNames.Add(exports.Function);
                                    }
                                    var firstNotSecond = importedFunctionNames.Except(exportsFunctionNames).ToList();
                                    //   filePath = path;
                                    if (string.Equals(name, "kernel32.dll", StringComparison.OrdinalIgnoreCase) || string.Equals(name, "msvcrt.dll", StringComparison.OrdinalIgnoreCase))
                                    {
                                        filePath = GetModulePath(name, currentDirectory, FilePath, reader).First();
                                        break;
                                    }
                                    else if (!importedFunctionNames.Except(exportsFunctionNames).Any())
                                    {
                                        filePath = path;
                                        break;
                                    }
                                }
                            }
                        }

                        else
                        {
                            filePath = filePathsTable[name].ToString();
                        }

                        if (filePath == null)
                        {
                            if (GetModulePath(name, currentDirectory, FilePath, reader).Count > 0)
                            {
                                //   importMismatchedFiles.Add(name);
                                issues.Add(new ErrorObject(name, "Imports and Export mismatch found"));
                                //Suggestion for import export mismatch error
                                smartSuggestionEngine.readErrorCode(name, 4);
                            }
                            else
                            {
                                issues.Add(new ErrorObject(name, "File path not found"));
                                //Suggestion for null file path
                                smartSuggestionEngine.readErrorCode(name, 5);
                            }
                        }
                        var hLib2 = LoadLibraryEx(filePath, 0,
                                                  DONT_RESOLVE_DLL_REFERENCES | LOAD_IGNORE_CODE_AUTHZ_LEVEL);
                        if (listOfBranch.Contains(name))
                        {
                            //  circularDependencyFiles.Add(name);
                            issues.Add(new ErrorObject(name, "Circular dependency is detected"));
                            //Suggestion for circular dependency
                            smartSuggestionEngine.readErrorCode(name, 6);
                            continue;
                        }
                        else
                        {
                            List <string> newBranchList = listOfBranch.ToList();
                            newBranchList.Add(name);
                            if (!CheckLibrary(name))
                            {
                                PE = new PortableExecutable(name, filePath, true, newBranchList);
                            }
                            else
                            {
                                PE = new PortableExecutable(name, filePath, false, newBranchList);
                            }
                            // Dependencies.Add(PE);
                            portableExecutableLoader.Load(PE);
                            Dependencies.Add(PE);
                        }
                    }
                }
                //To catch error in dependencies
                catch (Exception) {
                }
                return;
            }
        }
예제 #37
0
        static void ShellExecCmdLine(IntPtr hInstance, IntPtr hwnd, string command, string startDir, global::System.Diagnostics.ProcessWindowStyle nShow, ShellExecCmdLineFlags dwSeclFlags)
        {
            string cmd = command;
            string args = null;
            if (UrlIs(command, URLIS_URL))
                cmd = command;
            else
            {
                if (global::System.Environment.OSVersion.Version.Major >= 6)
                    EvaluateSystemAndUserCommandLine(cmd, startDir, out cmd, out args, dwSeclFlags);
                else
                    EvaluateUserCommandLine(cmd, startDir, out cmd, out args);
            }

            if (!UrlIs(cmd, URLIS_URL)
                && (
                    (dwSeclFlags & ShellExecCmdLineFlags.SECL_USEFULLPATHDIR) == ShellExecCmdLineFlags.SECL_USEFULLPATHDIR
                    || startDir == null
                    || startDir.Length == 0))
            {
                string dir = QualifyWorkingDir(cmd);
                if (dir != null)
                    startDir = dir;
            }

            if (UserSettingStorage.Instance.LeaveCmdOpen && File.Exists(cmd))
            {
                bool needsCommandLine;

                try
                {

                    var peHeaderReader = new PeHeaderReader(cmd);

                    if (peHeaderReader.Is32BitHeader)
                        needsCommandLine = peHeaderReader.OptionalHeader32.Subsystem == 3; // IMAGE_SUBSYSTEM_WINDOWS_CUI == 3
                    else
                        needsCommandLine = peHeaderReader.OptionalHeader64.Subsystem == 3;
                }

                catch (Exception)
                {
                    // Error reading the headers. We will try to run the command the standard way.
                    needsCommandLine = false;
                }

                if (needsCommandLine)
                {
                    string cmdExe;
                    string dummy;
                    EvaluateSystemAndUserCommandLine("cmd.exe", startDir, out cmdExe, out dummy, dwSeclFlags);

                    // check whether user typed >cmd, because we don't want to create 2 nested shells
                    if (cmdExe != cmd)
                    {
                        args = string.Format("/k {0} {1}", cmd, args);
                        cmd = cmdExe;
                    }
                }
            }

            global::System.Diagnostics.ProcessStartInfo startInfo = new global::System.Diagnostics.ProcessStartInfo();
            startInfo.UseShellExecute = true;
            startInfo.Arguments = args;
            startInfo.FileName = cmd;
            startInfo.WindowStyle = global::System.Diagnostics.ProcessWindowStyle.Normal;
            startInfo.ErrorDialog = (dwSeclFlags | ShellExecCmdLineFlags.SECL_NO_UI) == 0;
            startInfo.ErrorDialogParentHandle = hwnd;

            try
            {
                global::System.Diagnostics.Process.Start(startInfo);
            }
            catch (Exception e)
            {
                if (!startInfo.ErrorDialog)
                    throw e;
            }
        }
예제 #38
0
        public async Task <int> SignAsync(string signTool,
                                          string signToolArgs,
                                          string file,
                                          string keyVaultCertificateName,
                                          string keyVaultUrl,
                                          string keyVaultClientId,
                                          string keyVaultClientSecret,
                                          string keyVaultAccessToken)
        {
            /* We need to do a few things here.
             *
             * 1. Get an access token if one is not provided. If one is provided, we assume it's valid.
             * 2. Download and save the certificate. We do this each time as a way to verify credentials and the certificate name
             * 3. Pass the location of the cert to SignTool via the -f parameter.
             * 4. Pass the file to sign for SignTool
             *
             */

            string validatedToken = null;

            async Task <string> Authenticate(string authority, string resource, string scope)
            {
                if (!string.IsNullOrWhiteSpace(keyVaultAccessToken))
                {
                    validatedToken = keyVaultAccessToken;
                    return(keyVaultAccessToken);
                }

                var context    = new AuthenticationContext(authority);
                var credential = new ClientCredential(keyVaultClientId, keyVaultClientSecret);

                var result = await context.AcquireTokenAsync(resource, credential).ConfigureAwait(false);

                if (result == null)
                {
                    throw new InvalidOperationException("Authentication to Azure failed.");
                }
                validatedToken = result.AccessToken;
                return(result.AccessToken);
            }

            var client = new KeyVaultClient(Authenticate, new HttpClient());

            // We call this here to verify it's a valid cert
            // It also implicitly validates the access token or credentials
            var kvcert = await client.GetCertificateAsync(keyVaultUrl, keyVaultCertificateName).ConfigureAwait(false);

            var fileName = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), "KeyVaultCerts", $"{keyVaultCertificateName}.cer");

            Directory.CreateDirectory(Path.GetDirectoryName(fileName));
            File.WriteAllBytes(fileName, kvcert.Cer);

            // path to our helper library
            var location = Path.GetDirectoryName(typeof(Program).Assembly.Location);
            var dir      = new DirectoryInfo(location);

            // See if the signtool is x86 or x64
            var peReader    = new PeHeaderReader(signTool);
            var platformDir = peReader.Is32BitHeader ? "x86" : "x64";

            var dlibLocation = Path.Combine(dir.FullName, platformDir, "KeyVaultSigner.dll");

            signToolArgs += $@" /dlib ""{dlibLocation}"" ";

            signToolArgs += $@" /f ""{fileName}"" ""{file}"" ";

            var psi = new ProcessStartInfo
            {
                FileName       = signTool,
                Arguments      = signToolArgs,
                CreateNoWindow = true,
                Environment    =
                {
                    { "KEYVAULT_ACCESSTOKEN",    validatedToken                  },
                    { "KEYVAULT_KEY_IDENTIFIER", kvcert.KeyIdentifier.Identifier }
                },
                RedirectStandardError  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false
            };

            var process = Process.Start(psi);

            var output = process.StandardOutput.ReadToEnd();
            var error  = process.StandardError.ReadToEnd();

            application.Out.Write(output);
            application.Error.WriteLine(error);
            process.WaitForExit();

            return(process.ExitCode);
        }