Beispiel #1
0
 public static ModuleDefMD OpenModule(string filename)
 {
     var ctx = ModuleDefMD.CreateModuleContext();
     var peImage = new PEImage(File.ReadAllBytes(filename), filename);
     var mod = ModuleDefMD.Load(peImage, ctx);
     ctx.AssemblyResolver.AddToCache(mod);
     return mod;
 }
		/// <summary>
		/// Create a <see cref="DotNetFile"/> instance
		/// </summary>
		/// <param name="fileName">The file to load</param>
		/// <returns>A new <see cref="DotNetFile"/> instance</returns>
		public static DotNetFile Load(string fileName) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(fileName));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
Beispiel #3
0
		/// <summary>
		/// Create a <see cref="MetaData"/> instance
		/// </summary>
		/// <param name="data">The .NET file data</param>
		/// <returns>A new <see cref="MetaData"/> instance</returns>
		internal static MetaData Load(byte[] data) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(data));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
Beispiel #4
0
		/// <summary>
		/// Create a <see cref="MetaData"/> instance
		/// </summary>
		/// <param name="fileName">The file to load</param>
		/// <returns>A new <see cref="MetaData"/> instance</returns>
		internal static MetaData Load(string fileName) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(fileName));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
		/// <summary>
		/// Create a <see cref="DotNetFile"/> instance
		/// </summary>
		/// <param name="data">The .NET file data</param>
		/// <returns>A new <see cref="DotNetFile"/> instance</returns>
		public static DotNetFile Load(byte[] data) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(data));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
Beispiel #6
0
 public ECallListReader(string filename)
 {
     this.peImage = new PEImage(filename);
     this.reader = peImage.CreateFullStream();
     this.is32bit = peImage.ImageNTHeaders.OptionalHeader.Magic == 0x010B;
     this.ptrSize = is32bit ? 4U : 8;
     var last = peImage.ImageSectionHeaders[peImage.ImageSectionHeaders.Count - 1];
     this.endRva = (uint)last.VirtualAddress + last.VirtualSize;
     this.list = new List<ECClass>();
     this.tableFormat = null;
     Read();
 }
Beispiel #7
0
		public dnModule(byte[] module, string fileName, ModuleContext ctx) {
			RawData = module;
			ErrorMessage = null;
			Name = Path.GetFileName(fileName);

			var creator = new dnModuleStreamCreator(module, fileName);
			try {
				Image = new PEImage(creator, ImageLayout.File, true);
			}
			catch (Exception ex) {
				ErrorMessage += string.Format("Error while loading PE Image:{0}{1}{0}{0}",
					Environment.NewLine, ex);

				Image = null;
				return;
			}

			try {
				MetaData = MetaDataCreator.CreateMetaData(Image);
			}
			catch (Exception ex) {
				ErrorMessage += string.Format("Error while loading MetaData:{0}{1}{0}{0}",
					Environment.NewLine, ex);

				MetaData = null;
				return;
			}

			try {
				ModuleDef = (ModuleDefMD)loadInternal.Invoke(null, new object[] {
					MetaData, new ModuleCreationOptions {
						TryToLoadPdbFromDisk = true,
						Context = ctx
					}
				});
				ModuleDef.EnableTypeDefFindCache = true;
			}
			catch (Exception ex) {
				ErrorMessage = string.Format("Error while loading ModuleDef:{0}{1}{0}{0}",
					Environment.NewLine, ex);

				ModuleDef = null;
				return;
			}

			if (ModuleDef.Assembly != null)
				Name = ModuleDef.Assembly.Name;
			else
				Name = ModuleDef.Name;
			if (string.IsNullOrEmpty(Name))
				Name = Path.GetFileName(fileName);
		}
