Пример #1
0
        public static IntPtr GetPEBAddress(uint ProcessId)
        {
            //Get a handle to our own process
            IntPtr hProc = Kernel32.OpenProcess(ProcessAccess.All, false, ProcessId);

            //Allocate memory for a new PROCESS_BASIC_INFORMATION structure
            IntPtr pbi = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PROCESS_BASIC_INFORMATION)));

            //Allocate memory for a long
            IntPtr outLong = Marshal.AllocHGlobal(sizeof(long));
            IntPtr outPtr  = IntPtr.Zero;

            NtStatus queryStatus = 0;

            //Store API call success in a boolean
            queryStatus = NtDll.NtQueryInformationProcess(hProc, ProcessInfo.ProcessBasicInformation, pbi, (uint)Marshal.SizeOf(typeof(PROCESS_BASIC_INFORMATION)), outLong);

            //Close handle and free allocated memory
            Kernel32.CloseHandle(hProc);
            Marshal.FreeHGlobal(outLong);

            //STATUS_SUCCESS = 0, so if API call was successful querySuccess should contain 0 ergo we reverse the check.
            outPtr = ((PROCESS_BASIC_INFORMATION)Marshal.PtrToStructure(pbi, typeof(PROCESS_BASIC_INFORMATION))).PebBaseAddress;

            //Free allocated space
            Marshal.FreeHGlobal(pbi);

            //Return pointer to PEB base address
            return(outPtr);
        }
Пример #2
0
        public static unsafe void VisitProcesses(ResizeableBuffer resizeableBuffer, SystemProcInfoVisitor visit)
        {
            var size = 100 * 1024;

            while (true)
            {
                var buffer = resizeableBuffer.Get(ref size, false);
                fixed(byte *ptr = buffer)
                {
                    var status = NtDll.NtQuerySystemInformation(
                        SYSTEM_INFORMATION_CLASS.SystemProcessInformation,
                        (IntPtr)ptr,
                        buffer.Length,
                        out size);

                    if (status == NtStatus.STATUS_INFO_LENGTH_MISMATCH)
                    {
                        continue;
                    }

                    if (!status.IsSuccessful())
                    {
                        throw new InvalidOperationException($"Can't query SystemProcessInformation. NtStatus: 0x{status:X}");
                    }

                    VisitProcesses(ptr, buffer, visit);
                    return;
                }
            }
        }
Пример #3
0
        public static IEnumerable <ProcessInfo> GetLockingProcessInfos(string[] paths, LockManagerFeatures features = default)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if ((features & LockManagerFeatures.UseLowLevelApi) != 0)
                {
                    return(NtDll.GetLockingProcessInfos(paths));
                }

                return(RestartManager.GetLockingProcessInfos(paths));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                return(ProcFileSystem.GetLockingProcessInfos(paths));
            }
            else
            {
                if ((features & LockManagerFeatures.ThrowIfNotSupported) != 0)
                {
                    throw new NotSupportedException("Current OS platform is not supported");
                }

                return(Enumerable.Empty <ProcessInfo>());
            }
        }
Пример #4
0
        public NhaamaHandle(IntPtr handle, NhaamaProcess process)
        {
            _handle  = handle;
            _process = process;

            IntPtr dupHandle = IntPtr.Zero;

            var status = NtDll.NtDuplicateObject(process.BaseProcess.Handle, handle, Process.GetCurrentProcess().Handle, out dupHandle, 0, false, DuplicateOptions.DUPLICATE_SAME_ACCESS);

            if (status != NtStatus.Success)
            {
                throw new Exception($"Could not duplicate handle. (NtStatus:{status.ToString()})");
            }

            var objectNameInformationPtr = NtDll.NtQueryObject(dupHandle, OBJECT_INFORMATION_CLASS.ObjectNameInformation);

            if (objectNameInformationPtr == IntPtr.Zero)
            {
                return;
            }

            var objInfo = Marshal.PtrToStructure <Native.Structs.OBJECT_NAME_INFORMATION>(objectNameInformationPtr);

            if (objInfo.Name.ToString() != null)
            {
                Name = objInfo.Name.ToString();
            }

            Marshal.FreeHGlobal(objectNameInformationPtr);
            NtDll.NtClose(dupHandle);
        }
