public override void Release()
        {
            Marshal.FreeHGlobal(this.pwfx_free);
            Marshal.Release(this.pdscb8);
            Marshal.Release(this.pdsc8);
            //Marshal.ReleaseComObject(this.dscb8);
            //Marshal.ReleaseComObject(this.dsc8);
            Marshal.FinalReleaseComObject(this.dscb8);
            Marshal.FinalReleaseComObject(this.dsc8);

            this.pwfx_free = IntPtr.Zero;

            this.pdscb8 = IntPtr.Zero;
            this.pdsc8  = IntPtr.Zero;

            this.dscb8 = null;
            this.dsc8  = null;

            foreach (var handle in this.notifyHandle_close)
            {
                Win32API.CloseHandle(handle);
            }
            this.notifyHandle_close = null;

            base.Release();
        }
Example #2
0
        private int MAX_PATH = 260; //字符串最大长度

        #region 读内存操作
        /// <summary>
        /// 读取内存中指定字节的数据
        /// </summary>
        /// <param name="baseAddress">需要读取的地址</param>
        /// <param name="pid">进程PID</param>
        /// <param name="value">读取到的数据</param>
        /// <returns>读取成功返回true,失败返回false</returns>
        private bool ReadMemoryValue(Int32 baseAddress, int pid, int len, out byte[] value)
        {
            try
            {
                byte[] buffer      = new byte[len];
                IntPtr byteAddress = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0); //获取缓冲区地址
                IntPtr hProcess    = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, pid);
                if (hProcess == IntPtr.Zero)
                {
                    value = new byte[len];
                    return(false);
                }
                int  read;
                bool ret = Win32API.ReadProcessMemory(hProcess, (IntPtr)baseAddress, byteAddress, len, out read); //将指定内存中的值读入缓冲区
                Win32API.CloseHandle(hProcess);
                if (ret == false)
                {
                    value = new byte[len];
                    return(false);
                }
                value = buffer;
                return(true);
            }
            catch
            {
                value = new byte[len];
                return(false);
            }
        }
        public void Set_SONY_DS4_Output(byte RightMotor, byte LeftMotor, byte RedLed, byte GreenLed, byte BlueLed)
        {
            IntPtr DeviceFileHandle = Win32API.CreateFile(_DeviceName,
                                                          Win32API.DesiredAccess.Read | Win32API.DesiredAccess.Write,
                                                          Win32API.ShareMode.Read | Win32API.ShareMode.Write,
                                                          IntPtr.Zero,
                                                          Win32API.CreateDisposition.OpenExisting,
                                                          0,
                                                          IntPtr.Zero);

            if (DeviceFileHandle != new IntPtr(-1))
            {
                byte[] buf = new byte[32];
                buf[0] = 0x05;
                buf[1] = 0xFF;
                buf[4] = RightMotor;  // 0-255
                buf[5] = LeftMotor;   // 0-255
                buf[6] = RedLed;      // 0-255
                buf[7] = GreenLed;    // 0-255
                buf[8] = BlueLed;     // 0-255
                uint bytes_written;
                bool res = Win32API.WriteFile(DeviceFileHandle, buf, (uint)buf.Length, out bytes_written, IntPtr.Zero);


                Win32API.CloseHandle(DeviceFileHandle);
            }
        }
        public void Set_SONY_PS3_Output(byte RightMotor, byte LeftMotor, byte RedLed, byte GreenLed, byte BlueLed)
        {
            IntPtr DeviceFileHandle = Win32API.CreateFile(_DeviceName,
                                                          Win32API.DesiredAccess.Read | Win32API.DesiredAccess.Write,
                                                          Win32API.ShareMode.Read | Win32API.ShareMode.Write,
                                                          IntPtr.Zero,
                                                          Win32API.CreateDisposition.OpenExisting,
                                                          0,
                                                          IntPtr.Zero);

            if (DeviceFileHandle != new IntPtr(-1))
            {
                byte[] command = new byte[37];
                command = new byte[] { 0x52,
                                       0x01,
                                       0x00, 0xfe, RightMotor, 0xfe, LeftMotor,
                                       0x00, 0x00, 0x00, 0x00, RedLed,
                                       0xff, 0x27, 0x10, 0x00, 0x32,
                                       0xff, 0x27, 0x10, 0x00, 0x32,
                                       0xff, 0x27, 0x10, 0x00, 0x32,
                                       0xff, 0x27, 0x10, 0x00, 0x32,
                                       0x00, 0x00, 0x00, 0x00, 0x00 };

                uint bytes_written;
                bool res = Win32API.WriteFile(DeviceFileHandle, command, (uint)command.Length, out bytes_written, IntPtr.Zero);


                Win32API.CloseHandle(DeviceFileHandle);
            }
        }