Beispiel #8
0
        public frmSecView(dnlib.PE.PEImage myPe, string peFileName)
        {
            //Debug.WriteLine("[frmSecView]");
            log.Log(LogType.Normal, "frmSecView");

            this.is64 = myPe.ImageNTHeaders.FileHeader.Machine == Machine.AMD64 |
                        myPe.ImageNTHeaders.FileHeader.Machine == Machine.IA64;

            this.InitializeComponent();
            this.myPeFileName = peFileName;
            foreach (var a in myPe.ImageSectionHeaders)
            {
                this.reaperListView1.Items.Add(new ListViewItem(new[] { Encoding.ASCII.GetString(a.Name), ((uint)a.VirtualAddress).ToString("X8"), ((uint)a.VirtualSize).ToString("X8"), ((uint)myPe.ToFileOffset(a.VirtualAddress)).ToString("X8"), (a.SizeOfRawData).ToString("X8"), (a.Characteristics).ToString("X8") }));
            }
        }
Beispiel #9
0
		/// <summary>
		/// Create a <see cref="MetaData"/> instance
		/// </summary>
		/// <param name="addr">Address of a .NET file in memory</param>
		/// <returns>A new <see cref="MetaData"/> instance</returns>
		internal static MetaData Load(IntPtr addr) {
			IPEImage peImage = null;

			// We don't know what layout it is. Memory is more common so try that first.
			try {
				return Load(peImage = new PEImage(addr, ImageLayout.Memory, true));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				peImage = null;
			}

			try {
				return Load(peImage = new PEImage(addr, ImageLayout.File, true));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
Beispiel #10
0
        static uint GetEntryPointToken(string filename, out string otherModuleName)
        {
            otherModuleName = null;
            IImageStream cor20HeaderStream = null;
            try {
                using (var peImage = new PEImage(filename)) {
                    var dotNetDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];
                    if (dotNetDir.VirtualAddress == 0)
                        return 0;
                    if (dotNetDir.Size < 0x48)
                        return 0;
                    var cor20Header = new ImageCor20Header(cor20HeaderStream = peImage.CreateStream(dotNetDir.VirtualAddress, 0x48), true);
                    if ((cor20Header.Flags & ComImageFlags.NativeEntryPoint) != 0)
                        return 0;
                    uint token = cor20Header.EntryPointToken_or_RVA;
                    if ((Table)(token >> 24) != Table.File)
                        return token;

                    using (var mod = ModuleDefMD.Load(peImage)) {
                        var file = mod.ResolveFile(token & 0x00FFFFFF);
                        if (file == null || !file.ContainsMetaData)
                            return 0;

                        otherModuleName = file.Name;
                        return token;
                    }
                }
            }
            catch {
            }
            finally {
                if (cor20HeaderStream != null)
                    cor20HeaderStream.Dispose();
            }
            return 0;
        }
			uint GetRuntimeTimeStamp() {
				string path = module.Location;
				if (string.IsNullOrEmpty(path))
					return 0;

				try {
					var rtNames = new List<string>();
					foreach (var rtModRef in mainType.RuntimeModuleRefs) {
						string dllName = rtModRef.Name;
						if (!dllName.ToUpperInvariant().EndsWith(".DLL"))
							dllName += ".dll";
						rtNames.Add(dllName);
					}
					if (rtNames.Count == 0)
						return 0;

					for (var di = new DirectoryInfo(Path.GetDirectoryName(path)); di != null; di = di.Parent) {
						foreach (var dllName in rtNames) {
							try {
								using (var peImage = new PEImage(Path.Combine(di.FullName, dllName))) {
									if (peImage.ImageNTHeaders.FileHeader.Machine == Machine.I386)
										return peImage.ImageNTHeaders.FileHeader.TimeDateStamp;
								}
							}
							catch {
							}
						}
					}
				}
				catch {
				}

				return 0;
			}
		/// <summary>
		/// Create a <see cref="DotNetFile"/> instance
		/// </summary>
		/// <param name="addr">Address of a .NET file in memory</param>
		/// <param name="imageLayout">Image layout of the file in memory</param>
		/// <returns>A new <see cref="DotNetFile"/> instance</returns>
		public static DotNetFile Load(IntPtr addr, ImageLayout imageLayout) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(addr, imageLayout, true));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
