Example #1
0
 // Populates the entries.
 public async Task InsertDataEntries(NativeHandle mdEntriesH, Dictionary <string, List <byte> > data)
 {
     foreach (var pair in data)
     {
         await Session.MDataEntries.InsertAsync(mdEntriesH, pair.Key.ToUtfBytes(), pair.Value);
     }
 }
        public static Task InsertAsync(NativeHandle entryActionsH, List <byte> entKey, List <byte> entVal)
        {
            var tcs = new TaskCompletionSource <object>();

            ResultCb callback = (_, result) => {
                if (result.ErrorCode != 0)
                {
                    tcs.SetException(result.ToException());
                    return;
                }

                tcs.SetResult(null);
            };

            var entKeyPtr = entKey.ToIntPtr();
            var entValPtr = entVal.ToIntPtr();

            AppBindings.MDataEntryActionsInsert(
                Session.AppPtr,
                entryActionsH,
                entKeyPtr,
                (IntPtr)entKey.Count,
                entValPtr,
                (IntPtr)entVal.Count,
                callback);

            Marshal.FreeHGlobal(entKeyPtr);
            Marshal.FreeHGlobal(entValPtr);

            return(tcs.Task);
        }
Example #3
0
 // Populate the md entry actions handle.
 public async Task InsertEntriesAsync(NativeHandle entryActionsH, Dictionary <string, object> data)
 {
     foreach (var pair in data)
     {
         await Session.MDataEntryActions.InsertAsync(entryActionsH, pair.Key.ToUtfBytes(), pair.Value.Json().ToUtfBytes());
     }
 }
