コード例 #1
0
ファイル: ElevatedApplication.cs プロジェクト: vormz/win-app
 private static extern bool DuplicateTokenEx(
     Kernel32.SafeObjectHandle hExistingToken,
     Kernel32.ACCESS_MASK dwDesiredAccess,
     ref Kernel32.SECURITY_ATTRIBUTES lpTokenAttributes,
     Kernel32.SECURITY_IMPERSONATION_LEVEL impersonationLevel,
     TOKEN_TYPE tokenType,
     out Kernel32.SafeObjectHandle phNewToken);
コード例 #2
0
        public HidGuardianControlDevice()
        {
            _deviceHandle = Kernel32.CreateFile(DevicePath,
                                                Kernel32.ACCESS_MASK.GenericRight.GENERIC_READ | Kernel32.ACCESS_MASK.GenericRight.GENERIC_WRITE,
                                                Kernel32.FileShare.FILE_SHARE_READ | Kernel32.FileShare.FILE_SHARE_WRITE,
                                                IntPtr.Zero, Kernel32.CreationDisposition.OPEN_EXISTING,
                                                Kernel32.CreateFileFlags.FILE_ATTRIBUTE_NORMAL
                                                | Kernel32.CreateFileFlags.FILE_FLAG_NO_BUFFERING
                                                | Kernel32.CreateFileFlags.FILE_FLAG_WRITE_THROUGH
                                                | Kernel32.CreateFileFlags.FILE_FLAG_OVERLAPPED,
                                                Kernel32.SafeObjectHandle.Null
                                                );

            if (_deviceHandle.IsInvalid)
            {
                throw new ArgumentException($"Couldn't open device {DevicePath}");
            }

            var maxThreads            = (int)Config.Default.Core.HGCD.Performance.WorkerThreads;
            var completionPortThreads = (int)Config.Default.Core.HGCD.Performance.CompletionPortThreads;

            ThreadPool.SetMinThreads(maxThreads, completionPortThreads);

            Log.Information("Spawning {MaxThreads} threads", maxThreads);

            for (var i = 0; i < maxThreads; i++)
            {
                _invertedCallTasks.Add(
                    Task.Factory.StartNew(InvertedCallSupplierWorker, _invertedCallTokenSource.Token));
            }
        }
コード例 #3
0
        public static bool OverlappedDeviceIoControl(this Kernel32.SafeObjectHandle handle, uint ioControlCode,
                                                     IntPtr inBuffer, int inBufferSize, IntPtr outBuffer, int outBufferSize, out int bytesReturned)
        {
            var resetEvent = new ManualResetEvent(false);
            var overlapped = Marshal.AllocHGlobal(Marshal.SizeOf <NativeOverlapped>());

            Marshal.StructureToPtr(new NativeOverlapped {
                EventHandle = resetEvent.SafeWaitHandle.DangerousGetHandle()
            },
                                   overlapped, false);

            try
            {
                Kernel32.DeviceIoControl(
                    handle,
                    unchecked ((int)ioControlCode),
                    inBuffer, inBufferSize, outBuffer, outBufferSize,
                    out bytesReturned, overlapped);

                return(Kernel32.GetOverlappedResult(handle, overlapped, out bytesReturned, true));
            }
            finally
            {
                resetEvent.Dispose();
                Marshal.FreeHGlobal(overlapped);
            }
        }
コード例 #4
0
ファイル: BthPS3Device.cs プロジェクト: sulidev/Shibari
        protected BthPS3Device(string path, Kernel32.SafeObjectHandle handle, int index) : base(
                DualShockConnectionType.Bluetooth, handle, index)
        {
            DevicePath = path;

            _outputReportConsumerTask = _outputReportConsumerSchedule.Subscribe(OnConsumeOutputReport);
        }