Beispiel #13
0
		/// <summary>
		/// Create a <see cref="MetaData"/> instance
		/// </summary>
		/// <param name="addr">Address of a .NET file in memory</param>
		/// <param name="imageLayout">Image layout of the file in memory</param>
		/// <returns>A new <see cref="MetaData"/> instance</returns>
		internal static MetaData Load(IntPtr addr, ImageLayout imageLayout) {
			IPEImage peImage = null;
			try {
				return Load(peImage = new PEImage(addr, imageLayout, true));
			}
			catch {
				if (peImage != null)
					peImage.Dispose();
				throw;
			}
		}
Beispiel #14
0
		bool UnpackNativeImage(IEnumerable<IDeobfuscator> deobfuscators) {
			using (var peImage = new PEImage(Filename)) {
				foreach (var deob in deobfuscators) {
					byte[] unpackedData = null;
					try {
						unpackedData = deob.UnpackNativeFile(peImage);
					}
					catch {
					}
					if (unpackedData == null)
						continue;

					var oldModule = module;
					try {
						module = assemblyModule.Load(unpackedData);
					}
					catch {
						Logger.w("Could not load unpacked data. File: {0}, deobfuscator: {0}", peImage.FileName ?? "(unknown filename)", deob.TypeLong);
						continue;
					}
					finally {
						if (oldModule != null)
							oldModule.Dispose();
					}
					this.deob = deob;
					return true;
				}
			}

			return false;
		}
Beispiel #15
0
		// Very simple, will probably fail if various fields have been overwritten with invalid values
		void WritePEFile(byte[] raw, byte[] dst, int rawSize, out int finalSize) {
			progress.ThrowIfCancellationRequested();
			for (int i = 0; i < rawSize; i++)
				dst[i] = 0;
			try {
				var peImage = new PEImage(raw, ImageLayout.Memory, true);
				int offset = 0;
				Array.Copy(raw, 0, dst, 0, (int)peImage.ImageNTHeaders.OptionalHeader.SizeOfHeaders);
				offset += (int)peImage.ImageNTHeaders.OptionalHeader.SizeOfHeaders;

				foreach (var sect in peImage.ImageSectionHeaders)
					Array.Copy(raw, (int)sect.VirtualAddress, dst, (int)sect.PointerToRawData, (int)sect.SizeOfRawData);

				var lastSect = peImage.ImageSectionHeaders[peImage.ImageSectionHeaders.Count - 1];
				var fa = peImage.ImageNTHeaders.OptionalHeader.FileAlignment;
				finalSize = (int)((lastSect.PointerToRawData + lastSect.SizeOfRawData + fa - 1) & ~(fa - 1));
			}
			catch {
				finalSize = rawSize;
				Array.Copy(raw, dst, rawSize);
			}
		}
Beispiel #16
0
        ImageSectionHeader[] GetOrCreateSectionHeaders()
        {
            var h = sectionHeaders;
            if (h != null)
                return h;

            try {
                ulong addr = module.Address;
                if (addr == 0)
                    return sectionHeaders = new ImageSectionHeader[0];
                var data = new byte[0x1000];
                int sizeRead;
                this.module.Process.CorProcess.ReadMemory(this.module.Address, data, 0, data.Length, out sizeRead);
                using (var peImage = new PEImage(data, !module.IsDynamic && module.IsInMemory ? ImageLayout.File : ImageLayout.Memory, true))
                    return sectionHeaders = peImage.ImageSectionHeaders.ToArray();
            }
            catch {
                Debug.Fail("Couldn't read section headers");
            }
            return sectionHeaders = new ImageSectionHeader[0];
        }