Пример #5
0
        private static bool IsWindowsVersionOrGreater(uint majorVersion, uint minorVersion, ushort servicePackMajor)
        {
            var osvi = new NativeStructs.RTL_OSVERSIONINFOEXW(0);

            ulong conditionMask =
                Kernel32.VerSetConditionMask
                (
                    Kernel32.VerSetConditionMask
                    (
                        Kernel32.VerSetConditionMask
                        (
                            0,
                            NativeConstants.VER_MAJORVERSION,
                            NativeConstants.VER_GREATER_EQUAL
                        ),
                        NativeConstants.VER_MINORVERSION,
                        NativeConstants.VER_GREATER_EQUAL
                    ),
                    NativeConstants.VER_SERVICEPACKMAJOR,
                    NativeConstants.VER_GREATER_EQUAL
                );

            osvi.dwMajorVersion    = majorVersion;
            osvi.dwMinorVersion    = minorVersion;
            osvi.wServicePackMajor = servicePackMajor;

            return(NtDll.RtlVerifyVersionInfo(ref osvi, NativeConstants.VER_MAJORVERSION | NativeConstants.VER_MINORVERSION | NativeConstants.VER_SERVICEPACKMAJOR, conditionMask) == NativeConstants.STATUS_SUCCESS);
        }
Пример #6
0
        public override byte[] ReadMemory(long address, int size)
        {
            byte[]  buffer = new byte[size];
            UIntPtr numBytes;
            int     error = 0;

            if (IsWow64() && !IsWow64Process(processHandle))
            {
                int status = NtDll.NtWow64ReadVirtualMemory64(processHandle, (long)address, buffer, size, out numBytes);
                error = NtDll.RtlNtStatusToDosError(status);
            }
            else
            {
                bool success = Kernel32.ReadProcessMemory(processHandle, checked ((IntPtr)address), buffer, size, out numBytes);
                if (!success)
                {
                    error = Marshal.GetLastWin32Error();
                }
            }
            if (error != 0 && error != 299 || (error == 299 && size > 0 && numBytes == UIntPtr.Zero))
            {
                throw new Win32Exception(error);
            }
            if (numBytes != (UIntPtr)size)
            {
                Array.Resize(ref buffer, (int)numBytes);
            }
            return(buffer);
        }
Пример #7
0
 public unsafe int BufferCB(double sampleTime, IntPtr buffer, int bufferLen)
 {
     if (_parent.NewFrame != null)
     {
         if (_bitmap == null || _bitmap.Width != Width || _bitmap.Height != Height)
         {
             _bitmap?.Dispose();
             _bitmap = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
         }
         var bitmapData = _bitmap.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
         var stride1    = bitmapData.Stride;
         var stride2    = bitmapData.Stride;
         var dst        = (byte *)((IntPtr)bitmapData.Scan0.ToPointer() + stride2 * (Height - 1));
         var pointer    = (byte *)buffer.ToPointer();
         for (var index = 0; index < Height; ++index)
         {
             NtDll.memcpy(dst, pointer, stride1);
             dst     -= stride2;
             pointer += stride1;
         }
         _bitmap.UnlockBits(bitmapData);
         _parent.OnNewFrame(_bitmap);
     }
     return(0);
 }
Пример #8
0
        /// <summary>
        /// Returns a collection of handles that are currently active within the system
        /// </summary>
        /// <returns>A collection of active handles</returns>
        public static ICollection <HandleInfo> GetHandles()
        {
            byte[]   buffer;
            NtStatus status;
            int      size       = 1024;
            uint     actualSize = 0;

            do
            {
                buffer = new byte[size];
                status = NtDll.NtQuerySystemInformation(SystemInformationType.HandleInformation, buffer,
                                                        Convert.ToUInt32(size), ref actualSize);
                if (status != NtStatus.Success && status != NtStatus.BufferTooSmall &&
                    status != NtStatus.InfoLengthMismatch)
                {
                    throw new Win32Exception("Could not retrieve system handle information");
                }

                size = Convert.ToInt32(actualSize);
            } while (status != NtStatus.Success);

            int count = Seriz.Parse <int>(buffer);

            NtDll.SystemHandle[] systemHandles = Seriz.Parse <NtDll.SystemHandle>(buffer.Skip(4).ToArray(), count);
            List <HandleInfo>    results       = new List <HandleInfo>();

            foreach (var handle in systemHandles)
            {
                results.Add(new HandleInfo(Convert.ToInt32(handle.ProcessId), handle.Type,
                                           new IntPtr(handle.Handle), handle.AccessMask));
            }

            return(results);
        }
Пример #9
0
 /// <summary>Retrieves information about the specified process using either NtQueryInformationProcess or GetProcessInformation.</summary>
 /// <typeparam name="T">The type of information to retrieve.</typeparam>
 /// <param name="process">
 /// A handle to the process. This handle must have the <c>PROCESS_SET_INFORMATION</c> access right. For more information, see Process
 /// Security and Access Rights.
 /// </param>
 /// <returns>An object containing the requested type of information.</returns>
 /// <exception cref="ArgumentException">Type mismatch.</exception>
 public static T GetInformation <T>(this Process process) where T : struct
 {
     if (CorrespondingTypeAttribute.CanGet <T, NtDll.PROCESSINFOCLASS>(out var pic))
     {
         return(NtDll.NtQueryInformationProcess <T>(process, pic));
     }
     return(GetProcessInformation <T>(process));
 }