Example #5
0
        /// <summary>
        /// 获取模块地址
        /// </summary>
        /// <param name="pid">目标进程PID</param>
        /// <param name="moduleName">需获取到的模块名</param>
        /// <returns>返回个int类型的吧.想怎么转换看你们自己了.</returns>
        public int GetModelBaseAddr(int pid, string moduleName)
        {
            Win32API.PROCESSENTRY32 pr = new Win32API.PROCESSENTRY32();
            Win32API.MODULEENTRY32  mo = new Win32API.MODULEENTRY32();
            IntPtr LM;

            if (string.IsNullOrEmpty(moduleName))
            {
                return(-1);
            }
            pr.dwSize = (uint)Marshal.SizeOf(typeof(Win32API.PROCESSENTRY32));
            LM        = Win32API.CreateToolhelp32Snapshot(Win32API.TH32CS_SNAPMODULE, (IntPtr)pid);
            if (LM.ToInt32() > 0)
            {
                mo.dwSize = (uint)Marshal.SizeOf(typeof(Win32API.MODULEENTRY32));
                if (Win32API.Module32First(LM, ref mo))
                {
                    do
                    {
                        if (mo.szModule == moduleName)
                        {
                            Win32API.CloseHandle(LM);
                            return(mo.modBaseAddr.ToInt32());
                        }
                    }while (Win32API.Module32Next(LM, ref mo));
                }
                Win32API.CloseHandle(LM);
            }
            //获取不到.或者遍历不到.都返回-1
            return(-1);
        }
Example #6
0
        public override void Release()
        {
            Marshal.FreeHGlobal(this.pwfx_free);
            Marshal.Release(this.pdsb8);
            Marshal.Release(this.pds8);
            //Marshal.ReleaseComObject(this.dsb8);
            //Marshal.ReleaseComObject(this.ds8);
            Marshal.FinalReleaseComObject(this.dsb8);
            Marshal.FinalReleaseComObject(this.ds8);

            this.pwfx_free = IntPtr.Zero;

            this.pdsb8 = IntPtr.Zero;
            this.pds8  = IntPtr.Zero;

            this.dsb8 = null;
            this.ds8  = null;

            foreach (var item in notifyHwnd_close)
            {
                Win32API.CloseHandle(item);
            }
            this.notifyHwnd_close = null;
            this.rgdsbpn          = null;

            base.Release();
        }
Example #7
0
 public void Undo()
 {
     try
     {
         Win32API.CloseHandle(_main_token);
         _win_identity_context.Undo();
     }
     catch (Exception ex) { }
 }
        public static IEnumerable <string> UnsafeGetFilesLockedBy(List <int> pids)
        {
            if (!Utils.IsAdmin)
            {
                Log.Error("You are not running with administrator rights, therefore you cannot use the internal implementation.");
                yield break;
            }

            foreach (var handle in GetHandles(pids))
            {
                var path = string.Empty;
                var hwnd = IntPtr.Zero;
                var hinf = handle;

                using (var mre = new ManualResetEvent(false))
                {
                    var thd = new Thread(() =>
                    {
                        try
                        {
                            path = GetFilePath(hinf, ref hwnd);
                        }
                        catch { }
                        finally
                        {
                            try { mre.Set(); } catch { }
                        }
                    })
                    {
                        IsBackground = true
                    };

                    thd.Start();

                    if (!mre.WaitOne(100))
                    {
                        Log.Trace("Handle 0x" + handle.Handle.ToString("X") + " timed out and will now hopefully be killed.");

                        new Thread(() =>
                        {
                            try
                            {
                                Win32API.CancelIo(hwnd);
                                Win32API.CloseHandle(hwnd);
                                thd.Interrupt();
                                thd.Abort();
                            } catch { }
                        }).Start();
                    }
                }

                if (!string.IsNullOrEmpty(path))
                {
                    yield return(path);
                }
            }
        }
Example #9
0
        // =====================================================================
        // ShareDIO FileMapping Delete Object
        // =====================================================================

        public int ShareMemory_DeleteDIOObject()
        {
            if (this.mbFirstInited != 1)
            {
                return(-1);
            }
            this.mbFirstInited = 0;
            Win32API.UnmapViewOfFile(mlpPulseAndSensorAddress);
            Win32API.CloseHandle(mhPulseAndSensorMapping);
            Win32API.CloseHandle(mhPulseAndSensorMutex);

            return(0);
        }
Example #10
0
        public Impersonator(string xiUserName, string xiPassword, string xiDomain)
        {
            if (!Win32API.RevertToSelf())
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            IntPtr token = IntPtr.Zero;

            try
            {
                if (string.IsNullOrEmpty(xiDomain))
                {
                    xiDomain = System.Environment.MachineName;
                }

                if (Win32API.LogonUser(xiUserName, xiDomain, xiPassword, Win32API.LOGON32_LOGON_INTERACTIVE, Win32API.LOGON32_PROVIDER_DEFAULT, ref token) == 0)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                IntPtr tokenDuplicate = IntPtr.Zero;

                try
                {
                    if (Win32API.DuplicateToken(token, 2 /*SecurityImpersonation*/, ref tokenDuplicate) == 0)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    using (var tempWindowsIdentity = new WindowsIdentity(tokenDuplicate))
                    {
                        ImpersonationContext = tempWindowsIdentity.Impersonate();
                    }
                }
                finally
                {
                    if (tokenDuplicate != IntPtr.Zero)
                    {
                        Win32API.CloseHandle(tokenDuplicate);
                    }
                }
            }
            finally
            {
                if (token != IntPtr.Zero)
                {
                    Win32API.CloseHandle(token);
                }
            }
        }