Beispiel #17
0
		public static MemoryModuleDefFile Create(DnModule dnModule, bool loadSyms) {
			Debug.Assert(!dnModule.IsDynamic);
			Debug.Assert(dnModule.Address != 0);
			ulong address = dnModule.Address;
			var process = dnModule.Process;
			var data = new byte[dnModule.Size];
			string location = dnModule.IsInMemory ? string.Empty : dnModule.Name;

			ProcessMemoryUtils.ReadMemory(process, address, data, 0, data.Length);

			var peImage = new PEImage(data, GetImageLayout(dnModule), true);
			var module = ModuleDefMD.Load(peImage);
			module.Location = location;
			bool autoUpdateMemory = false;//TODO: Init to default value
			if (GacInfo.IsGacPath(dnModule.Name))
				autoUpdateMemory = false;	// GAC files are not likely to decrypt methods in memory
			return new MemoryModuleDefFile(process, address, data, dnModule.IsInMemory, module, loadSyms, autoUpdateMemory);
		}
Beispiel #18
0
		void InitializeExeFields() {
			if (exeFieldsInitialized)
				return;
			exeFieldsInitialized = true;

			isExe = false;
			timestamp = null;
			version = null;

			if (!module.IsDynamic && module.IsInMemory) {
				var bytes = module.Process.CorProcess.ReadMemory(module.Address, (int)module.Size);
				if (bytes != null) {
					try {
						using (var peImage = new PEImage(bytes))
							InitializeExeFieldsFrom(peImage);
					}
					catch {
					}
				}
			}
			else if (module.IsDynamic || module.IsInMemory) {
				if (module.CorModule.IsManifestModule)
					version = new AssemblyNameInfo(module.Assembly.FullName).Version;
			}
			else {
				try {
					using (var peImage = new PEImage(module.Name))
						InitializeExeFieldsFrom(peImage);
				}
				catch {
				}
			}
		}
Beispiel #19
0
        void InitializeExeFields()
        {
            if (exeFieldsInitialized)
                return;
            exeFieldsInitialized = true;

            isExe = false;
            timestamp = null;
            version = null;

            if (!module.IsDynamic && module.IsInMemory) {
                var bytes = module.Process.CorProcess.ReadMemory(module.Address, (int)module.Size);
                if (bytes != null) {
                    try {
                        using (var peImage = new PEImage(bytes))
                            InitializeExeFieldsFrom(peImage);
                    }
                    catch {
                    }
                }
            }
            else if (module.IsDynamic || module.IsInMemory) {
                //TODO: Support dynamic modules
            }
            else {
                try {
                    using (var peImage = new PEImage(module.Name))
                        InitializeExeFieldsFrom(peImage);
                }
                catch {
                }
            }
        }
Beispiel #20
0
		PEState CreatePEState() {
			try {
				ulong addr = Address;
				if (addr == 0)
					return PEState.Null;
				var data = new byte[0x1000];
				debugger.Read(Address, data, 0, data.Length);
				using (var peImage = new PEImage(data, IsFileLayout ? ImageLayout.File : ImageLayout.Memory, true))
					return new PEState(peImage.ImageSectionHeaders.ToArray());
			}
			catch {
				Debug.Fail("Couldn't read section headers");
				return PEState.Null;
			}
		}
Beispiel #21
0
        LoadedFile LoadAssembly(object state)
        {
            IPEImage peImage;

            if (OtherSettings.Instance.UseMemoryMappedIO)
                peImage = new PEImage(fileName);
            else
                peImage = new PEImage(File.ReadAllBytes(fileName));

            var dotNetDir = peImage.ImageNTHeaders.OptionalHeader.DataDirectories[14];
            bool isDotNet = dotNetDir.VirtualAddress != 0 && dotNetDir.Size >= 0x48;

            if (isDotNet) {
                try {
                    ModuleDef module;
                    var opts = new ModuleCreationOptions(CreateModuleContext());
                    if (OtherSettings.Instance.UseMemoryMappedIO)
                        module = ModuleDefMD.Load(peImage, opts);
                    else
                        module = ModuleDefMD.Load(peImage, opts);
                    return InitializeModule(module);
                }
                catch {
                }
            }

            return new LoadedFile(peImage, null);
        }