Пример #10
0
        /// <summary>
        /// Gets the friendly name, as shown in Windows' control panel.
        /// </summary>
        /// <returns>System.String.</returns>
        private string GetFriendlyName()
        {
            var lpVersionInformation = new NtDll.OSVERSIONINFOEX();

            lpVersionInformation.dwOSVersionInfoSize = (uint)Marshal.SizeOf(lpVersionInformation);
            NtDll.RtlGetVersion(ref lpVersionInformation);

            return(ConvertAdapterName(NameBytes, 0, lpVersionInformation.dwPlatformId, lpVersionInformation.dwMajorVersion));
        }
Пример #11
0
        /// <summary>
        /// Gets the version.
        /// </summary>
        /// <returns><see cref="NtDll.OSVERSIONINFOEX" />.</returns>
        private static NtDll.OSVERSIONINFOEX GetVersion()
        {
            var osversioninfoex = new NtDll.OSVERSIONINFOEX();

            osversioninfoex.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osversioninfoex);
            NtDll.RtlGetVersion(ref osversioninfoex);

            return(osversioninfoex);
        }
Пример #12
0
        public static bool IsWindowsServer()
        {
            var osvi = new NativeStructs.RTL_OSVERSIONINFOEXW(0);

            osvi.wProductType = NativeConstants.VER_NT_WORKSTATION;

            ulong conditionMask = Kernel32.VerSetConditionMask(0, NativeConstants.VER_PRODUCT_TYPE, NativeConstants.VER_EQUAL);

            var  result   = NtDll.RtlVerifyVersionInfo(ref osvi, NativeConstants.VER_PRODUCT_TYPE, conditionMask);
            bool clientOS = (result == NativeConstants.STATUS_SUCCESS);

            return(!clientOS);
        }
Пример #13
0
        public void Close()
        {
            //IntPtr hProcess = OpenProcess(ProcessAccessFlags.DupHandle, false, pid);
            IntPtr dupHandle = IntPtr.Zero;

            var status = NtDll.NtDuplicateObject(_process.BaseProcess.Handle, _handle, IntPtr.Zero, out dupHandle, 0, false, DuplicateOptions.DUPLICATE_CLOSE_SOURCE);

            NtDll.NtClose(dupHandle);

            if (status != NtStatus.Success)
            {
                throw new Exception($"Could not close handle. (NtStatus:{status.ToString()})");
            }
        }
Пример #14
0
        private static bool IsWindows10OrHigher()
        {
            var version = NtDll.RtlGetVersion();

            if (default(Version) == version)
            {
                // Snippet from Koopakiller https://dotnet-snippets.de/snippet/os-version-name-mit-wmi/4929
                using (var mos = new ManagementObjectSearcher("SELECT Caption, Version FROM Win32_OperatingSystem"))
                {
                    var attribs = mos.Get().OfType <ManagementObject>();
                    //caption = attribs.FirstOrDefault().GetPropertyValue("Caption").ToString() ?? "Unknown";
                    version = new Version((attribs.FirstOrDefault()?.GetPropertyValue("Version") ?? "0.0.0.0").ToString());
                }
            }
            return(version >= new Version(10, 0));
        }
Пример #15
0
        public int ExecThread(IntPtr Func, IntPtr Param, bool Wait = false)
        {
            int    Ret = 0;
            IntPtr Thread;

            NtDll.RtlCreateUserThread(Proc, Func, Param, out Thread);

            if (Wait)
            {
                Ret = Kernel32.WaitForSingleObject(Thread, uint.MaxValue);
            }
            if (!Kernel32.CloseHandle(Thread))
            {
                throw new Win32Exception();
            }

            return(Ret);
        }
        private static bool IsWindows10BuildOrGreaterWin32(int build)
        {
            var osVer = new NtDll.OsVersionInfoEXW
            {
                DwMajorVersion = 10, DwMinorVersion = 0, DwBuildNumber = (uint)build
            };

            const NtDll.TypeMask mask = NtDll.TypeMask.VerMajorVersion | NtDll.TypeMask.VerMinorVersion | NtDll.TypeMask.VerBuildNumber;

            ulong cond = NtDll.VerSetConditionMask(0, NtDll.TypeMask.VerMajorVersion, NtDll.Condition.VerGreaterEqual);

            cond = NtDll.VerSetConditionMask(cond, NtDll.TypeMask.VerMinorVersion, NtDll.Condition.VerGreaterEqual);
            cond = NtDll.VerSetConditionMask(cond, NtDll.TypeMask.VerBuildNumber, NtDll.Condition.VerGreaterEqual);

            // HACK: Use RtlVerifyVersionInfo instead of VerifyVersionInfoW as the
            //       latter lies unless the user knew to embed a non-default manifest
            //       announcing support for Windows 10 via supportedOS GUID
            return(NtDll.RtlVerifyVersionInfo(ref osVer, mask, cond) == 0);
        }