Example #4
0
        private void btnImpersonate_Click(object sender, EventArgs e)
        {
            TokenImpersonationLevel implevel = TokenImpersonationLevel.Impersonation;

            try
            {
                if (_token.GetTokenType() == TokenType.Impersonation)
                {
                    implevel = _token.GetImpersonationLevel();
                }

                using (UserToken token = _token.DuplicateToken(TokenType.Impersonation, implevel, (TokenLibrary.TokenIntegrityLevel)comboBoxILForDup.SelectedItem))
                {
                    NativeHandle imptoken = null;
                    using (ImpersonateProcess imp = token.Impersonate())
                    {
                        imptoken = NativeBridge.OpenThreadToken();
                    }
                    if (imptoken != null)
                    {
                        OpenForm(new UserToken(imptoken), false);
                    }
                    else
                    {
                        MessageBox.Show(this, "Couldn't open thread token", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #5
0
            void Accept(RemoteConnection connection)
            {
                var          ch     = (TcpServerChannel)this.channel;
                NativeHandle client = connection.Client;

                if (connection.Error != null)
                {
                    Logger.Warn("Client connection failed.", connection.Error);
                    try
                    {
                        client?.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Logger.Warn("Failed to dispose a client connection.", ex);
                    }

                    return;
                }

                if (client == null)
                {
                    return;
                }

                if (ch.EventLoop is DispatcherEventLoop dispatcher)
                {
                    dispatcher.Dispatch(client);
                }
                else
                {
                    this.Accept((Tcp)client);
                }
            }
Example #6
0
        /// <summary>
        /// Set the velocity of this <see cref="PhysicsObject"/>.
        /// </summary>
        /// <param name="velocity"></param>
        public void SetVelocity(Vector3 velocity)
        {
            var action = new pe_action_set_velocity();

            action.v = velocity;
            NativeHandle.Action(action);
        }
        public static Task <List <(List <byte>, List <byte>, ulong)> > ForEachAsync(NativeHandle entH)
        {
            var tcs     = new TaskCompletionSource <List <(List <byte>, List <byte>, ulong)> >();
            var entries = new List <(List <byte>, List <byte>, ulong)>();

            MDataEntriesForEachCb forEachCb = (_, entryKeyPtr, entryKeyLen, entryValPtr, entryValLen, entryVersion) => {
                var entryKey = entryKeyPtr.ToList <byte>(entryKeyLen);
                var entryVal = entryValPtr.ToList <byte>(entryValLen);
                entries.Add((entryKey, entryVal, entryVersion));
            };

            ListBasedResultCb forEachResCb = (_, result) => {
                if (result.ErrorCode != 0)
                {
                    tcs.SetException(result.ToException());
                    return;
                }

                tcs.SetResult(entries);
            };

            AppBindings.MDataEntriesForEach(Session.AppPtr, entH, forEachCb, forEachResCb);

            return(tcs.Task);
        }
Example #8
0
        private static string FormatText(HandleEntry ent)
        {
            NativeHandle h = NativeBridge.DuplicateHandleFromProcess(ent.ProcessId, ent.Handle, 0, DuplicateHandleOptions.DuplicateSameAccess);

            try
            {
                StringBuilder builder = new StringBuilder();

                if ((ent.GrantedAccess & (int)HandleUtils.AccessRights.SectionMapRead) != 0)
                {
                    builder.Append("R");
                }

                if ((ent.GrantedAccess & (int)HandleUtils.AccessRights.SectionMapWrite) != 0)
                {
                    builder.Append("W");
                }

                return(String.Format("[{0}/0x{0:X}] {1} Size: {2} Access: {3}", ent.Handle.ToInt64(), ent.ObjectName, NativeBridge.GetSectionSize(h), builder.ToString()));
            }
            finally
            {
                h.Close();
            }
        }
 public TokenEntry(NativeHandle handle)
 {
     Handle                   = handle;
     SecurityDescriptor       = NativeBridge.GetSecurityDescriptorForHandle(handle);
     StringSecurityDescriptor = NativeBridge.GetStringSecurityDescriptor(SecurityDescriptor);
     UserName                 = NativeBridge.GetUserNameForToken(handle);
 }
Example #10
0
        public GLXWindow(NativeHandle displayHandle, NativeHandle windowHandle)
        {
            DisplayHandle = displayHandle;
            WindowHandle  = windowHandle;

            _swapInterval = 1;
        }
Example #11
0
        //调起支付
        private bool UpPayClick(int id, object obj)
        {
            NativeHandle handle = new NativeHandle();

            if (type == payType.alipay)
            {
                object payData = PayOrderInterfaceMgr.Instance.GetDatas(LoginModel.Instance.Uid, Urltype.alipay, PayOrderInterfaceMgr.Instance.payfor, GetPayCount());
                if (payData != null)
                {
                    handle.Alipay(payData.ToString());

                    type = payType.none;
                }
            }
            else if (type == payType.wechat)
            {
                object o = PayOrderInterfaceMgr.Instance.GetDatas(LoginModel.Instance.Uid, Urltype.wx, PayOrderInterfaceMgr.Instance.payfor, GetPayCount());
                if (o != null)
                {
                    PayData payData = o as PayData;
                    handle.WechatPay(payData.appid, payData.partnerid, payData.prepayid, payData.noncestr, payData.timestamp, payData.package, payData.sign);
                    type = payType.none;
                }
            }
            else
            {
                SystemMsgView.SystemFunction(Function.Tip, Info.Chooseone);
            }
            return(false);
        }
Example #12
0
        /// <summary>
        /// Adds and executes a physics action of type T.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="setParams">Sets the parameters of the action to be performed.</param>
        public void Action <T>(Action <T> setParams) where T : pe_action
        {
            var actionParams = Activator.CreateInstance <T>();

            setParams(actionParams);
            NativeHandle.Action(actionParams);
        }
            public ProcessEntry(NativeHandle handle)
            {
                Handle  = handle;
                Pid     = NativeBridge.GetPidForProcess(handle);
                Threads = NativeBridge.GetThreadsForProcess(handle).Select(h => new ThreadEntry(h)).ToArray();
                Array.Sort(Threads, (a, b) => a.Tid - b.Tid);

                SecurityDescriptor       = NativeBridge.GetSecurityDescriptorForHandle(handle);
                StringSecurityDescriptor = NativeBridge.GetStringSecurityDescriptor(SecurityDescriptor);

                ImagePath = String.Empty;
                if (Pid == 0)
                {
                    Name = "Idle";
                }
                else if (Pid == 4)
                {
                    Name = "System";
                }
                else
                {
                    ImagePath = NativeBridge.GetProcessPath(handle);
                    Name      = Path.GetFileNameWithoutExtension(ImagePath);
                }

                NativeHandle token = NativeBridge.OpenProcessToken(handle);

                if (token != null)
                {
                    Token = new TokenEntry(token);
                }
            }
Example #14
0
        static void Main(string[] args)
        {
            bool show_help       = false;
            uint standard_filter = 0;

            int pid = Process.GetCurrentProcess().Id;

            try
            {
                OptionSet opts = new OptionSet()
                {
                    { "r", "Recursive tree directory listing",
                      v => _recursive = v != null },
                    { "sddl", "Print full SDDL security descriptors", v => _print_sddl = v != null },
                    { "p|pid=", "Specify a PID of a process to impersonate when checking", v => pid = int.Parse(v.Trim()) },
                    { "w", "Show only write permissions granted", v => _show_write_only = v != null },
                    { "f=", String.Format("Filter on a specific file right [{0}]",
                                          String.Join(",", Enum.GetNames(typeof(FileAccessRights)))), v => _file_filter |= ParseRight(v, typeof(FileAccessRights)) },
                    { "d=", String.Format("Filter on a specific directory right [{0}]",
                                          String.Join(",", Enum.GetNames(typeof(FileDirectoryAccessRights)))), v => _dir_filter |= ParseRight(v, typeof(FileDirectoryAccessRights)) },
                    { "s=", String.Format("Filter on a standard right [{0}]",
                                          String.Join(",", Enum.GetNames(typeof(StandardAccessRights)))), v => standard_filter |= ParseRight(v, typeof(StandardAccessRights)) },
                    { "x=", "Specify a base path to exclude from recursive search", v => _walked.Add(v.ToLower()) },
                    { "q", "Don't print errors", v => _quiet = v != null },
                    { "onlydirs", "Only check the permissions of directories", v => _only_dirs = v != null },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                };

                List <string> paths = opts.Parse(args);

                if (show_help || (paths.Count == 0))
                {
                    ShowHelp(opts);
                }
                else
                {
                    _type  = ObjectTypeInfo.GetTypeByName("file");
                    _token = NativeBridge.OpenProcessToken(pid);

                    _file_filter |= standard_filter;
                    _dir_filter  |= standard_filter;

                    foreach (string path in paths)
                    {
                        if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory)
                        {
                            DumpDirectory(new DirectoryInfo(path));
                        }
                        else
                        {
                            DumpFile(new FileInfo(path));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #15
0
        public Task RegisterAsync(IChannel channel)
        {
            var nativeChannel = channel as INativeChannel;

            if (nativeChannel is null)
            {
                ThrowHelper.ThrowArgumentException_RegChannel();
            }

            // The handle loop must be the same as the loop of the
            // handle was created from.
            NativeHandle handle     = nativeChannel.GetHandle();
            IntPtr       loopHandle = handle.LoopHandle();

            for (int i = 0; i < _eventLoops.Length; i++)
            {
                var eventLoop = _eventLoops[i];
                if (eventLoop.UnsafeLoop.Handle == loopHandle)
                {
                    return(eventLoop.RegisterAsync(nativeChannel));
                }
            }

            return(ThrowHelper.ThrowInvalidOperationException(loopHandle));
        }
Example #16
0
        /// <summary>
        /// Adds an impulse to this <see cref="PhysicsObject"/>.
        /// </summary>
        /// <param name="impulse">Direction and length of the impulse.</param>
        public void AddImpulse(Vector3 impulse)
        {
            var action = new pe_action_impulse();

            action.impulse = impulse;
            NativeHandle.Action(action);
        }
        public static MailslotHandle Create(
            FileAccess access,
            string fileName,
            ObjectFlags objectFlags,
            NativeHandle rootDirectory,
            int quota,
            int maxMessageSize,
            long readTimeout,
            FileCreateOptions createOptions
            )
        {
            ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
            IoStatusBlock isb;
            IntPtr handle;

            try
            {
                Win32.NtCreateMailslotFile(
                    out handle,
                    access,
                    ref oa,
                    out isb,
                    createOptions,
                    quota,
                    maxMessageSize,
                    ref readTimeout
                    ).ThrowIf();
            }
            finally
            {
                oa.Dispose();
            }

            return new MailslotHandle(handle, true);
        }
Example #18
0
 public int FindChild(ParticleEffect pEffect)
 {
     if (pEffect == null)
     {
         return(-1);
     }
     return(NativeHandle.FindChild(pEffect.NativeHandle));
 }
Example #19
0
        public ParticleEmitter Spawn(Vector3 position)
        {
            var nativeLoc = new ParticleLoc(position);

            var nativeEmitter = NativeHandle.Spawn(nativeLoc);

            return(nativeEmitter == null ? null : new ParticleEmitter(nativeEmitter));
        }
Example #20
0
        /// <summary>
        /// Adds an impulse to this <see cref="PhysicsObject"/>. The impulse will be applied to the point in world-space.
        /// </summary>
        /// <param name="impulse">Direction and length of the impulse.</param>
        /// <param name="point">Point of application, in world-space.</param>
        public void AddImpulse(Vector3 impulse, Vector3 point)
        {
            var action = new pe_action_impulse();

            action.impulse = impulse;
            action.point   = point;
            NativeHandle.Action(action);
        }
Example #21
0
        /// <summary>
        /// Attaches a particle emitter object to a specific entity slot and loads it with <paramref name="particleEffect"/>.
        /// </summary>
        /// <param name="slot">The slot to load the particle in.</param>
        /// <param name="particleEffect">Particle effect to load.</param>
        /// <param name="scale">Scale of the emitter.</param>
        public void LoadParticleEmitter(int slot, ParticleEffect particleEffect, float scale = 1.0f)
        {
            var sp = new SpawnParams {
                fSizeScale = scale
            };

            NativeHandle.LoadParticleEmitter(slot, particleEffect.NativeHandle, sp, false, false);
        }
Example #22
0
        /// <summary>
        /// </summary>
        /// <param name="permissionsHandle"></param>
        /// <param name="dataEntries"></param>
        /// <returns>A serialised MdInfo</returns>
        public async Task <MDataInfo> CreateRandomPrivateMd(NativeHandle permissionsHandle, NativeHandle dataEntries, ulong protocol)
        {
            var mdInfo = await Session.MDataInfoActions.RandomPrivateAsync(protocol);

            await Session.MData.PutAsync(mdInfo, permissionsHandle, dataEntries); // <----------------------------------------------    Commit ------------------------

            return(mdInfo);
        }
Example #23
0
        /// <summary>
        /// Adds an angled impulse to this <see cref="PhysicsObject"/>.
        /// </summary>
        /// <param name="impulse">Angle and length of the impulse.</param>
        public void AddAngImpulse(Vector3 impulse)
        {
            var action = new pe_action_impulse
            {
                angImpulse = impulse
            };

            NativeHandle.Action(action);
        }
Example #24
0
 public void InsertChild(int slot, ParticleEffect pEffect)
 {
     if (pEffect == null)
     {
         Log.Error <ParticleEffect>("Tried to insert null into slot {0}!", slot);
         return;
     }
     NativeHandle.InsertChild(slot, pEffect.NativeHandle);
 }
        static void Main(string[] args)
        {
            bool show_help = false;

            int pid = Process.GetCurrentProcess().Id;

            try
            {
                OptionSet opts = new OptionSet()
                {
                    { "r", "Recursive tree directory listing",
                      v => _recursive = v != null },
                    { "sddl", "Print full SDDL security descriptors", v => _print_sddl = v != null },
                    { "p|pid=", "Specify a PID of a process to impersonate when checking", v => pid = int.Parse(v.Trim()) },
                    { "w", "Show only write permissions granted", v => _show_write_only = v != null },
                    { "k=", String.Format("Filter on a specific key right [{0}]",
                                          String.Join(",", Enum.GetNames(typeof(KeyAccessRights)))), v => _key_rights |= ParseRight(v, typeof(KeyAccessRights)) },
                    { "s=", String.Format("Filter on a standard right [{0}]",
                                          String.Join(",", Enum.GetNames(typeof(StandardAccessRights)))), v => _key_rights |= ParseRight(v, typeof(StandardAccessRights)) },
                    { "x=", "Specify a base path to exclude from recursive search", v => _walked.Add(v.ToLower()) },
                    { "h|help", "show this message and exit", v => show_help = v != null },
                };

                List <string> paths = opts.Parse(args);

                if (show_help || (paths.Count == 0))
                {
                    ShowHelp(opts);
                }
                else
                {
                    _type  = ObjectTypeInfo.GetTypeByName("key");
                    _token = NativeBridge.OpenProcessToken(pid);

                    foreach (string path in paths)
                    {
                        RegistryKey key = OpenKey(path);

                        if (key != null)
                        {
                            try
                            {
                                DumpKey(key);
                            }
                            finally
                            {
                                key.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Example #26
0
        private void ReleaseUnmanagedResources()
        {
            if (!NativeHandle.IsNull())
            {
                NativeMethods.FreeLibrary(NativeHandle);

                NativeHandle = IntPtr.Zero;
            }
        }
Example #27
0
        public void LoadMaterial(string path)
        {
            var material = Global.gEnv.p3DEngine.GetMaterialManager().LoadMaterial(path);

            if (material != null)
            {
                NativeHandle.SetMaterial(material);
            }
        }
Example #28
0
        /// <summary>
        /// Get the status of the <see cref="PhysicsEntity"/>.
        /// The type of status can be specified by choosing from for example <see cref="DynamicsStatus"/>, <see cref="LivingStatus"/>, or <see cref="VehicleStatus"/>.
        /// </summary>
        /// <typeparam name="T">The type of the <see cref="BasePhysicsStatus"/> to be retrieved, for example <see cref="DynamicsStatus"/></typeparam>
        /// <returns></returns>
        public T GetStatus <T>() where T : BasePhysicsStatus, new()
        {
            var status       = new T();
            var nativeStatus = status.ToBaseNativeStatus();

            NativeHandle.GetStatus(nativeStatus);
            status.NativeToManaged(nativeStatus);
            return(status);
        }
Example #29
0
        /// <summary>
        /// Method to get the character at the specified slot.
        /// </summary>
        /// <param name="slot">The index of the character slot.</param>
        /// <returns>The CharacterInstance or null if character with this slot does not exist.</returns>
        public Character GetCharacter(int slot)
        {
            var nativeCharacter = NativeHandle.GetCharacter(slot);

            if (nativeCharacter == null)
            {
                return(null);
            }
            return(new Character(nativeCharacter));
        }
Example #30
0
        /// <summary>
        /// Move this <see cref="PhysicsObject"/> in a direction, but apply the velocity instantly.
        /// </summary>
        /// <param name="direction"></param>
        public void Jump(Vector3 direction)
        {
            var action = new pe_action_move();

            //Jump mode 1 - instant velocity change
            action.iJump = 1;
            action.dir   = direction;

            NativeHandle.Action(action);
        }
Example #31
0
        /// <summary>
        /// Move this <see cref="PhysicsObject"/> in a direction.
        /// </summary>
        /// <param name="direction"></param>
        public void Move(Vector3 direction)
        {
            var action = new pe_action_move();

            //Jump mode 2 - just adds to current velocity
            action.iJump = 2;
            action.dir   = direction;

            NativeHandle.Action(action);
        }
Example #32
0
        public static NamedPipeHandle Create(
            FileAccess access,
            string fileName,
            ObjectFlags objectFlags,
            NativeHandle rootDirectory,
            FileShareMode shareMode,
            FileCreationDisposition creationDisposition,
            FileCreateOptions createOptions,
            PipeType type,
            PipeType readMode,
            PipeCompletionMode completionMode,
            int maximumInstances,
            int inboundQuota,
            int outboundQuota,
            long defaultTimeout
            )
        {
            NtStatus status;
            ObjectAttributes oa = new ObjectAttributes(fileName, objectFlags, rootDirectory);
            IoStatusBlock isb;
            IntPtr handle;

            // If a timeout wasn't specified, use a default value.
            if (defaultTimeout == 0)
                defaultTimeout = -50 * Win32.TimeMsTo100Ns; // 50 milliseconds

            try
            {
                if ((status = Win32.NtCreateNamedPipeFile(
                    out handle,
                    access,
                    ref oa,
                    out isb,
                    shareMode,
                    creationDisposition,
                    createOptions,
                    type,
                    readMode,
                    completionMode,
                    maximumInstances,
                    inboundQuota,
                    outboundQuota,
                    ref defaultTimeout
                    )) >= NtStatus.Error)
                    Win32.Throw(status);
            }
            finally
            {
                oa.Dispose();
            }

            return new NamedPipeHandle(handle, true);
        }
Example #33
0
        public static NativeHandle OpenObject(int access, string name, ObjectFlags objectFlags, NativeHandle rootDirectory)
        {
            ObjectAttributes oa = new ObjectAttributes(name, objectFlags, rootDirectory);

            try
            {
                return new NativeHandle(KProcessHacker.Instance.KphOpenNamedObject(access, oa).ToIntPtr(), true);
            }
            finally
            {
                oa.Dispose();
            }
        }
Example #34
0
        public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle, ProcessHandle process, bool getName)
        {
            IntPtr handle = new IntPtr(thisHandle.Handle);
            IntPtr objectHandleI;
            int retLength = 0;
            GenericHandle objectHandle = null;

            if (thisHandle.Handle == 0 || thisHandle.Handle == -1 || thisHandle.Handle == -2)
                throw new WindowsException(NtStatus.InvalidHandle);

            if (KProcessHacker.Instance == null)
            {
                NtStatus status;

                if ((status = Win32.NtDuplicateObject(
                    process, handle, ProcessHandle.Current, out objectHandleI, 0, 0, 0)) >= NtStatus.Error)
                    Win32.ThrowLastError(status);

                objectHandle = new GenericHandle(objectHandleI);
            }

            ObjectInformation info = new ObjectInformation();

            lock (Windows.ObjectTypes)
            {
                if (Windows.ObjectTypes.ContainsKey(thisHandle.ObjectTypeNumber))
                {
                    info.TypeName = Windows.ObjectTypes[thisHandle.ObjectTypeNumber];
                }
                else
                {
                    int baseAddress = 0;

                    if (KProcessHacker.Instance != null)
                    {
                        KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
                            IntPtr.Zero, 0, out retLength, out baseAddress);
                    }
                    else
                    {
                        Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
                            IntPtr.Zero, 0, out retLength);
                    }

                    if (retLength > 0)
                    {
                        using (MemoryAlloc otiMem = new MemoryAlloc(retLength))
                        {
                            if (KProcessHacker.Instance != null)
                            {
                                if (KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
                                    otiMem, otiMem.Size, out retLength, out baseAddress) >= NtStatus.Error)
                                    throw new Exception("ZwQueryObject failed.");
                            }
                            else
                            {
                                if (Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
                                    otiMem, otiMem.Size, out retLength) >= NtStatus.Error)
                                    throw new Exception("NtQueryObject failed.");
                            }

                            var oti = otiMem.ReadStruct<ObjectTypeInformation>();
                            var str = oti.Name;

                            if (KProcessHacker.Instance != null)
                                str.Buffer = str.Buffer.Increment(otiMem.Memory.Decrement(baseAddress));

                            info.TypeName = str.Read();
                            Windows.ObjectTypes.Add(thisHandle.ObjectTypeNumber, info.TypeName);
                        }
                    }
                }
            }

            if (!getName)
                return info;

            if (info.TypeName == "File")
            {
                if (KProcessHacker.Instance != null)
                {

                    info.OrigName = KProcessHacker.Instance.GetHandleObjectName(process, handle);
                }
                else
                {

                    int hackLevel = 1;

                    if (OSVersion.IsBelowOrEqual(WindowsVersion.XP))
                        hackLevel = 2;

                    if (hackLevel == 1)
                    {
                        try
                        {

                            using (MemoryAlloc oniMem = new MemoryAlloc(0x4000))
                            {
                                if (NProcessHacker.PhQueryNameFileObject(
                                    objectHandle, oniMem, oniMem.Size, out retLength) >= NtStatus.Error)
                                    throw new Exception("PhQueryNameFileObject failed.");

                                var oni = oniMem.ReadStruct<ObjectNameInformation>();

                                info.OrigName = oni.Name.Read();
                            }
                        }
                        catch (DllNotFoundException)
                        {
                            hackLevel = 2;
                        }
                    }

                    if (hackLevel == 0)
                    {
                        info.OrigName = GetObjectNameNt(process, handle, objectHandle);
                    }
                    else if (hackLevel == 2)
                    {

                        if ((int)thisHandle.GrantedAccess != 0x0012019f)
                            info.OrigName = GetObjectNameNt(process, handle, objectHandle);
                    }
                }
            }
            else
            {

                info.OrigName = GetObjectNameNt(process, handle, objectHandle);
            }

            try
            {
                switch (info.TypeName)
                {
                    case "File":

                        if (!string.IsNullOrEmpty(info.OrigName))
                            info.BestName = FileUtils.GetFileName(info.OrigName);

                        break;

                    case "Key":
                        info.BestName = NativeUtils.FormatNativeKeyName(info.OrigName);

                        break;

                    case "Process":
                        {
                            int processId;

                            if (KProcessHacker.Instance != null)
                            {
                                processId = KProcessHacker.Instance.KphGetProcessId(process, handle);

                                if (processId == 0)
                                    throw new Exception("Invalid PID");
                            }
                            else
                            {
                                using (var processHandle =
                                    new NativeHandle<ProcessAccess>(process, handle, OSVersion.MinProcessQueryInfoAccess))
                                {
                                    if ((processId = Win32.GetProcessId(processHandle)) == 0)
                                        Win32.ThrowLastError();
                                }
                            }

                            info.BestName = (new ClientId(processId, 0)).GetName(false);
                        }

                        break;

                    case "Thread":
                        {
                            int processId;
                            int threadId;

                            if (KProcessHacker.Instance != null)
                            {
                                threadId = KProcessHacker.Instance.KphGetThreadId(process, handle, out processId);

                                if (threadId == 0 || processId == 0)
                                    throw new Exception("Invalid TID or PID");
                            }
                            else
                            {
                                using (var threadHandle =
                                    new NativeHandle<ThreadAccess>(process, handle, OSVersion.MinThreadQueryInfoAccess))
                                {
                                    var basicInfo = ThreadHandle.FromHandle(threadHandle).GetBasicInformation();

                                    threadId = basicInfo.ClientId.ThreadId;
                                    processId = basicInfo.ClientId.ProcessId;
                                }
                            }

                            info.BestName = (new ClientId(processId, threadId)).GetName(true);
                        }

                        break;

                    case "TmEn":
                        {
                            using (var enHandleDup =
                                new NativeHandle<EnlistmentAccess>(process, handle, EnlistmentAccess.QueryInformation))
                            {
                                var enHandle = EnlistmentHandle.FromHandle(enHandleDup);

                                info.BestName = enHandle.GetBasicInformation().EnlistmentId.ToString("B");
                            }
                        }
                        break;

                    case "TmRm":
                        {
                            using (var rmHandleDup =
                                new NativeHandle<ResourceManagerAccess>(process, handle, ResourceManagerAccess.QueryInformation))
                            {
                                var rmHandle = ResourceManagerHandle.FromHandle(rmHandleDup);

                                info.BestName = rmHandle.GetDescription();

                                if (string.IsNullOrEmpty(info.BestName))
                                    info.BestName = rmHandle.GetGuid().ToString("B");
                            }
                        }
                        break;

                    case "TmTm":
                        {
                            using (var tmHandleDup =
                                new NativeHandle<TmAccess>(process, handle, TmAccess.QueryInformation))
                            {
                                var tmHandle = TmHandle.FromHandle(tmHandleDup);

                                info.BestName = FileUtils.GetFileName(FileUtils.GetFileName(tmHandle.GetLogFileName()));

                                if (string.IsNullOrEmpty(info.BestName))
                                    info.BestName = tmHandle.GetBasicInformation().TmIdentity.ToString("B");
                            }
                        }
                        break;

                    case "TmTx":
                        {
                            using (var transactionHandleDup =
                                new NativeHandle<TransactionAccess>(process, handle, TransactionAccess.QueryInformation))
                            {
                                var transactionHandle = TransactionHandle.FromHandle(transactionHandleDup);

                                info.BestName = transactionHandle.GetDescription();

                                if (string.IsNullOrEmpty(info.BestName))
                                    info.BestName = transactionHandle.GetBasicInformation().TransactionId.ToString("B");
                            }
                        }
                        break;

                    case "Token":
                        {
                            using (var tokenHandleDup =
                                new NativeHandle<TokenAccess>(process, handle, TokenAccess.Query))
                            {
                                var tokenHandle = TokenHandle.FromHandle(tokenHandleDup);
                                var sid = tokenHandle.GetUser();

                                using (sid)
                                    info.BestName = sid.GetFullName(true) + ": 0x" +
                                        tokenHandle.GetStatistics().AuthenticationId.ToString();
                            }
                        }

                        break;

                    default:
                        if (info.OrigName != null &&
                            info.OrigName != "")
                        {
                            info.BestName = info.OrigName;
                        }
                        else
                        {
                            info.BestName = null;
                        }

                        break;
                }
            }
            catch
            {
                if (info.OrigName != null && info.OrigName != "")
                {
                    info.BestName = info.OrigName;
                }
                else
                {
                    info.BestName = null;
                }
            }

            if (objectHandle != null)
                objectHandle.Dispose();

            return info;
        }
 public MailslotHandle(
     string fileName,
     ObjectFlags objectFlags,
     NativeHandle rootDirectory,
     FileShareMode shareMode,
     FileCreateOptions openOptions,
     FileAccess access
     )
     : base(fileName, objectFlags, rootDirectory, shareMode, openOptions, access)
 { }
Example #36
0
        public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle, ProcessHandle process, bool getName)
        {
            IntPtr handle = new IntPtr(thisHandle.Handle);
            IntPtr objectHandleI;
            int retLength = 0;
            GenericHandle objectHandle = null;

            if (thisHandle.Handle == 0 || thisHandle.Handle == -1 || thisHandle.Handle == -2)
                throw new WindowsException(NtStatus.InvalidHandle);

            // Duplicate the handle if we're not using KPH
            if (KProcessHacker.Instance == null)
            {
                NtStatus status;

                if ((status = Win32.NtDuplicateObject(
                    process, handle, ProcessHandle.Current, out objectHandleI, 0, 0, 0)) >= NtStatus.Error)
                    Win32.Throw(status);

                objectHandle = new GenericHandle(objectHandleI);
            }

            ObjectInformation info = new ObjectInformation();

            // If the cache contains the object type's name, use it. Otherwise, query the type 
            // for its name.
            Windows.ObjectTypesLock.AcquireShared();

            try
            {
                if (Windows.ObjectTypes.ContainsKey(thisHandle.ObjectTypeNumber))
                {
                    info.TypeName = Windows.ObjectTypes[thisHandle.ObjectTypeNumber];
                }
            }
            finally
            {
                Windows.ObjectTypesLock.ReleaseShared();
            }

            if (info.TypeName == null)
            {
                int baseAddress = 0;

                if (KProcessHacker.Instance != null)
                {
                    KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
                        IntPtr.Zero, 0, out retLength, out baseAddress);
                }
                else
                {
                    Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
                        IntPtr.Zero, 0, out retLength);
                }

                if (retLength > 0)
                {
                    using (MemoryAlloc otiMem = new MemoryAlloc(retLength))
                    {
                        if (KProcessHacker.Instance != null)
                        {
                            if (KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
                                otiMem, otiMem.Size, out retLength, out baseAddress) >= NtStatus.Error)
                                throw new Exception("ZwQueryObject failed.");
                        }
                        else
                        {
                            if (Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
                                otiMem, otiMem.Size, out retLength) >= NtStatus.Error)
                                throw new Exception("NtQueryObject failed.");
                        }

                        var oti = otiMem.ReadStruct<ObjectTypeInformation>();
                        var str = oti.Name;

                        if (KProcessHacker.Instance != null)
                            str.Buffer = str.Buffer.Increment(otiMem.Memory.Decrement(baseAddress));

                        info.TypeName = str.Read();

                        Windows.ObjectTypesLock.AcquireExclusive();

                        try
                        {
                            if (!Windows.ObjectTypes.ContainsKey(thisHandle.ObjectTypeNumber))
                                Windows.ObjectTypes.Add(thisHandle.ObjectTypeNumber, info.TypeName);
                        }
                        finally
                        {
                            Windows.ObjectTypesLock.ReleaseExclusive();
                        }
                    }
                }
            }

            if (!getName)
                return info;

            // Get the object's name. If the object is a file we must take special 
            // precautions so that we don't hang.
            if (info.TypeName == "File")
            {
                if (KProcessHacker.Instance != null)
                {
                    // Use KProcessHacker for files to avoid hangs.
                    info.OrigName = KProcessHacker.Instance.GetHandleObjectName(process, handle);
                }
                else
                {
                    // 0: No hack, query the thing normally.
                    // 1: No hack, use NProcessHacker.
                    // 2: Hack.
                    int hackLevel = 1;

                    // If we already tried to use NPH but it wasn't present, 
                    // skip to level 2.
                    if (NphNotAvailable)
                        hackLevel = 2;

                    // Can't use NPH because XP had a bug where a thread hanging 
                    // on NtQueryObject couldn't be terminated.
                    if (OSVersion.IsBelowOrEqual(WindowsVersion.XP))
                        hackLevel = 2;

                    // On Windows 7 and above the hanging bug appears to have 
                    // been fixed. Query the object normally.
                    // UPDATE: Not so. It still happens.
                    //if (OSVersion.IsAboveOrEqual(WindowsVersion.Seven))
                    //    hackLevel = 0;

                    if (hackLevel == 1)
                    {
                        try
                        {
                            // Use NProcessHacker.
                            using (MemoryAlloc oniMem = new MemoryAlloc(0x4000))
                            {
                                if (NProcessHacker.PhQueryNameFileObject(
                                    objectHandle, oniMem, oniMem.Size, out retLength) >= NtStatus.Error)
                                    throw new Exception("PhQueryNameFileObject failed.");

                                var oni = oniMem.ReadStruct<ObjectNameInformation>();

                                info.OrigName = oni.Name.Read();
                            }
                        }
                        catch (DllNotFoundException)
                        {
                            hackLevel = 2;
                            NphNotAvailable = true;
                        }
                    }

                    if (hackLevel == 0)
                    {
                        info.OrigName = GetObjectNameNt(process, handle, objectHandle);
                    }
                    else if (hackLevel == 2)
                    {
                        // KProcessHacker and NProcessHacker not available. Fall back to using hack
                        // (i.e. not querying the name at all if the access is 0x0012019f).
                        if ((int)thisHandle.GrantedAccess != 0x0012019f)
                            info.OrigName = GetObjectNameNt(process, handle, objectHandle);
                    }
                }
            }
            else
            {
                // Not a file. Query the object normally.
                info.OrigName = GetObjectNameNt(process, handle, objectHandle);
            }

            // Get a better name for the handle.
            try
            {
                switch (info.TypeName)
                {
                    case "File":
                        // Resolves \Device\HarddiskVolume1 into C:, for example.
                        if (!string.IsNullOrEmpty(info.OrigName))
                            info.BestName = FileUtils.GetFileName(info.OrigName);

                        break;

                    case "Key":
                        info.BestName = NativeUtils.FormatNativeKeyName(info.OrigName);

                        break;

                    case "Process":
                        {
                            int processId;

                            if (KProcessHacker.Instance != null)
                            {
                                processId = KProcessHacker.Instance.KphGetProcessId(process, handle);

                                if (processId == 0)
                                    throw new Exception("Invalid PID");
                            }
                            else
                            {
                                using (var processHandle =
                                    new NativeHandle<ProcessAccess>(process, handle, OSVersion.MinProcessQueryInfoAccess))
                                {
                                    if ((processId = Win32.GetProcessId(processHandle)) == 0)
                                        Win32.Throw();
                                }
                            }

                            info.BestName = (new ClientId(processId, 0)).GetName(false);
                        }

                        break;

                    case "Thread":
                        {
                            int processId;
                            int threadId;

                            if (KProcessHacker.Instance != null)
                            {
                                threadId = KProcessHacker.Instance.KphGetThreadId(process, handle, out processId);

                                if (threadId == 0 || processId == 0)
                                    throw new Exception("Invalid TID or PID");
                            }
                            else
                            {
                                using (var threadHandle =
                                    new NativeHandle<ThreadAccess>(process, handle, OSVersion.MinThreadQueryInfoAccess))
                                {
                                    var basicInfo = ThreadHandle.FromHandle(threadHandle).GetBasicInformation();

                                    threadId = basicInfo.ClientId.ThreadId;
                                    processId = basicInfo.ClientId.ProcessId;
                                }
                            }

                            info.BestName = (new ClientId(processId, threadId)).GetName(true);
                        }

                        break;

                    case "TmEn":
                        {
                            using (var enHandleDup =
                                new NativeHandle<EnlistmentAccess>(process, handle, EnlistmentAccess.QueryInformation))
                            {
                                var enHandle = EnlistmentHandle.FromHandle(enHandleDup);

                                info.BestName = enHandle.GetBasicInformation().EnlistmentId.ToString("B");
                            }
                        }
                        break;

                    case "TmRm":
                        {
                            using (var rmHandleDup =
                                new NativeHandle<ResourceManagerAccess>(process, handle, ResourceManagerAccess.QueryInformation))
                            {
                                var rmHandle = ResourceManagerHandle.FromHandle(rmHandleDup);

                                info.BestName = rmHandle.GetDescription();

                                if (string.IsNullOrEmpty(info.BestName))
                                    info.BestName = rmHandle.GetGuid().ToString("B");
                            }
                        }
                        break;

                    case "TmTm":
                        {
                            using (var tmHandleDup =
                                new NativeHandle<TmAccess>(process, handle, TmAccess.QueryInformation))
                            {
                                var tmHandle = TmHandle.FromHandle(tmHandleDup);

                                info.BestName = FileUtils.GetFileName(FileUtils.GetFileName(tmHandle.GetLogFileName()));

                                if (string.IsNullOrEmpty(info.BestName))
                                    info.BestName = tmHandle.GetBasicInformation().TmIdentity.ToString("B");
                            }
                        }
                        break;

                    case "TmTx":
                        {
                            using (var transactionHandleDup =
                                new NativeHandle<TransactionAccess>(process, handle, TransactionAccess.QueryInformation))
                            {
                                var transactionHandle = TransactionHandle.FromHandle(transactionHandleDup);

                                info.BestName = transactionHandle.GetDescription();

                                if (string.IsNullOrEmpty(info.BestName))
                                    info.BestName = transactionHandle.GetBasicInformation().TransactionId.ToString("B");
                            }
                        }
                        break;

                    case "Token":
                        {
                            using (var tokenHandleDup =
                                new NativeHandle<TokenAccess>(process, handle, TokenAccess.Query))
                            {
                                var tokenHandle = TokenHandle.FromHandle(tokenHandleDup);
                                var sid = tokenHandle.GetUser();

                                using (sid)
                                    info.BestName = sid.GetFullName(true) + ": 0x" +
                                        tokenHandle.GetStatistics().AuthenticationId.ToString();
                            }
                        }

                        break;

                    default:
                        if (info.OrigName != null &&
                            info.OrigName != "")
                        {
                            info.BestName = info.OrigName;
                        }
                        else
                        {
                            info.BestName = null;
                        }

                        break;
                }
            }
            catch
            {
                if (info.OrigName != null && info.OrigName != "")
                {
                    info.BestName = info.OrigName;
                }
                else
                {
                    info.BestName = null;
                }
            }

            if (objectHandle != null)
                objectHandle.Dispose();

            return info;
        }
        private void ScanCsrHandles()
        {
            this.Cursor = Cursors.WaitCursor;
            listProcesses.BeginUpdate();
            listProcesses.Items.Clear();

            try
            {
                var processes = Windows.GetProcesses();
                int totalCount = 0;
                int hiddenCount = 0;
                int terminatedCount = 0;

                processes.Remove(0);

                List<int> foundPids = new List<int>();

                var csrProcesses = this.GetCsrProcesses();

                // Duplicate each process handle and check if they exist in the normal list.
                foreach (var csrhandle in csrProcesses)
                {
                    try
                    {
                        var handles = csrhandle.GetHandles();

                        foreach (var handle in handles)
                        {
                            int pid = 0;
                            bool isThread = false;

                            try
                            {
                                pid = KProcessHacker.Instance.KphGetProcessId(csrhandle, handle.Handle);

                                // HACK: Using exception for program flow!
                                if (pid == 0)
                                    throw new Exception();
                            }
                            catch
                            {
                                // Probably not a process handle.
                                // Try opening it as a thread.
                                try
                                {
                                    int tid = KProcessHacker.Instance.KphGetThreadId(csrhandle, handle.Handle, out pid);
                                    isThread = true;

                                    if (tid == 0)
                                        throw new Exception();
                                }
                                catch
                                {
                                    continue;
                                }
                            }

                            // Avoid duplicate PIDs.
                            if (foundPids.Contains(pid))
                                continue;

                            foundPids.Add(pid);

                            try
                            {
                                ProcessHandle phandle;

                                if (!isThread)
                                {
                                    var dupHandle =
                                        new NativeHandle<ProcessAccess>(csrhandle,
                                            handle.Handle,
                                            Program.MinProcessQueryRights);
                                    phandle = ProcessHandle.FromHandle(dupHandle);
                                }
                                else
                                {
                                    using (var dupHandle =
                                        new NativeHandle<ThreadAccess>(csrhandle,
                                            handle.Handle,
                                            Program.MinThreadQueryRights))
                                        phandle = ThreadHandle.FromHandle(dupHandle).
                                            GetProcess(Program.MinProcessQueryRights);
                                }

                                AddProcessItem(
                                    phandle,
                                    pid,
                                    ref totalCount, ref hiddenCount, ref terminatedCount,
                                    (pid_) => processes.ContainsKey(pid_)
                                    );
                                phandle.Dispose();
                            }
                            catch (WindowsException ex2)
                            {
                                AddErrorItem(ex2, pid, ref totalCount, ref hiddenCount, ref terminatedCount);
                            }
                        }
                    }
                    catch (WindowsException ex)
                    {
                        PhUtils.ShowException("Unable to get the CSR handle list", ex);
                        return;
                    }

                    csrhandle.Dispose();
                }

                labelCount.Text = totalCount.ToString() + " running processes (excl. kernel, idle, non-Windows), " +
                    hiddenCount.ToString() + " hidden, " + terminatedCount.ToString() + " terminated.";

                if (hiddenCount > 0)
                    labelCount.ForeColor = Color.Red;
                else
                    labelCount.ForeColor = SystemColors.WindowText;
            }
            finally
            {
                listProcesses.EndUpdate();
                this.Cursor = Cursors.Default;
            }
        }
 //-------------------------------------------------------------------------
 // Use this for initialization
 void Start()
 {
     m_Native = new NativeHandle();
     m_LogMessage = "";
 }
        private ProcessHandle OpenProcessCsr(int pid, ProcessAccess access)
        {
            var csrProcesses = this.GetCsrProcesses();

            foreach (var csrProcess in csrProcesses)
            {
                foreach (var handle in csrProcess.GetHandles())
                {
                    try
                    {
                        // Assume that the handle is a process handle.
                        int handlePid = KProcessHacker.Instance.KphGetProcessId(csrProcess, handle.Handle);

                        if (handlePid == pid)
                            return ProcessHandle.FromHandle(
                                new NativeHandle<ProcessAccess>(csrProcess, handle.Handle, access)
                                );
                        else if (handlePid == 0)
                            throw new Exception(); // HACK
                    }
                    catch
                    {
                        try
                        {
                            // Assume that the handle is a thread handle.
                            int handlePid;

                            int tid = KProcessHacker.Instance.KphGetThreadId(csrProcess, handle.Handle, out handlePid);

                            if (tid == 0)
                                throw new Exception();

                            if (handlePid == pid)
                            {
                                using (var dupHandle =
                                    new NativeHandle<ThreadAccess>(csrProcess, handle.Handle, Program.MinThreadQueryRights))
                                    return ThreadHandle.FromHandle(dupHandle).GetProcess(access);
                            }
                        }
                        catch
                        { }
                    }
                }

                csrProcess.Dispose();
            }

            throw new Exception("Could not find process (hidden from handle table).");
        }