Example #11
0
 /// <summary>
 /// 将值写入指定内存地址中
 /// </summary>
 /// <param name="baseAddress">需要写入的地址</param>
 /// <param name="processName">进程名</param>
 /// <param name="value">写入的值</param>
 private bool WriteMemoryValue(Int32 baseAddress, int pid, byte[] value)
 {
     try
     {
         IntPtr hProcess = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, pid); //0x1F0FFF 最高权限
         if (hProcess == IntPtr.Zero)
         {
             return(false);
         }
         bool ret = Win32API.WriteProcessMemory(hProcess, (IntPtr)baseAddress, value, value.Length, IntPtr.Zero);
         Win32API.CloseHandle(hProcess);
         return(ret);
     }
     catch
     {
         return(false);
     }
 }
        /// <summary>
        /// Read and store Manufacturer string and Product string from the device
        /// These values are read by opening a File Handle with the device
        /// </summary>
        private void GetManufacturerAndProductString(String DevicePath)
        {
            IntPtr DeviceFileHandle = Win32API.CreateFile(DevicePath,
                                                          Win32API.DesiredAccess.None,
                                                          Win32API.ShareMode.Read | Win32API.ShareMode.Write,
                                                          IntPtr.Zero,
                                                          Win32API.CreateDisposition.OpenExisting,
                                                          0,
                                                          IntPtr.Zero);

            if (DeviceFileHandle != new IntPtr(-1))
            {
                byte[] buf = new byte[256];
                if (!Win32API.HidD_GetManufacturerString(DeviceFileHandle, buf, (uint)buf.Length))
                {
                    //Error
                    _ManufacturerName = "[Unknown Manufacturer]";
                }
                else
                {
                    _ManufacturerName = Encoding.Unicode.GetString(buf, 0, buf.Length);
                    if (_ManufacturerName.Contains("\0"))
                    {
                        _ManufacturerName = _ManufacturerName.Substring(0, _ManufacturerName.IndexOf("\0"));
                    }
                }

                if (!Win32API.HidD_GetProductString(DeviceFileHandle, buf, (uint)buf.Length))
                {
                    //Error
                    _ProductName = "[Unknown Product]";
                }
                else
                {
                    _ProductName = Encoding.Unicode.GetString(buf, 0, buf.Length);
                    if (_ProductName.Contains("\0"))
                    {
                        _ProductName = _ProductName.Substring(0, _ProductName.IndexOf("\0"));
                    }
                }

                Win32API.CloseHandle(DeviceFileHandle);
            }
        }