Пример #17
0
        public static Process GetParentProcess(this Process P)
        {
            PROCESS_BASIC_INFORMATION PBI = new PROCESS_BASIC_INFORMATION();
            int RetLen;
            int Status = 0;

            Status = NtDll.NtQueryInformationProcess(P.Handle, ProcessInformationClasss.ProcessBasicInformation, new IntPtr(&PBI),
                                                     Marshal.SizeOf(PBI), out RetLen);

            if (Status != 0)
            {
                throw new Win32Exception(Status);
            }

            try {
                return(Process.GetProcessById(PBI.Reserved3.ToInt32()));
            } catch (ArgumentException) {
                return(null);
            }
        }
        /// <summary>
        /// Returns whether the windows version running on is at least the specified one.
        /// </summary>
        private static unsafe bool IsWindowsVersionOrGreaterWin32(int major, int minor, int sp)
        {
            var osVer = new NtDll.OsVersionInfoEXW
            {
                DwMajorVersion = (uint)major, DwMinorVersion = (uint)minor, DwBuildNumber = 0, DwPlatformId = 0, WServicePackMajor = (ushort)sp
            };

            osVer.DwOSVersionInfoSize = (uint)Marshal.SizeOf(osVer);
            osVer.SzCsdVersion[0]     = (char)0;

            const NtDll.TypeMask mask = NtDll.TypeMask.VerMajorVersion | NtDll.TypeMask.VerMinorVersion | NtDll.TypeMask.VerServicePackMajor;

            ulong cond = NtDll.VerSetConditionMask(0, NtDll.TypeMask.VerMajorVersion, NtDll.Condition.VerGreaterEqual);

            cond = NtDll.VerSetConditionMask(cond, NtDll.TypeMask.VerMinorVersion, NtDll.Condition.VerGreaterEqual);
            cond = NtDll.VerSetConditionMask(cond, NtDll.TypeMask.VerServicePackMajor, NtDll.Condition.VerGreaterEqual);

            // HACK: Use RtlVerifyVersionInfo instead of VerifyVersionInfoW as the
            //       latter lies unless the user knew to embed a non-default manifest
            //       announcing support for Windows 10 via supportedOS GUID
            return(NtDll.RtlVerifyVersionInfo(ref osVer, mask, cond) == 0);
        }
Пример #19
0
        public static void spoon(out int Res)
        {
            Res = -1;
            ProcessInfo *PInf = (ProcessInfo *)Marshal.AllocHGlobal(sizeof(ProcessInfo));

            if (NtDll.RtlCloneUserProcess(CloneProcessFlags.CreateSuspended | CloneProcessFlags.InheritHandles,
                                          IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, PInf) == CloneStatus.Parent)
            {
                Res = Kernel32.GetProcessId(PInf->ProcInfo.Process);

                Kernel32.ResumeThread(PInf->ProcInfo.Thread);
                Kernel32.CloseHandle(PInf->ProcInfo.Process);
                Kernel32.CloseHandle(PInf->ProcInfo.Thread);
                Marshal.FreeHGlobal(new IntPtr(PInf));
            }
            else
            {
                Res = 0;

                if (Kernel32.FreeConsole())
                {
                    Kernel32.AllocConsole();

                    StreamWriter OutWriter = new StreamWriter(Console.OpenStandardOutput());
                    OutWriter.AutoFlush = true;
                    Console.SetOut(OutWriter);

                    StreamWriter ErrWriter = new StreamWriter(Console.OpenStandardError());
                    ErrWriter.AutoFlush = true;
                    Console.SetError(ErrWriter);

                    StreamReader InReader = new StreamReader(Console.OpenStandardInput());
                    Console.SetIn(InReader);
                }
            }
        }