コード例 #5
0
        public void StartSuspended()
        {
            var pi = new Kernel32.PROCESS_INFORMATION();
            var si = new Kernel32.STARTUPINFO()
            {
                hStdInput  = Kernel32.SafeObjectHandle.Null,
                hStdOutput = Kernel32.SafeObjectHandle.Null,
                hStdError  = Kernel32.SafeObjectHandle.Null
            };
            var processCreationFlags = Kernel32.CreateProcessFlags.CREATE_SUSPENDED |
                                       Kernel32.CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT;

            if (SpawnNewConsoleWindow)
            {
                processCreationFlags |= Kernel32.CreateProcessFlags.CREATE_NEW_CONSOLE;
            }

            if (!Kernel32.CreateProcess(null, new StringBuilder(string.Join(" ", args)).ToString(), IntPtr.Zero, IntPtr.Zero, false,
                                        processCreationFlags, IntPtr.Zero, null, ref si, out pi))
            {
                throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
            }

            hProcess = new Kernel32.SafeObjectHandle(pi.hProcess);
            pid      = pi.dwProcessId;
            hThread  = new Kernel32.SafeObjectHandle(pi.hThread);
        }
コード例 #6
0
        public unsafe Job()
        {
            _handle = Kernel32.CreateJobObject(null, null);

            var info = new Kernel32.JOBOBJECT_BASIC_LIMIT_INFORMATION
            {
                LimitFlags = Kernel32.JOB_OBJECT_LIMIT_FLAGS.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
            };

            var extendedInfo = new Kernel32.JOBOBJECT_EXTENDED_LIMIT_INFORMATION
            {
                BasicLimitInformation = info
            };

            var length          = Marshal.SizeOf(typeof(Kernel32.JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
            var extendedInfoPtr = Marshal.AllocHGlobal(length);

            Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

            if (!Kernel32.SetInformationJobObject(_handle, Kernel32.JOBOBJECTINFOCLASS.JobObjectExtendedLimitInformation,
                                                  extendedInfoPtr, (uint)length))
            {
                throw new Exception(
                          $"Unable to set information. Error: {Marshal.GetLastWin32Error()}");
            }
        }
コード例 #7
0
        public static bool OverlappedWriteFile(this Kernel32.SafeObjectHandle handle,
                                               IntPtr buffer, int bufferSize, out int bytesReturned)
        {
            var resetEvent = new ManualResetEvent(false);
            var overlapped = Marshal.AllocHGlobal(Marshal.SizeOf <NativeOverlapped>());

            Marshal.StructureToPtr(new NativeOverlapped {
                EventHandle = resetEvent.SafeWaitHandle.DangerousGetHandle()
            },
                                   overlapped, false);

            try
            {
                int?bytesRead = 0;

                Kernel32.WriteFile(
                    handle,
                    buffer,
                    bufferSize,
                    ref bytesRead,
                    overlapped);

                return(Kernel32.GetOverlappedResult(handle, overlapped, out bytesReturned, true));
            }
            finally
            {
                resetEvent.Dispose();
                Marshal.FreeHGlobal(overlapped);
            }
        }
コード例 #8
0
        private FireShockDevice(string path, Kernel32.SafeObjectHandle handle, int index) : base(
                DualShockConnectionType.USB, handle, index)
        {
            DevicePath = path;

            var length = Marshal.SizeOf(typeof(FireshockGetDeviceBdAddr));
            var pData  = Marshal.AllocHGlobal(length);

            try
            {
                var ret = DeviceHandle.OverlappedDeviceIoControl(
                    IoctlFireshockGetDeviceBdAddr,
                    IntPtr.Zero, 0, pData, length,
                    out _);

                if (!ret)
                {
                    throw new FireShockGetDeviceBdAddrFailedException(
                              $"Failed to request address of device {path}",
                              new Win32Exception(Marshal.GetLastWin32Error()));
                }

                var resp = Marshal.PtrToStructure <FireshockGetDeviceBdAddr>(pData);

                ClientAddress = new PhysicalAddress(resp.Device.Address);
            }
            finally
            {
                Marshal.FreeHGlobal(pData);
            }

            length = Marshal.SizeOf(typeof(FireshockGetHostBdAddr));
            pData  = Marshal.AllocHGlobal(length);

            try
            {
                var ret = DeviceHandle.OverlappedDeviceIoControl(
                    IoctlFireshockGetHostBdAddr,
                    IntPtr.Zero, 0, pData, length,
                    out _);

                if (!ret)
                {
                    throw new FireShockGetHostBdAddrFailedException(
                              $"Failed to request host address for device {ClientAddress}",
                              new Win32Exception(Marshal.GetLastWin32Error()));
                }

                var resp = Marshal.PtrToStructure <FireshockGetHostBdAddr>(pData);

                HostAddress = new PhysicalAddress(resp.Host.Address);
            }
            finally
            {
                Marshal.FreeHGlobal(pData);
            }
        }
コード例 #9
0
            public NavigationDevice(string path, Kernel32.SafeObjectHandle handle, int index) : base(path, handle,
                                                                                                     index)
            {
                Marshal.WriteByte(OutputReportBuffer, 11, 0x01);
                //Marshal.WriteByte(OutputReportBuffer, 12, 0x01);
                //Marshal.WriteByte(OutputReportBuffer, 13, 0x00);
                //Marshal.WriteByte(OutputReportBuffer, 14, 0x00);
                //Marshal.WriteByte(OutputReportBuffer, 15, 0x00);

                SendHidCommand(OutputReportBuffer, OutputReportBufferSize);
            }
コード例 #10
0
            public SixaxisDevice(string path, Kernel32.SafeObjectHandle handle, int index) : base(path, handle, index)
            {
                DeviceType = DualShockDeviceType.DualShock3;
                //
                // Remote MAC address is encoded in path as InstanceId
                // This is a lazy approach but saves an I/O request ;)
                //
                ClientAddress = PhysicalAddress.Parse(path.Substring(path.LastIndexOf('&') + 1, 12));

                //
                // Initialize default output report native buffer
                //
                FillMemory(OutputReportBuffer, OutputReportBufferSize, 0);
                Marshal.Copy(HidOutputReport, 0, OutputReportBuffer, HidOutputReport.Length);

                //
                // Crude way to assign device index as LED number
                //
                if (index >= 0 && index < 4)
                {
                    Marshal.WriteByte(OutputReportBuffer, 11, _ledOffsets[index]);
                }

                //
                // Send the start command to remote device
                //
                var unmanagedBuffer = Marshal.AllocHGlobal(_hidEnableCommand.Length);

                Marshal.Copy(_hidEnableCommand, 0, unmanagedBuffer, _hidEnableCommand.Length);

                try
                {
                    var ret = handle.OverlappedDeviceIoControl(
                        IOCTL_BTHPS3_HID_CONTROL_WRITE,
                        unmanagedBuffer,
                        _hidEnableCommand.Length,
                        IntPtr.Zero,
                        0,
                        out _
                        );

                    if (!ret)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(unmanagedBuffer);
                }

                SendHidCommand(OutputReportBuffer, OutputReportBufferSize);
            }
コード例 #11
0
            public FireShock3Device(string path, Kernel32.SafeObjectHandle handle, int index) : base(path, handle,
                                                                                                     index)
            {
                DeviceType = DualShockDeviceType.DualShock3;

                Log.Information("Device is {DeviceType} " +
                                "with address {ClientAddress} " +
                                "currently paired to {HostAddress}",
                                DeviceType, ClientAddress.AsFriendlyName(), HostAddress.AsFriendlyName());

                if (index >= 0 && index < 4)
                {
                    HidOutputReport[9] = _ledOffsets[index];
                }
            }
コード例 #12
0
ファイル: Device.cs プロジェクト: tlsnns/WindowsKernelBrowser
        Device(string strDeviceName)
        {
            SafeObjectHandle = Kernel32.CreateFile($@"\\.\{strDeviceName}",
                                                   Kernel32.ACCESS_MASK.GenericRight.GENERIC_READ | Kernel32.ACCESS_MASK.GenericRight.GENERIC_WRITE,
                                                   Kernel32.FileShare.FILE_SHARE_READ | Kernel32.FileShare.FILE_SHARE_WRITE,
                                                   Kernel32.SECURITY_ATTRIBUTES.Create(),
                                                   Kernel32.CreationDisposition.OPEN_EXISTING,
                                                   Kernel32.CreateFileFlags.FILE_ATTRIBUTE_NORMAL,
                                                   Kernel32.SafeObjectHandle.Null);

            if (SafeObjectHandle.IsInvalid)
            {
                var errorcode = Kernel32.GetLastError();
                throw new Win32Exception(errorcode, $"打开设备失败,win32错误码:{errorcode}");
            }
        }
コード例 #13
0
        public TerminalService()
        {
            _job = Kernel32.CreateJobObject(IntPtr.Zero, null);

            var limit = new Kernel32.JOBOBJECT_EXTENDED_LIMIT_INFORMATION();

            limit.BasicLimitInformation.LimitFlags = Kernel32.JOB_OBJECT_LIMIT_FLAGS.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
            unsafe
            {
                if (!Kernel32.SetInformationJobObject(_job, Kernel32.JOBOBJECTINFOCLASS.JobObjectExtendedLimitInformation, &limit, (uint)sizeof(Kernel32.JOBOBJECT_EXTENDED_LIMIT_INFORMATION)))
                {
                    Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
                }
            }

            _plinkFile = Path.GetTempFileName();
            File.SetAttributes(_plinkFile, File.GetAttributes(_plinkFile) | FileAttributes.Temporary);
            _plinkHandle = ExtractPlink();
        }
コード例 #14
0
ファイル: BluetoothHelper.cs プロジェクト: ViGEm/DsHidMini
        /// <summary>
        ///     Instruct host radio to disconnect a given remote device.
        /// </summary>
        /// <param name="device">The MAC address of the remote device.</param>
        public static void DisconnectRemoteDevice(PhysicalAddress device)
        {
            var radioParams = new BLUETOOTH_FIND_RADIO_PARAMS();

            radioParams.Init();

            var findHandle = BluetoothFindFirstRadio(ref radioParams, out var radioHandle);

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

            var payloadSize = Marshal.SizeOf <ulong>();
            var payload = Marshal.AllocHGlobal(payloadSize);
            var raw = new byte[] { 0x00, 0x00 }.Concat(device.GetAddressBytes()).Reverse().ToArray();
            var value = (long)BitConverter.ToUInt64(raw, 0);

            Marshal.WriteInt64(payload, value);

            try
            {
                using (var safeHandle = new Kernel32.SafeObjectHandle(radioHandle))
                {
                    Kernel32.DeviceIoControl(
                        safeHandle,
                        unchecked ((int)IOCTL_BTH_DISCONNECT_DEVICE),
                        payload,
                        payloadSize,
                        IntPtr.Zero,
                        0,
                        out _,
                        IntPtr.Zero
                        );
                }
            }
            finally
            {
                Marshal.FreeHGlobal(payload);
            }

            BluetoothFindRadioClose(findHandle);
        }
コード例 #15
0
        protected DualShockDevice(DualShockConnectionType connectionType, Kernel32.SafeObjectHandle handle, int index)
        {
            ConnectionType = connectionType;
            DeviceHandle   = handle;
            DeviceIndex    = index;

            OutputReportBuffer = Marshal.AllocHGlobal(OutputReportBufferSize);
            _outputReportTask  = _outputReportSchedule.Subscribe(OnOutputReportSafe);

            //
            // Start two tasks requesting input reports in parallel.
            //
            // While on threads request gets completed, another request can be
            // queued by the other thread. This way no input can get lost because
            // there's always at least one pending request in the driver to get
            // completed. Each thread uses inverted calls for maximum performance.
            //
            Task.Factory.StartNew(RequestInputReportWorker, _inputCancellationTokenSourcePrimary.Token);
            Task.Factory.StartNew(RequestInputReportWorker, _inputCancellationTokenSourceSecondary.Token);
        }
コード例 #16
0
        public bool AddProcess(IntPtr handle)
        {
            var processHandle = new Kernel32.SafeObjectHandle(handle, false);

            return(Kernel32.AssignProcessToJobObject(_handle, processHandle));
        }
コード例 #17
0
        public HidDevice(string path)
        {
            //device mutex
            lockObject = new object();

            //static buffers
            strBuffer = new StringBuilder(256);

            //open device
            //TODO why is 0x40000000 missing from FileAttribute in PInvoke?
            reference = Kernel32.CreateFile(path, Kernel32.ACCESS_MASK.GenericRight.GENERIC_WRITE, Kernel32.FileShare.FILE_SHARE_READ | Kernel32.FileShare.FILE_SHARE_WRITE, IntPtr.Zero, Kernel32.CreationDisposition.OPEN_EXISTING, Kernel32.CreateFileFlags.FILE_FLAG_OVERLAPPED, Kernel32.SafeObjectHandle.Null);

            if (reference.IsInvalid)
            {
                return;
            }

            //overlapped
            fileEvent      = new ManualResetEvent(false);
            fileOverlapped = new SafeOverlapped(fileEvent);

            //get preparsed data
            if (!Hid.HidD_GetPreparsedData(reference, out preparsedData))
            {
                return;
            }

            //transfer buffers
            capabilities  = Hid.HidP_GetCaps(preparsedData);
            inBuffer      = new byte[capabilities.InputReportByteLength];
            outBuffer     = new byte[capabilities.OutputReportByteLength];
            featureBuffer = new byte[capabilities.FeatureReportByteLength];

            //dynamic caps
            inputValueCaps   = new List <ValueCaps>();
            outputValueCaps  = new List <ValueCaps>();
            featureValueCaps = new List <ValueCaps>();

            ushort numInputCaps   = capabilities.NumberInputValueCaps;
            ushort numOutputCaps  = capabilities.NumberOutputValueCaps;
            ushort numFeatureCaps = capabilities.NumberFeatureValueCaps;

            ushort maxValueCaps = Math.Max(numInputCaps, numOutputCaps);

            maxValueCaps = Math.Max(maxValueCaps, numFeatureCaps);

            int    valueCapSize = Marshal.SizeOf <ValueCaps>();
            IntPtr valueCapPtr  = Marshal.AllocHGlobal(maxValueCaps * valueCapSize);

            HidPStatus stat = Hid.HidP_GetValueCaps(ReportType.Input, valueCapPtr, ref numInputCaps, preparsedData);

            for (int i = 0; i < numInputCaps; i++)
            {
                ValueCaps val = Marshal.PtrToStructure <ValueCaps>(new IntPtr(valueCapPtr.ToInt64() + (i * valueCapSize)));
                inputValueCaps.Add(val);
            }

            stat = Hid.HidP_GetValueCaps(ReportType.Output, valueCapPtr, ref numOutputCaps, preparsedData);

            for (int i = 0; i < numOutputCaps; i++)
            {
                ValueCaps val = Marshal.PtrToStructure <ValueCaps>(new IntPtr(valueCapPtr.ToInt64() + i * valueCapSize));
                outputValueCaps.Add(val);
            }

            stat = Hid.HidP_GetValueCaps(ReportType.Feature, valueCapPtr, ref numFeatureCaps, preparsedData);

            for (int i = 0; i < numFeatureCaps; i++)
            {
                ValueCaps val = Marshal.PtrToStructure <ValueCaps>(new IntPtr(valueCapPtr.ToInt64() + i * valueCapSize));
                featureValueCaps.Add(val);
            }

            Marshal.FreeHGlobal(valueCapPtr);
        }
コード例 #18
0
ファイル: ElevatedApplication.cs プロジェクト: vormz/win-app
 private static extern bool OpenProcessToken(
     IntPtr processHandle,
     Kernel32.ACCESS_MASK desiredAccess,
     out Kernel32.SafeObjectHandle tokenHandle);
コード例 #19
0
 public static extern bool GetProcessTimes(Kernel32.SafeObjectHandle handle, out long creation, out long exit, out long kernel, out long user);