Exemple #1
0
        public bool DumpModule(IntPtr moduleHandle, string filePath)
        {
            return(false);

            Injection.Options options;
            MetadataService   metadataService;
            MetadataInfo      metadataInfo;

            byte[] peImage;

            options = new Injection.Options {
                PortName   = Guid.NewGuid().ToString(),
                ObjectName = Guid.NewGuid().ToString()
            };
            using (NativeProcess process = NativeProcess.Open(_processId))
                if (!process.InjectManaged(typeof(MetadataService).Assembly.Location, typeof(Injection).FullName, "Main", options.Serialize(), out int result) || result != 0)
                {
                    return(false);
                }
            metadataService = (MetadataService)Activator.GetObject(typeof(MetadataService), $"Ipc://{options.PortName}/{options.ObjectName}");
            metadataInfo    = metadataService.GetMetadataInfo(moduleHandle);
            PrintStreamInfo("#~ or #-", metadataInfo.TableStream);
            PrintStreamInfo("#Strings", metadataInfo.StringHeap);
            PrintStreamInfo("#US", metadataInfo.UserStringHeap);
            PrintStreamInfo("#GUID", metadataInfo.GuidHeap);
            PrintStreamInfo("#Blob", metadataInfo.BlobHeap);
            peImage = DumpMemoryModule(moduleHandle);
            return(true);
        }
Exemple #2
0
        public void TestOpenProcess()
        {
            var explorer = NativeProcess.EnumProcesses().First(pi => pi.Name.ToLower() == "explorer.exe");
            var process  = NativeProcess.Open(ProcessAccessMask.QueryInformation, explorer.Id);

            Console.WriteLine(process.StartTime);
        }
Exemple #3
0
    public IEnumerable <ModuleInfo> EnumerateModules()
    {
        using var process = NativeProcess.Open(processId);
        if (process.IsInvalid)
        {
            throw new InvalidOperationException();
        }
        using var dataTarget     = DataTarget.AttachToProcess((int)processId, 1000, AttachFlag.Passive);
        dataTarget.SymbolLocator = DummySymbolLocator.Instance;
        foreach (var runtime in dataTarget.ClrVersions.Select(t => t.CreateRuntime()))
        {
            var clrVersion = runtime.ClrInfo.Version.ToString();
            foreach (var domain in runtime.AppDomains)
            {
                var domainName = domain.Name;
                foreach (var module in domain.Modules)
                {
                    if (module.ImageBase == 0)
                    {
                        continue;
                    }
                    if (!IsValidPEMagic(module, process))
                    {
                        continue;
                    }
                    // .NET 3.5有nlp文件,但是被认为是.NET模块

                    GetModuleFileInfo(module, out var name, out var path);
                    uint size = GetModuleSize(module, process);
                    yield return(new DotNetModuleInfo(name, (nuint)module.ImageBase, size, path, domainName, clrVersion));
                }
            }
        }
    }
 public ModulesForm(uint processId, string processName, bool isDotNetProcess, DumperCoreWrapper dumperCore)
 {
     InitializeComponent();
     _process = NativeProcess.Open(processId);
     if (_process == NativeProcess.InvalidProcess)
     {
         throw new InvalidOperationException();
     }
     _isDotNetProcess = isDotNetProcess;
     _dumperCore      = dumperCore;
     Text             = $"{_resources.GetString("StrModules")} {processName}(ID={processId.ToString()})";
     typeof(ListView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, lvwModules, new object[] { true });
     lvwModules.ListViewItemSorter = new ListViewItemSorter(lvwModules, new List <TypeCode> {
         TypeCode.String,
         TypeCode.String,
         TypeCode.String,
         TypeCode.UInt64,
         TypeCode.Int32,
         TypeCode.String
     })
     {
         AllowHexLeading = true
     };
     RefreshModuleList();
 }