Пример #20
0
        internal static unsafe bool CryptProtectData(SafeBSTRHandle uncryptedBuffer, out SafeBSTRHandle cryptedBuffer)
        {
            byte *uncryptedBufferPtr = null;

            DATA_BLOB pDataOut = default(DATA_BLOB);

            try
            {
                uncryptedBuffer.AcquirePointer(ref uncryptedBufferPtr);
                DATA_BLOB pDataIn = new DATA_BLOB((IntPtr)uncryptedBufferPtr, uncryptedBuffer.Length * 2);
                if (CryptProtectData(new IntPtr(&pDataIn), String.Empty, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, CRYPTPROTECTMEMORY_SAME_PROCESS, new IntPtr(&pDataOut)))
                {
                    SafeBSTRHandle newHandle = SafeBSTRHandle.Allocate(pDataOut.pbData, pDataOut.cbData);
                    cryptedBuffer = newHandle;
                    return(true);
                }
                else
                {
                    cryptedBuffer = SafeBSTRHandle.Allocate(null, 0);
                    return(false);
                }
            }
            finally
            {
                if (uncryptedBufferPtr != null)
                {
                    uncryptedBuffer.ReleasePointer();
                }

                if (pDataOut.pbData != IntPtr.Zero)
                {
                    NtDll.ZeroMemory(pDataOut.pbData, (UIntPtr)pDataOut.cbData);
                    Marshal.FreeHGlobal(pDataOut.pbData);
                }
            }
        }
Пример #21
0
        public override int WriteMemory(long address, byte[] data)
        {
            UIntPtr numBytes;
            int     error = 0;

            if (IsWow64() && !IsWow64Process(processHandle))
            {
                int status = NtDll.NtWow64WriteVirtualMemory64(processHandle, address, data, data.Length, out numBytes);
                error = NtDll.RtlNtStatusToDosError(status);
            }
            else
            {
                bool success = Kernel32.WriteProcessMemory(processHandle, checked ((IntPtr)address), data, data.Length, out numBytes);
                if (!success)
                {
                    error = Marshal.GetLastWin32Error();
                }
            }
            if (error != 0 && error != 299 || (error == 299 && data.Length > 0 && numBytes == UIntPtr.Zero))
            {
                throw new Win32Exception(error);
            }
            return((int)numBytes);
        }
Пример #22
0
        public NhaamaHandle[] GetHandles()
        {
            var handles = new List <NhaamaHandle>();

            var    nHandleInfoSize = 0x10000;
            var    ipHandlePointer = Marshal.AllocHGlobal(nHandleInfoSize);
            var    nLength         = 0;
            IntPtr ipHandle;

            while ((NtDll.NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemHandleInformation, ipHandlePointer, nHandleInfoSize, ref nLength)) == NtStatus.InfoLengthMismatch)
            {
                nHandleInfoSize = nLength;
                Marshal.FreeHGlobal(ipHandlePointer);
                ipHandlePointer = Marshal.AllocHGlobal(nLength);
            }

            byte[] baTemp = new byte[nLength];
            Marshal.Copy(ipHandlePointer, baTemp, 0, nLength);

            long lHandleCount;

            if (Is64BitProcess())
            {
                lHandleCount = Marshal.ReadInt64(ipHandlePointer);
                ipHandle     = new IntPtr(ipHandlePointer.ToInt64() + 8);
            }
            else
            {
                lHandleCount = Marshal.ReadInt32(ipHandlePointer);
                ipHandle     = new IntPtr(ipHandlePointer.ToInt32() + 4);
            }

            SYSTEM_HANDLE_INFORMATION shHandle;

            List <SYSTEM_HANDLE_INFORMATION> test = new List <SYSTEM_HANDLE_INFORMATION>();

            for (long lIndex = 0; lIndex < lHandleCount; lIndex++)
            {
                shHandle = new SYSTEM_HANDLE_INFORMATION();
                if (Is64BitProcess())
                {
                    shHandle = (SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(ipHandle, shHandle.GetType());
                    ipHandle = new IntPtr(ipHandle.ToInt64() + Marshal.SizeOf(shHandle) + 8);
                }
                else
                {
                    ipHandle = new IntPtr(ipHandle.ToInt64() + Marshal.SizeOf(shHandle));
                    shHandle = (SYSTEM_HANDLE_INFORMATION)Marshal.PtrToStructure(ipHandle, shHandle.GetType());
                }
                if (shHandle.ProcessID != BaseProcess.Id)
                {
                    continue;
                }

                try
                {
                    test.Add(shHandle);
                }
                catch
                {
                    // ignored
                }
            }

            foreach (var systemHandleInformation in test)
            {
                try
                {
                    handles.Add(new NhaamaHandle(new IntPtr(systemHandleInformation.Handle), this));
                }
                catch
                {
                    //ignored
                }
            }

            return(handles.ToArray());
        }