Example #13
0
            private static string GetFilePath(Win32API.SYSTEM_HANDLE_INFORMATION sYSTEM_HANDLE_INFORMATION, Process process)
            {
                IntPtr m_ipProcessHwnd   = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, process.Id);
                IntPtr ipHandle          = IntPtr.Zero;
                var    objBasic          = new Win32API.OBJECT_BASIC_INFORMATION();
                IntPtr ipBasic           = IntPtr.Zero;
                var    objObjectType     = new Win32API.OBJECT_TYPE_INFORMATION();
                IntPtr ipObjectType      = IntPtr.Zero;
                var    objObjectName     = new Win32API.OBJECT_NAME_INFORMATION();
                IntPtr ipObjectName      = IntPtr.Zero;
                string strObjectTypeName = "";
                string strObjectName     = "";
                int    nLength           = 0;
                int    nReturn           = 0;
                IntPtr ipTemp            = IntPtr.Zero;

                if (!Win32API.DuplicateHandle(m_ipProcessHwnd, sYSTEM_HANDLE_INFORMATION.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_SAME_ACCESS))
                {
                    return(null);
                }

                ipBasic = Marshal.AllocHGlobal(Marshal.SizeOf(objBasic));
                Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectBasicInformation, ipBasic, Marshal.SizeOf(objBasic), ref nLength);
                objBasic = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(ipBasic, objBasic.GetType());
                Marshal.FreeHGlobal(ipBasic);


                ipObjectType = Marshal.AllocHGlobal(objBasic.TypeInformationLength);
                nLength      = objBasic.TypeInformationLength;
                while ((uint)(nReturn = Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectTypeInformation, ipObjectType, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
                {
                    Marshal.FreeHGlobal(ipObjectType);
                    ipObjectType = Marshal.AllocHGlobal(nLength);
                }

                objObjectType = (Win32API.OBJECT_TYPE_INFORMATION)Marshal.PtrToStructure(ipObjectType, objObjectType.GetType());
                if (Is64Bits())
                {
                    ipTemp = new IntPtr(Convert.ToInt64(objObjectType.Name.Buffer.ToString(), 10) >> 32);
                }
                else
                {
                    ipTemp = objObjectType.Name.Buffer;
                }

                strObjectTypeName = Marshal.PtrToStringUni(ipTemp, objObjectType.Name.Length >> 1);
                Marshal.FreeHGlobal(ipObjectType);
                if (strObjectTypeName != "File")
                {
                    return(null);
                }

                nLength = objBasic.NameInformationLength;

                ipObjectName = Marshal.AllocHGlobal(nLength);
                while ((uint)(nReturn = Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectNameInformation, ipObjectName, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
                {
                    Marshal.FreeHGlobal(ipObjectName);
                    ipObjectName = Marshal.AllocHGlobal(nLength);
                }
                objObjectName = (Win32API.OBJECT_NAME_INFORMATION)Marshal.PtrToStructure(ipObjectName, objObjectName.GetType());
                //
                if (Is64Bits())
                {
                    ipTemp = new IntPtr(Convert.ToInt64(objObjectName.Name.Buffer.ToString(), 10) >> 32);
                }
                else
                {
                    ipTemp = objObjectName.Name.Buffer;
                }

                if (ipTemp != IntPtr.Zero)
                {
                    if (nLength < 0)
                    {
                        return(null);
                    }
                    byte[] baTemp = new byte[nLength];
                    try
                    {
                        Marshal.Copy(ipTemp, baTemp, 0, nLength);

                        strObjectName = Marshal.PtrToStringUni(Is64Bits() ? new IntPtr(ipTemp.ToInt64()) : new IntPtr(ipTemp.ToInt32()));
                    }
                    catch (Exception)        //AccessViolationException)
                    {
                        return(null);
                    }
                    finally
                    {
                        Marshal.FreeHGlobal(ipObjectName);
                        Win32API.CloseHandle(ipHandle);
                    }
                }

                string path = GetRegularFileNameFromDevice(strObjectName);

                try
                {
                    return(path);
                }
                catch
                {
                    return(null);
                }
            }
Example #14
0
 public void CloseHandle()
 {
     Win32API.CloseHandle(new IntPtr(int.Parse(sYSTEM_HANDLE_INFORMATION.Handle.ToString())));
 }
Example #15
0
        private void _loadInfo()
        {
            IntPtr ipHandle = IntPtr.Zero;

            Win32API.OBJECT_BASIC_INFORMATION objBasic = new Win32API.OBJECT_BASIC_INFORMATION();
            IntPtr ipBasic = IntPtr.Zero;

            Win32API.OBJECT_TYPE_INFORMATION objObjectType = new Win32API.OBJECT_TYPE_INFORMATION();
            IntPtr ipObjectType = IntPtr.Zero;

            Win32API.OBJECT_NAME_INFORMATION objObjectName = new Win32API.OBJECT_NAME_INFORMATION();
            IntPtr ipObjectName      = IntPtr.Zero;
            string strObjectTypeName = "";
            string strObjectName     = "";
            int    nLength           = 0;
            int    nReturn           = 0;
            IntPtr ipTemp            = IntPtr.Zero;
            IntPtr m_ipProcessHwnd   = m_ipProcessHwnd = Win32API.OpenProcess(Win32API.ProcessAccessFlags.DupHandle, false, sYSTEM_HANDLE_INFORMATION.ProcessID);

            //OpenProcessForHandle(sYSTEM_HANDLE_INFORMATION.ProcessID);
            if (!Win32API.DuplicateHandle(m_ipProcessHwnd, sYSTEM_HANDLE_INFORMATION.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_SAME_ACCESS))
            {
                return;
            }

            ipBasic = Marshal.AllocHGlobal(Marshal.SizeOf(objBasic));
            Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectBasicInformation, ipBasic, Marshal.SizeOf(objBasic), ref nLength);
            objBasic = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(ipBasic, objBasic.GetType());
            Marshal.FreeHGlobal(ipBasic);


            ipObjectType = Marshal.AllocHGlobal(objBasic.TypeInformationLength);
            nLength      = objBasic.TypeInformationLength;
            while ((uint)(nReturn = Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectTypeInformation, ipObjectType, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
            {
                Marshal.FreeHGlobal(ipObjectType);
                ipObjectType = Marshal.AllocHGlobal(nLength);
            }

            objObjectType = (Win32API.OBJECT_TYPE_INFORMATION)Marshal.PtrToStructure(ipObjectType, objObjectType.GetType());
            if (Is64Bits())
            {
                ipTemp = new IntPtr(Convert.ToInt64(objObjectType.Name.Buffer.ToString(), 10) >> 32);
            }
            else
            {
                ipTemp = objObjectType.Name.Buffer;
            }

            strObjectTypeName = Marshal.PtrToStringUni(ipTemp, objObjectType.Name.Length >> 1);
            Marshal.FreeHGlobal(ipObjectType);
            if (strObjectTypeName != "File")
            {
                return;
            }

            nLength      = objBasic.NameInformationLength;
            ipObjectName = Marshal.AllocHGlobal(nLength);
            while ((uint)(nReturn = Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectNameInformation, ipObjectName, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
            {
                Marshal.FreeHGlobal(ipObjectName);
                ipObjectName = Marshal.AllocHGlobal(nLength);
            }
            objObjectName = (Win32API.OBJECT_NAME_INFORMATION)Marshal.PtrToStructure(ipObjectName, objObjectName.GetType());

            if (Is64Bits())
            {
                ipTemp = new IntPtr(Convert.ToInt64(objObjectName.Name.Buffer.ToString(), 10) >> 32);
            }
            else
            {
                ipTemp = objObjectName.Name.Buffer;
            }

            byte[] baTemp = new byte[nLength];
            try
            {
                Win32API.CopyMemory(baTemp, ipTemp, (uint)nLength);
            }
            catch (Exception ex) { }

            if (Is64Bits())
            {
                strObjectName = Marshal.PtrToStringUni(new IntPtr(ipTemp.ToInt64()));
            }
            else
            {
                strObjectName = Marshal.PtrToStringUni(new IntPtr(ipTemp.ToInt32()));
            }

            Marshal.FreeHGlobal(ipObjectName);
            Win32API.CloseHandle(ipHandle);

            _name = GetRegularFileNameFromDevice(strObjectName);
        }
Example #16
0
        /// <summary>
        /// 检查指针是否有效
        /// </summary>
        /// <param name="strs"></param>
        /// <returns>-1为无效,返回最后指针</returns>
        private int GetFindDataAddr(string strs, int pid)
        {
            int readaddr = 0;
            int longAdd  = 0;                        //返回最后指针

            char[] module      = new char[MAX_PATH]; //记录模块的名字
            int    moduleindex = 0;                  //记录模块长度
            int    nindex      = 0;                  //记录指针个数
            int    noffset     = 0;
            int    index       = 0;

            bool[] subindex = new bool[MAX_PATH];           //标记"-"号的位置:true,默认是"+":false
            char[,] offsetaddrstr = new char[MAX_PATH, 16]; //存储偏移地址
            int[] offsetaddr = new int[MAX_PATH];           //存储指针

            int len = strs.Length;

            if (len < 1)
            {
                longAdd = -1;
                return(longAdd);
            }
            for (int i = 0; i < len; i++)
            {
                if (strs[i] == '<' || moduleindex > 0)                 //获取模块名字
                {
                    if (strs[i] == '>')
                    {
                        moduleindex = -1;
                    }
                    else if (strs[i + 1] != '>')
                    {
                        module[moduleindex] = strs[i + 1];
                        moduleindex++;
                    }
                }
                if (strs[i] == '>' && moduleindex == 0)                //模块名字错误
                {
                    longAdd = -1;
                    return(longAdd);
                }
                if (strs[i] == '[')
                {
                    nindex++;                                              //记录指针个数
                }
                else if (((strs[i] == '+' || index > 0) || (strs[i] == '-' || index > 0) || moduleindex == 0))
                {
                    if (strs[i] == '-')                                   //记录-号的下标
                    {
                        subindex[noffset] = true;
                    }
                    if (strs[i] == ']')
                    {
                        index = 0;
                        noffset++;
                    }
                    else if (strs[i] != ']' && (strs[i] == '+' || strs[i] == '-'))
                    {
                        offsetaddrstr[noffset, index] = strs[i + 1];
                        index++;
                        i++;
                    }
                    else if (strs[i] != ']')
                    {
                        offsetaddrstr[noffset, index] = strs[i];
                        index++;
                    }
                }
                else if ((noffset == nindex))       //记录最后一个偏移地址
                {
                    if (strs[i] == '-')             //记录-号的下标
                    {
                        subindex[noffset] = true;
                    }
                    if (strs[i] == '+' || strs[i] == '-')
                    {
                        offsetaddrstr[noffset, index] = strs[i + 1];
                        index++;
                    }
                    else if (index > 0)
                    {
                        offsetaddrstr[noffset, index] = strs[i + 1];
                        index++;
                    }
                }
            }

            int Baseaddr = 0;

            if (moduleindex == -1) //说明有传入<modulename>
            {
                String moduleName = new String(module);
                moduleName = moduleName.Replace(new String(new Char[] { '\0' }), "");
                Baseaddr   = GetModelBaseAddr(pid, moduleName);
                if (Baseaddr <= 0)
                {
                    longAdd = -1;
                    return(longAdd);
                }
            }

            if (nindex > 0) //说明不是一级指针
            {
                for (int i = 0; i < nindex; i++)
                {
                    string s = "";
                    for (int j = 0; j < 16; j++)
                    {
                        if (offsetaddrstr[i, j] != '\0')
                        {
                            s = s + offsetaddrstr[i, j];
                        }
                    }
                    offsetaddr[i] = Convert.ToInt32(s, 16);
                    if (i == 0 && Baseaddr > 0)
                    {
                        readaddr = Baseaddr + offsetaddr[i];
                    }
                    else if (i == 0)
                    {
                        readaddr = offsetaddr[i];
                    }
                    else if (readaddr != 0)
                    {
                        if (subindex[i])
                        {
                            readaddr = longAdd - offsetaddr[i];
                        }
                        else
                        {
                            readaddr = longAdd + offsetaddr[i];
                        }
                    }

                    byte[] buffer      = new byte[4];
                    IntPtr byteAddress = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0); //获取缓冲区地址
                    IntPtr hProcess    = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, pid);
                    int    read        = 0;
                    bool   ret         = Win32API.ReadProcessMemory(hProcess, (IntPtr)readaddr, byteAddress, 4, out read); //将指定内存中的值读入缓冲区
                    Win32API.CloseHandle(hProcess);
                    if (ret == false || read <= 0)
                    {
                        return(-1);
                    }
                    longAdd = Marshal.ReadInt32(byteAddress);

                    if (longAdd == 0) //说明读取错误地址
                    {
                        longAdd = -1;
                        return(longAdd);
                    }
                }
                string st = "";
                for (int j = 0; j < 16; j++)
                {
                    if (offsetaddrstr[nindex, j] != '\0')
                    {
                        st = st + offsetaddrstr[nindex, j];
                    }
                }
                offsetaddr[nindex] = Convert.ToInt32(st, 16); //最后一个偏移
                if (subindex[nindex])
                {
                    longAdd = longAdd - offsetaddr[nindex];
                }
                else
                {
                    longAdd = longAdd + offsetaddr[nindex];
                }
            }
            else if (moduleindex != -1) //1367DBC   都是数值
            {
                longAdd = Convert.ToInt32(strs, 16);
            }
            else if (moduleindex == -1) //<xx.exe>+1367DBC    模块地址+数值
            {
                string s = "";
                for (int i = 0; i < 16; i++)
                {
                    if (offsetaddrstr[0, i] != '\0')
                    {
                        s = s + offsetaddrstr[0, i];
                    }
                }
                longAdd = Convert.ToInt32(s, 16);
                longAdd = Baseaddr + longAdd;
            }
            return(longAdd);               //返回最后地址;
        }
        private static string GetFilePath(Win32API.SYSTEM_HANDLE_INFORMATION systemHandleInformation, ref IntPtr ipHandle)
        {
            var ipProcessHwnd = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, systemHandleInformation.ProcessID);
            var objBasic      = new Win32API.OBJECT_BASIC_INFORMATION();
            var objObjectType = new Win32API.OBJECT_TYPE_INFORMATION();
            var objObjectName = new Win32API.OBJECT_NAME_INFORMATION();
            var strObjectName = "";
            var nLength       = 0;

            if (!Win32API.DuplicateHandle(ipProcessHwnd, systemHandleInformation.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_SAME_ACCESS))
            {
                //Log.Trace("GetFilePath(" + systemHandleInformation.ProcessID + ", 0x" + systemHandleInformation.Handle.ToString("X") + ") : DuplicateHandle(0x" + ipProcessHwnd.ToString("X") + ", 0x" + systemHandleInformation.Handle.ToString("X") + ") returned false.");
                return(null);
            }

            IntPtr ipBasic = Marshal.AllocHGlobal(Marshal.SizeOf(objBasic));

            Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectBasicInformation, ipBasic, Marshal.SizeOf(objBasic), ref nLength);
            objBasic = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(ipBasic, objBasic.GetType());
            Marshal.FreeHGlobal(ipBasic);

            IntPtr ipObjectType = Marshal.AllocHGlobal(objBasic.TypeInformationLength);

            nLength = objBasic.TypeInformationLength;
            // this one never locks...
            while ((uint)(Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectTypeInformation, ipObjectType, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
            {
                if (nLength == 0)
                {
                    Log.Trace("GetFilePath(" + systemHandleInformation.ProcessID + ", 0x" + systemHandleInformation.Handle.ToString("X") + ") : NtQueryObject(0x" + ipHandle.ToString("X") + ", ObjectTypeInformation) returned !STATUS_INFO_LENGTH_MISMATCH when nLength == 0.");
                    return(null);
                }
                Marshal.FreeHGlobal(ipObjectType);
                ipObjectType = Marshal.AllocHGlobal(nLength);
            }

            // TODO: check if this code still works on Windows 7, now that UNICODE_STRING doesn't have Pack = 1 defined

            objObjectType = (Win32API.OBJECT_TYPE_INFORMATION)Marshal.PtrToStructure(ipObjectType, objObjectType.GetType());

            // All handles that have these access flags seem to hang the NtQueryObject below.
            // Original discussion: http://forum.sysinternals.com/handle-name-help-ntqueryobject_topic14435_post68507.html#68507

            if (objBasic.GrantedAccess == 0x0012019F || objObjectType.ValidAccess == 0x0012019F || objBasic.GrantedAccess == 0x001A019F || objObjectType.ValidAccess == 0x001A019F)
            {
                Log.Trace("Blacklisted access value for handle 0x" + ipHandle.ToString("X") + "; see source code for more information.");
                return(null);
            }

            var strObjectTypeName = Marshal.PtrToStringUni(objObjectType.Name.Buffer, objObjectType.Name.Length >> 1);

            Marshal.FreeHGlobal(ipObjectType);
            if (strObjectTypeName != "File")
            {
                return(null);
            }

            nLength = objBasic.NameInformationLength;

            var ipObjectName = Marshal.AllocHGlobal(nLength);

            // ...this call sometimes hangs due to a Windows error.
            while ((uint)(Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectNameInformation, ipObjectName, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
            {
                Marshal.FreeHGlobal(ipObjectName);
                if (nLength == 0)
                {
                    Log.Trace("GetFilePath(" + systemHandleInformation.ProcessID + ", 0x" + systemHandleInformation.Handle.ToString("X") + ") : NtQueryObject(0x" + ipHandle.ToString("X") + ", ObjectNameInformation) returned !STATUS_INFO_LENGTH_MISMATCH when nLength == 0.");
                    return(null);
                }
                ipObjectName = Marshal.AllocHGlobal(nLength);
            }
            objObjectName = (Win32API.OBJECT_NAME_INFORMATION)Marshal.PtrToStructure(ipObjectName, objObjectName.GetType());

            if (objObjectName.Name.Buffer.ToInt64() > 0 && nLength > 0)
            {
                var baTemp = new byte[nLength];
                try
                {
                    Marshal.Copy(objObjectName.Name.Buffer, baTemp, 0, nLength);

                    strObjectName = Marshal.PtrToStringUni(objObjectName.Name.Buffer);
                }
                catch (AccessViolationException ex)
                {
                    Log.Trace("GetFilePath(" + systemHandleInformation.ProcessID + ", 0x" + systemHandleInformation.Handle.ToString("X") + ") Error while marshaling file name.", ex);
                    return(null);
                }
                finally
                {
                    Marshal.FreeHGlobal(ipObjectName);
                    Win32API.CloseHandle(ipHandle);
                }
            }

            if (strObjectName == null)
            {
                return(null);
            }

            if (strObjectName.StartsWith(@"\Device\Mup\"))
            {
                return(@"\\" + strObjectName.Substring(12));
            }

            try
            {
                return(GetRegularFileNameFromDevice(strObjectName));
            }
            catch
            {
                return(null);
            }
        }
Example #18
0
        private static string GetFilePath(Win32API.SYSTEM_HANDLE_INFORMATION systemHandleInformation, Process process)
        {
            var    ipProcessHwnd = Win32API.OpenProcess(Win32API.ProcessAccessFlags.All, false, process.Id);
            var    objBasic = new Win32API.OBJECT_BASIC_INFORMATION();
            var    objObjectType = new Win32API.OBJECT_TYPE_INFORMATION();
            var    objObjectName = new Win32API.OBJECT_NAME_INFORMATION();
            var    strObjectName = "";
            var    nLength = 0;
            IntPtr ipTemp, ipHandle;

            if (!Win32API.DuplicateHandle(ipProcessHwnd, systemHandleInformation.Handle, Win32API.GetCurrentProcess(), out ipHandle, 0, false, Win32API.DUPLICATE_SAME_ACCESS))
            {
                return(null);
            }

            IntPtr ipBasic = Marshal.AllocHGlobal(Marshal.SizeOf(objBasic));

            Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectBasicInformation, ipBasic, Marshal.SizeOf(objBasic), ref nLength);
            objBasic = (Win32API.OBJECT_BASIC_INFORMATION)Marshal.PtrToStructure(ipBasic, objBasic.GetType());
            Marshal.FreeHGlobal(ipBasic);

            IntPtr ipObjectType = Marshal.AllocHGlobal(objBasic.TypeInformationLength);

            nLength = objBasic.TypeInformationLength;
            // this one never locks...
            while ((uint)(Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectTypeInformation, ipObjectType, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
            {
                if (nLength == 0)
                {
                    Console.WriteLine("nLength returned at zero! ");
                    return(null);
                }
                Marshal.FreeHGlobal(ipObjectType);
                ipObjectType = Marshal.AllocHGlobal(nLength);
            }

            objObjectType = (Win32API.OBJECT_TYPE_INFORMATION)Marshal.PtrToStructure(ipObjectType, objObjectType.GetType());
            if (Is64Bits())
            {
                ipTemp = new IntPtr(Convert.ToInt64(objObjectType.Name.Buffer.ToString(), 10) >> 32);
            }
            else
            {
                ipTemp = objObjectType.Name.Buffer;
            }

            var strObjectTypeName = Marshal.PtrToStringUni(ipTemp, objObjectType.Name.Length >> 1);

            Marshal.FreeHGlobal(ipObjectType);
            if (strObjectTypeName != "File")
            {
                return(null);
            }

            nLength = objBasic.NameInformationLength;

            var ipObjectName = Marshal.AllocHGlobal(nLength);

            // ...this call sometimes hangs. Is a Windows error.
            while ((uint)(Win32API.NtQueryObject(ipHandle, (int)Win32API.ObjectInformationClass.ObjectNameInformation, ipObjectName, nLength, ref nLength)) == Win32API.STATUS_INFO_LENGTH_MISMATCH)
            {
                Marshal.FreeHGlobal(ipObjectName);
                if (nLength == 0)
                {
                    Console.WriteLine("nLength returned at zero! " + strObjectTypeName);
                    return(null);
                }
                ipObjectName = Marshal.AllocHGlobal(nLength);
            }
            objObjectName = (Win32API.OBJECT_NAME_INFORMATION)Marshal.PtrToStructure(ipObjectName, objObjectName.GetType());

            if (Is64Bits())
            {
                ipTemp = new IntPtr(Convert.ToInt64(objObjectName.Name.Buffer.ToString(), 10) >> 32);
            }
            else
            {
                ipTemp = objObjectName.Name.Buffer;
            }

            if (ipTemp != IntPtr.Zero)
            {
                var baTemp = new byte[nLength];
                try
                {
                    Marshal.Copy(ipTemp, baTemp, 0, nLength);

                    strObjectName = Marshal.PtrToStringUni(Is64Bits() ? new IntPtr(ipTemp.ToInt64()) : new IntPtr(ipTemp.ToInt32()));
                }
                catch (AccessViolationException)
                {
                    return(null);
                }
                finally
                {
                    Marshal.FreeHGlobal(ipObjectName);
                    Win32API.CloseHandle(ipHandle);
                }
            }

            string path = GetRegularFileNameFromDevice(strObjectName);

            try
            {
                return(path);
            }
            catch
            {
                return(null);
            }
        }
Example #19
0
        /// <summary>
        /// Get broker's identity. If on a failover cluster, get resoruce group network name
        /// computer account login token
        /// Notice: This method returns null if it is not failover cluster or it is Azure cluster.
        /// </summary>
        /// <returns></returns>
        private static WindowsIdentity GetBrokerIdentity()
        {
            if (SoaHelper.IsOnAzure())
            {
                // Skip following logic if it is on Azure.
                return(null);
            }

            int clusterState = (int)ClusterState.ClusterStateNotInstalled;

            uint ret = Win32API.GetNodeClusterState(null, out clusterState);

            if (ret != 0)
            {
                TraceHelper.TraceEvent(TraceEventType.Error, "Cannot access local failover cluster state. Error = {0}", ret);
                return(null);
            }

            if (clusterState == (int)ClusterState.ClusterStateNotConfigured || clusterState == (int)ClusterState.ClusterStateNotInstalled)
            {
                TraceHelper.TraceEvent(TraceEventType.Information, "Cannot access local failover cluster state. Error = {0}", ret);
                return(null);
            }

            IntPtr hCluster  = IntPtr.Zero;
            IntPtr hResource = IntPtr.Zero;

            try
            {
                // Get handle to local failover cluster
                hCluster = Win32API.OpenCluster(null);
                if (hCluster == IntPtr.Zero)
                {
                    TraceHelper.TraceEvent(TraceEventType.Error, "Cannot connect to local failover cluster. Error = {0}", Marshal.GetLastWin32Error());
                    return(null);
                }

                // Get handle to this broker's network name resource
                hResource = Win32API.OpenClusterResource(hCluster, Environment.MachineName);
                if (hResource == IntPtr.Zero)
                {
                    TraceHelper.TraceEvent(TraceEventType.Error, "Cannot connect to local failover cluster. Error = {0}", Marshal.GetLastWin32Error());
                    return(null);
                }

                // Get the login token of the network name for the broker's resource group's network name. This
                // is a computer account login token and is use to impersonate all calls to the services. The services
                // then ensure calls are only from broker nodes or resource groups.
                IntPtr loginToken = IntPtr.Zero;

                try
                {
                    loginToken = GetNetworkNameLoginToken(hCluster, hResource);

                    if (loginToken != IntPtr.Zero)
                    {
                        // Put login token in a WindowsIdentity object
                        // WindowsIdentity calls DuplicateToken and it is fine to close the handle later
                        return(new WindowsIdentity(loginToken));
                    }
                    else
                    {
                        return(null);
                    }
                }
                finally
                {
                    if (loginToken != IntPtr.Zero)
                    {
                        Win32API.CloseHandle(loginToken);
                    }
                }
            }

            finally
            {
                if (hResource != IntPtr.Zero)
                {
                    Win32API.CloseClusterResource(hResource);
                }

                if (hCluster != IntPtr.Zero)
                {
                    Win32API.CloseCluster(hCluster);
                }
            }
        }