Exemple #5
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                // all handles in the system
                var handles = SystemInformation.EnumHandles();
                Console.WriteLine($"Total handles: {handles.Length}");
                foreach (var handle in handles)
                {
                    Console.WriteLine($"H: 0x{handle.Handle:X4}\tPID: {handle.ProcessId}\tObject: 0x{handle.Object.ToUInt64():X}\tType: {handle.ObjectTypeIndex,2} Access: 0x{handle.AccessMask:X8}");
                }
            }
            else
            {
                int pid = int.Parse(args[0]);

                using (var process = NativeProcess.Open(ProcessAccessMask.QueryInformation, pid)) {
                    var handles = process.EnumHandles();
                    Console.WriteLine($"Total handles: {handles.Length}");
                    foreach (var handle in handles)
                    {
                        Console.WriteLine($"H: 0x{handle.Handle:X4}\t Count: {handle.HandleCount}\tType: {handle.ObjectTypeIndex,2}\tPointer Count: 0x{handle.PointerCount:X}");
                    }
                }
            }
        }
Exemple #6
0
        static void Main(string[] args)
        {
            var proc     = NativeProcess.Open(uint.Parse(args[0]));
            var procMem  = new LiveProcessMemoryAccessor(proc);
            var unloaded = new UnloadedModulesAccessor(procMem);

            var modules = unloaded.ReadUnloadedModules();
        }
Exemple #7
0
        public bool DumpModule(IntPtr moduleHandle, ImageLayout imageLayout, string filePath)
        {
            ClrModule           dacModule;
            InjectionClrVersion clrVersion;
            InjectionOptions    injectionOptions;
            MetadataInfoService metadataInfoService;
            MetadataInfo        metadataInfo;

            byte[] peImageData;

            dacModule = TryGetDacModule(moduleHandle);
            if (dacModule is null)
            {
                return(false);
            }
            switch (dacModule.Runtime.ClrInfo.Version.Major)
            {
            case 2:
                clrVersion = InjectionClrVersion.V2;
                break;

            case 4:
                clrVersion = InjectionClrVersion.V4;
                break;

            default:
                return(false);
            }
            // 判断要dump的模块的CLR版本
            injectionOptions = new InjectionOptions {
                PortName   = Guid.NewGuid().ToString(),
                ObjectName = Guid.NewGuid().ToString()
            };
            using (NativeProcess process = NativeProcess.Open(_processId))
                if (!process.InjectManaged(typeof(MetadataInfoService).Assembly.Location, typeof(Injection).FullName, "Main", XmlSerializer.Serialize(injectionOptions), clrVersion, out int result) || result != 0)
                {
                    return(false);
                }
            metadataInfoService = (MetadataInfoService)Activator.GetObject(typeof(MetadataInfoService), $"Ipc://{injectionOptions.PortName}/{injectionOptions.ObjectName}");
            // 注入DLL,通过.NET Remoting获取MetadataInfoService实例
            metadataInfo = XmlSerializer.Deserialize <MetadataInfo>(metadataInfoService.GetMetadataInfo(moduleHandle));
            if (!metadataInfo.PEInfo.IsValid)
            {
                return(false);
            }
            imageLayout = (ImageLayout)metadataInfo.PEInfo.ImageLayout;
            try {
                peImageData = DumpModule(moduleHandle, imageLayout, metadataInfo, null);
                // 尝试不使用文件中的节头
            }
            catch {
                peImageData = DumpModule(moduleHandle, imageLayout, metadataInfo, dacModule.FileName);
                // 如果出错,使用文件中的节头
            }
            File.WriteAllBytes(filePath, peImageData);
            return(true);
        }
Exemple #8
0
 public InjectingForm(uint processId)
 {
     InitializeComponent();
     _process = NativeProcess.Open(processId);
     if (_process == null)
     {
         throw new InvalidOperationException();
     }
     Text = $"Injector - {_process.Name}(ID={_process.Id.ToString()})";
 }
        /// <summary>
        /// 直接从内存中复制模块,不执行格式转换操作
        /// </summary>
        /// <param name="processId"></param>
        /// <param name="address"></param>
        /// <param name="imageLayout"></param>
        /// <returns></returns>
        public static byte[] Dump(uint processId, void *address, ref ImageLayout imageLayout)
        {
            if (processId == 0)
            {
                throw new ArgumentNullException(nameof(processId));
            }
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            using (var process = NativeProcess.Open(processId))
                return(Dump(process, address, ref imageLayout));
        }
 private Dictionary <int, ProcessViewModel> GetCurrentCpuTimes()
 {
     return((from p in SystemInformation.EnumProcesses()
             let id = p.Id
                      where id != 0
                      let process = NativeProcess.Open(ProcessAccessMask.QueryLimitedInformation, p.Id)
                                    select new {
         id,
         process.TotalTime,
         p.Name
     }).
            ToDictionary(pr => pr.id, pr => new ProcessViewModel {
         Name = pr.Name,
         TotalTime = pr.TotalTime,
         Id = pr.id
     }));
 }
Exemple #11
0
 public ModulesForm(uint processId, string processName, bool isDotNetProcess, DumperCoreWrapper dumperCore)
 {
     InitializeComponent();
     _process                    = NativeProcess.Open(processId);
     _isDotNetProcess            = isDotNetProcess;
     _dumperCore                 = dumperCore;
     Text                        = $"{_resources.GetString("StrModules")} {processName}(ID={processId.ToString()})";
     mnuOnlyDotNetModule.Checked = isDotNetProcess;
     typeof(ListView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, lvwModules, new object[] { true });
     lvwModules.ListViewItemSorter = new ListViewItemSorter(lvwModules, new Dictionary <int, TypeCode> {
         { 0, TypeCode.String }, { 1, Cache.Is64BitProcess ? TypeCode.UInt64 : TypeCode.UInt32 }, { 2, TypeCode.Int32 }, { 3, TypeCode.String }
     })
     {
         AllowHexLeading = true
     };
     RefreshModuleList();
 }
        private void mnuDumpProcess_Click(object sender, EventArgs e)
        {
            if (lvwProcesses.SelectedIndices.Count == 0)
            {
                return;
            }

            uint processId = uint.Parse(lvwProcesses.GetFirstSelectedSubItem(chProcessId.Index).Text);

            using (var process = NativeProcess.Open(processId))
                fbdlgDumped.SelectedPath = Path.GetDirectoryName(process.ImagePath);
            if (fbdlgDumped.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            DumpProcess(processId, Path.Combine(fbdlgDumped.SelectedPath, "Dumps"));
        }
Exemple #13
0
 public FunctionsForm(uint processId, nuint moduleHandle)
 {
     InitializeComponent();
     Utils.ScaleByDpi(this);
     process = NativeProcess.Open(processId);
     if (process.IsInvalid)
     {
         throw new InvalidOperationException();
     }
     module = process.UnsafeGetModule((void *)moduleHandle);
     Text   = TitleComposer.Compose(true, "Export Functions", module.Name, null);
     Utils.EnableDoubleBuffer(lvwFunctions);
     lvwFunctions.ListViewItemSorter = new ListViewItemSorter(lvwFunctions, new[] { TypeCode.String, TypeCode.UInt64, TypeCode.Int16 })
     {
         AllowHexLeading = true
     };
     RefreshFunctionList();
 }
Exemple #14
0
            public static byte[] Copy(uint processId, IntPtr processHandle, IntPtr moduleHandle, bool is64)
            {
                ulong imageSize;

                byte[] buffer;

                imageSize = GetImageSize(processHandle, moduleHandle, is64);
                buffer    = new byte[imageSize];
                using (NativeProcess process = NativeProcess.Open(processId))
                    foreach (PageInfo pageInfo in process.EnumeratePageInfos(moduleHandle, (IntPtr)((ulong)moduleHandle + imageSize)))
                    {
                        int startOffset;
                        int endOffset;

                        startOffset = (int)((long)pageInfo.Address - (long)moduleHandle);
                        //以p为起点,远程进程中页面起点映射到buffer中的偏移
                        endOffset = startOffset + (int)pageInfo.Size;
                        //以p为起点,远程进程中页面终点映射到buffer中的偏移
                        fixed(byte *p = buffer)
                        {
                            if (startOffset < 0)
                            {
                                //页面前半部分超出buffer
                                ReadProcessMemory(processHandle, moduleHandle, p, (IntPtr)((ulong)pageInfo.Size - ((ulong)moduleHandle - (ulong)pageInfo.Address)), null);
                            }
                            else
                            {
                                if (endOffset <= buffer.Length)
                                {
                                    //整个页面都可以存入buffer
                                    ReadProcessMemory(processHandle, pageInfo.Address, p + startOffset, pageInfo.Size, null);
                                }
                                else
                                {
                                    //页面后半部分/全部超出buffer
                                    ReadProcessMemory(processHandle, pageInfo.Address, p + startOffset, pageInfo.Size - (endOffset - buffer.Length), null);
                                    break;
                                }
                            }
                        }
                    }
                return(buffer);
            }
Exemple #15
0
        static void Main(string[] args)
        {
            var processes = SystemInformation.EnumProcesses();

            foreach (var pi in processes)
            {
                Console.Write($"{pi.Name} ({pi.Id}) Threads: {pi.Threads} Parent: {pi.ParentId}");
                if (pi.Id > 0)
                {
                    try {
                        using (var process = NativeProcess.Open(ProcessAccessMask.QueryLimitedInformation, pi.Id)) {
                            Console.Write($" Start: {process.CreateTime}");
                        }
                    }
                    catch { }
                }
                Console.WriteLine();
            }
        }
Exemple #16
0
 public ModulesForm(uint processId, string processName, bool isDotNetProcess, StrongBox <DumperType> dumperType)
 {
     InitializeComponent();
     _process = NativeProcess.Open(processId);
     if (_process == NativeProcess.InvalidProcess)
     {
         throw new InvalidOperationException();
     }
     _isDotNetProcess = isDotNetProcess;
     _dumperType      = dumperType;
     Text             = $"Modules {processName}(ID={processId})";
     Utils.EnableDoubleBuffer(lvwModules);
     lvwModules.ListViewItemSorter = new ListViewItemSorter(lvwModules, new List <TypeCode> {
         TypeCode.String, TypeCode.String, TypeCode.String, TypeCode.UInt64, TypeCode.Int32, TypeCode.String
     })
     {
         AllowHexLeading = true
     };
     RefreshModuleList();
 }
Exemple #17
0
        private byte[] DumpMemoryModule(IntPtr moduleHandle)
        {
            using (NativeProcess process = NativeProcess.Open(_processId)) {
                PageInfo firstPageInfo;
                byte[]   buffer;
                uint     imageSize;

                firstPageInfo = process.EnumeratePageInfos(moduleHandle, moduleHandle).First();
                buffer        = new byte[(uint)firstPageInfo.Size];
                process.ReadBytes(moduleHandle, buffer);
                imageSize = GetImageSize(buffer);
                buffer    = new byte[imageSize];
                foreach (PageInfo pageInfo in process.EnumeratePageInfos(moduleHandle, (IntPtr)((ulong)moduleHandle + imageSize)))
                {
                    uint offset;

                    offset = (uint)((ulong)pageInfo.Address - (ulong)moduleHandle);
                    process.TryReadBytes(pageInfo.Address, buffer, offset, (uint)pageInfo.Size);
                }
                return(buffer);
            }
        }
        public static byte[] DirectCopy(uint processId, void *moduleHandle, ImageLayout imageLayout)
        {
            using (NativeProcess process = NativeProcess.Open(processId)) {
                PageInfo firstPageInfo;
                byte[]   peImageData;
                uint     imageSize;

                firstPageInfo = process.EnumeratePageInfos(moduleHandle, moduleHandle).First();
                peImageData   = new byte[(uint)firstPageInfo.Size];
                process.ReadBytes(moduleHandle, peImageData);
                imageSize   = GetImageSize(peImageData, imageLayout);
                peImageData = new byte[imageSize];
                switch (imageLayout)
                {
                case ImageLayout.File:
                    if (!process.TryReadBytes(firstPageInfo.Address, peImageData, 0, imageSize))
                    {
                        throw new InvalidOperationException();
                    }
                    break;

                case ImageLayout.Memory:
                    foreach (PageInfo pageInfo in process.EnumeratePageInfos(moduleHandle, (byte *)moduleHandle + imageSize))
                    {
                        uint offset;

                        offset = (uint)((ulong)pageInfo.Address - (ulong)moduleHandle);
                        process.TryReadBytes(pageInfo.Address, peImageData, offset, (uint)pageInfo.Size);
                    }
                    break;

                default:
                    throw new NotSupportedException();
                }
                return(peImageData);
            }
        }
 public InjectingForm(uint processId)
 {
     InitializeComponent();
     _process = NativeProcess.Open(processId);
     Text     = $"Injector - {_process.Name}(ID={_process.Id.ToString()})";
 }
        public bool DumpModule(IntPtr moduleHandle, ImageLayout imageLayout, string filePath)
        {
            ClrModule           dacModule;
            InjectionClrVersion clrVersion;

            Injection.Options   options;
            AntiAntiDumpService antiAntiDumpService;
            AntiAntiDumpInfo    antiAntiDumpInfo;
            MetadataInfo        metadataInfo;

            byte[] peImageData;

            dacModule = TryGetDacModule(moduleHandle);
            if (dacModule == null)
            {
                return(false);
            }
            switch (dacModule.Runtime.ClrInfo.Version.Major)
            {
            case 2:
                clrVersion = InjectionClrVersion.V2;
                break;

            case 4:
                clrVersion = InjectionClrVersion.V4;
                break;

            default:
                return(false);
            }
            // 判断要dump的模块的CLR版本
            options = new Injection.Options {
                PortName   = Guid.NewGuid().ToString(),
                ObjectName = Guid.NewGuid().ToString()
            };
            using (NativeProcess process = NativeProcess.Open(_processId))
                if (!process.InjectManaged(typeof(AntiAntiDumpService).Assembly.Location, typeof(Injection).FullName, "Main", options.Serialize(), clrVersion, out int result) || result != 0)
                {
                    return(false);
                }
            antiAntiDumpService = (AntiAntiDumpService)Activator.GetObject(typeof(AntiAntiDumpService), $"Ipc://{options.PortName}/{options.ObjectName}");
            // 注入DLL,通过.NET Remoting获取AntiAntiDumpService实例
            antiAntiDumpInfo = antiAntiDumpService.GetAntiAntiDumpInfo(moduleHandle);
            if (!antiAntiDumpInfo.CanAntiAntiDump)
            {
                return(false);
            }
            imageLayout = (ImageLayout)antiAntiDumpInfo.ImageLayout;
            // 覆盖通过DAC获取的,不确定DAC获取的是否准确,毕竟DAC的bug还不少
            metadataInfo = antiAntiDumpInfo.MetadataInfo;
            PrintStreamInfo("#~ or #-", metadataInfo.TableStream);
            PrintStreamInfo("#Strings", metadataInfo.StringHeap);
            PrintStreamInfo("#US", metadataInfo.UserStringHeap);
            PrintStreamInfo("#GUID", metadataInfo.GuidHeap);
            PrintStreamInfo("#Blob", metadataInfo.BlobHeap);
            peImageData = PEImageHelper.DirectCopy(_processId, (void *)moduleHandle, imageLayout);
            FixHeader(peImageData, antiAntiDumpInfo);
            peImageData = PEImageHelper.ConvertImageLayout(peImageData, imageLayout, ImageLayout.File);
            File.WriteAllBytes(filePath, peImageData);
            return(true);
        }
Exemple #21
0
 public NativeProcess OpenProcess(AccessRights.ProcessAccessRights accessRights = AccessRights.ProcessAccessRights.All, bool inhertiable = false)
 {
     return(NativeProcess.Open(Process.ProcessId, accessRights, inhertiable));
 }
 private NormalDumper(uint processId)
 {
     _process = NativeProcess.Open(processId, ProcessAccess.MemoryRead | ProcessAccess.QueryInformation);
 }
Exemple #23
0
 private AntiAntiDumper(uint processId)
 {
     _process = NativeProcess.Open(processId);
 }
Exemple #24
0
 public NativeProcess Open(ProcessAccessRights rights = ProcessAccessRights.All, bool inheritable = false)
 {
     return(NativeProcess.Open(ProcessId, rights, false));
 }
Exemple #25
0
 protected DumperBase(uint processId)
 {
     process = NativeProcess.Open(processId, ProcessAccess.MemoryRead | ProcessAccess.QueryInformation);
 }
Exemple #26
0
        /// <summary>
        /// 直接从内存中复制模块,不执行格式转换操作
        /// </summary>
        /// <param name="processId">进程ID</param>
        /// <param name="moduleHandle">模块句柄</param>
        /// <param name="imageLayout">模块在内存中的格式</param>
        /// <param name="useSectionHeadersInFile">是否使用文件中的节头</param>
        /// <param name="alternativeToImagePath">如果无法正常获取模块路径,可提供备选模块路径</param>
        /// <returns></returns>
        public static byte[] DirectCopy(uint processId, void *moduleHandle, ImageLayout imageLayout, bool useSectionHeadersInFile, string alternativeToImagePath)
        {
            if (processId == 0)
            {
                throw new ArgumentNullException(nameof(processId));
            }
            if (moduleHandle is null)
            {
                throw new ArgumentNullException(nameof(moduleHandle));
            }
            if (useSectionHeadersInFile)
            {
                if (string.IsNullOrEmpty(alternativeToImagePath))
                {
                    alternativeToImagePath = null;
                }
                else
                {
                    if (!File.Exists(alternativeToImagePath))
                    {
                        throw new FileNotFoundException(nameof(alternativeToImagePath));
                    }
                }
            }

            using (NativeProcess process = NativeProcess.Open(processId)) {
                PageInfo firstPageInfo;
                string   imagePath;
                byte[]   peImageData;
                uint     imageSize;

                firstPageInfo = process.EnumeratePageInfos(moduleHandle, moduleHandle).First();
                if (useSectionHeadersInFile)
                {
                    imagePath = process.UnsafeGetModule(moduleHandle).ImagePath;
                    if (string.IsNullOrEmpty(imagePath) || !File.Exists(imagePath))
                    {
                        imagePath = alternativeToImagePath;
                    }
                }
                else
                {
                    imagePath = default;
                }
                // 获取模块路径(如果需要使用文件中的节头)
                if (useSectionHeadersInFile)
                {
                    imageSize = GetImageSize(File.ReadAllBytes(imagePath), imageLayout);
                }
                else
                {
                    byte[] peHeaderData;

                    peHeaderData = new byte[(uint)firstPageInfo.Size];
                    process.ReadBytes(moduleHandle, peHeaderData);
                    imageSize = GetImageSize(peHeaderData, imageLayout);
                }
                // 获取模块在内存中的大小
                peImageData = new byte[imageSize];
                switch (imageLayout)
                {
                case ImageLayout.File:
                    if (!process.TryReadBytes(firstPageInfo.Address, peImageData, 0, imageSize))
                    {
                        throw new InvalidOperationException();
                    }
                    break;

                case ImageLayout.Memory:
                    foreach (PageInfo pageInfo in process.EnumeratePageInfos(moduleHandle, (byte *)moduleHandle + imageSize))
                    {
                        uint offset;

                        offset = (uint)((ulong)pageInfo.Address - (ulong)moduleHandle);
                        process.TryReadBytes(pageInfo.Address, peImageData, offset, (uint)pageInfo.Size);
                    }
                    break;

                default:
                    throw new NotSupportedException();
                }
                // 转储
                if (useSectionHeadersInFile)
                {
                    using (PEImage peHeader = new PEImage(imagePath, false)) {
                        int    startOffset;
                        int    endOffset;
                        byte[] sectionHeadersData;

                        startOffset        = (int)peHeader.ImageSectionHeaders.First().StartOffset;
                        endOffset          = (int)peHeader.ImageSectionHeaders.Last().EndOffset;
                        sectionHeadersData = peHeader.CreateReader((FileOffset)startOffset).ReadBytes(endOffset - startOffset);
                        Buffer.BlockCopy(sectionHeadersData, 0, peImageData, startOffset, endOffset - startOffset);
                    }
                }
                // 替换节头(如果需要使用文件中的节头)
                return(peImageData);
            }
        }