Login Register






Useful Native Functions for VB.Net | Snippet filter_list
Author
Message
Useful Native Functions for VB.Net | Snippet #1
Yo.

As I've been working more and more on ven0m, I decided that instead of spamming pInvoke prototypes in every class I make, I should just start making a single class that I will reference across my projects. This class isn't entirely mine, lots of it is copy pasted from random places.

This may come in handy for anyone using native calls as this has a ton of the common ones, at least for me.

Code:
Public Class Native ' Native functions wrapped into single class Public Const NtCurrentProcess As Integer = -1 Public Const NtCurrentThread As Integer = -2 Public Const NT_SUCCESS As Long = &H0L Public Const STATUS_SUCCESS As Integer = 0 Public Const STATUS_FAILURE As Long = &H1L Public Const STATUS_PRIVILEGES_NOT_SET As Long = &H2L Public Const STATUS_INITUNISTRING_FAILURE As Long = &H3L Public Const SystemLoadAndCallImage As Integer = 38 Public Const STATUS_INFO_LENGTH_MISMATCH As Long = &HC0000004L Public Const PROCESS_PARAMETERS_NORMALIZED As Integer = 1 Public Shared ReadOnly INVALID_HANDLE_VALUE As New IntPtr(-1) Public Const STANDARD_RIGHTS_REQUIRED As Integer = &HF0000 Public Const SC_MANAGER_CONNECT As Integer = &H1 Public Const SC_MANAGER_CREATE_SERVICE As Integer = &H2 Public Const SC_MANAGER_ENUMERATE_SERVICE As Integer = &H4 Public Const SC_MANAGER_LOCK As Integer = &H8 Public Const SC_MANAGER_QUERY_LOCK_STATUS As Integer = &H10 Public Const SC_MANAGER_MODIFY_BOOT_CONFIG As Integer = &H20 Public Const SC_MANAGER_ALL_ACCESS As Integer = STANDARD_RIGHTS_REQUIRED Or SC_MANAGER_CONNECT Or SC_MANAGER_CREATE_SERVICE Or SC_MANAGER_ENUMERATE_SERVICE Or SC_MANAGER_LOCK Or SC_MANAGER_QUERY_LOCK_STATUS Or SC_MANAGER_MODIFY_BOOT_CONFIG Public Const SERVICE_QUERY_CONFIG As Integer = &H1 Public Const SERVICE_CHANGE_CONFIG As Integer = &H2 Public Const SERVICE_QUERY_STATUS As Integer = &H4 Public Const SERVICE_ENUMERATE_DEPENDENTS As Integer = &H8 Public Const SERVICE_START As Integer = &H10 Public Const SERVICE_STOP As Integer = &H20 Public Const SERVICE_RUNNING As Integer = &H4 Public Const SERVICE_PAUSED As Integer = &H7 Public Const SERVICE_STOPPED As Integer = &H1 Public Const SERVICE_START_PENDING As Integer = &H2 Public Const SERVICE_STOP_PENDING As Integer = &H3 Public Const SERVICE_PAUSE_PENDING As Integer = &H6 Public Const SERVICE_CONTINUE_PENDING As Integer = &H5 Public Const SERVICE_PAUSE_CONTINUE As Integer = &H40 Public Const SERVICE_INTERROGATE As Integer = &H80 Public Const SERVICE_USER_DEFINED_CONTROL As Integer = &H100 Public Const SERVICE_CONTROL_STOP As Integer = &H1 Public Const SERVICE_ALL_ACCESS As Integer = STANDARD_RIGHTS_REQUIRED Or SERVICE_QUERY_CONFIG Or SERVICE_CHANGE_CONFIG Or SERVICE_QUERY_STATUS Or SERVICE_ENUMERATE_DEPENDENTS Or SERVICE_START Or SERVICE_STOP Or SERVICE_PAUSE_CONTINUE Or SERVICE_INTERROGATE Or SERVICE_USER_DEFINED_CONTROL Public Const SERVICE_DEMAND_START As Integer = &H3 Public Const SERVICE_AUTO_START As Integer = &H2 Public Const SERVICE_KERNEL_DRIVER As Integer = &H1 Public Const SERVICE_WIN32_OWN_PROCESS As Integer = &H10 Public Const SERVICE_ERROR_NORMAL As Integer = &H1 Public Const SERVICE_ERROR_IGNORE As Integer = &H0 Public Const TH32CS_SNAPPROCESS As Integer = &H2 Public Const PROCESS_ALL_ACCESS As UInteger = &HF0000 Or &H100000 Or &HFFF Public Const MEM_COMMIT As Integer = &H1000 Public Const MEM_RESERVE As Integer = &H2000 Public Const PAGE_EXECUTE_READWRITE As Integer = &H40 Public Const ZWLOADMODE As Integer = 10 Public Const NTLOADMODE As Integer = 20 Public Const SMLOADMODE As Integer = 30 Public Const RTL_MODE As Integer = 555 Public Const CRT_MODE As Integer = 666 Public Const NT_MODE As Integer = 777 Public Const NO_PROC As Integer = 111 Public Const NO_DLLS As Integer = 112 Public Const MAIN_FUNCTIONS_FAILED As Integer = 113 Public Const ZW_SET_SYSTEM_INFO_FAILED As Integer = 114 Public Const FOR_NT_FUNCTIONS_FAILED As Integer = 115 Public Const FOR_SCM_FUNCTIONS_FAILED As Integer = 116 Public Const GENERIC_WRITE As Integer = &H40000000 Public Const CREATE_ALWAYS As Integer = 2 Public Const FILE_ATTRIBUTE_NORMAL As Integer = 128 Public Const GENERIC_READ As UInteger = &H80000000UI Public Const GENERIC_ALL As Integer = &H10000000 Public Const CREATE_NEW As Integer = 1 Public Const OPEN_EXISTING As Integer = 3 <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure CLIENT_ID Private UniqueProcess As Integer Private UniqueThread As Integer End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure UNICODE_STRING Public Length As UShort Public MaximumLength As UShort <MarshalAs(UnmanagedType.LPWStr)> Public Buffer As String End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure SYSTEM_LOAD_AND_CALL_IMAGE Public ModuleName As UNICODE_STRING End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure IO_STATUS_BLOCK Private Status As Long Private uInformation As ULong End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure CURDIR Private DosPath As UNICODE_STRING Private Handle As Integer End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure RTL_DRIVE_LETTER_CURDIR Private Flags As UShort Private Length As UShort Private TimeStamp As ULong Private DosPath As [String] End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure PROCESS_PARAMETERS Private MaximumLength As ULong Private Length As ULong Private Flags As ULong ' PROCESS_PARAMETERS_NORMALIZED Private DebugFlags As ULong Private ConsoleHandle As Integer Private ConsoleFlags As ULong Private StandardInput As Integer Private StandardOutput As Integer Private StandardError As Integer Private CurrentDirectory As CURDIR Private DllPath As UNICODE_STRING Private ImagePathName As UNICODE_STRING Private CommandLine As UNICODE_STRING Private Environment As [String] Private StartingX As ULong Private StartingY As ULong Private CountX As ULong Private CountY As ULong Private CountCharsX As ULong Private CountCharsY As ULong Private FillAttribute As ULong Private WindowFlags As ULong Private ShowWindowFlags As ULong Private WindowTitle As UNICODE_STRING Private Desktop As UNICODE_STRING Private ShellInfo As UNICODE_STRING Private RuntimeInfo As UNICODE_STRING Private CurrentDirectores As RTL_DRIVE_LETTER_CURDIR End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure SYSTEM_MODULE Private Reserved As ULong Private Base As ULong Private Size As ULong Private Flags As ULong Private Index As UShort Private Unknown As UShort Private LoadCount As UShort Private ModuleNameOffset As UShort Private ImageName As [String] End Structure <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure SYSTEM_MODULE_INFORMATION Private uCount As ULong Private aSM As SYSTEM_MODULE End Structure Public Enum SYSTEM_INFORMATION_CLASS SystemBasicInformation SystemProcessorInformation SystemPerformanceInformation SystemTimeOfDayInformation SystemPathInformation SystemProcessInformation SystemCallCountInformation SystemDeviceInformation SystemProcessorPerformanceInformation SystemFlagsInformation SystemCallTimeInformation SystemModuleInformation SystemLocksInformation SystemStackTraceInformation SystemPagedPoolInformation SystemNonPagedPoolInformation SystemHandleInformation SystemObjectInformation SystemPageFileInformation SystemVdmInstemulInformation SystemVdmBopInformation SystemFileCacheInformation SystemPoolTagInformation SystemInterruptInformation SystemDpcBehaviorInformation SystemFullMemoryInformation SystemLoadGdiDriverInformation SystemUnloadGdiDriverInformation SystemTimeAdjustmentInformation SystemSummaryMemoryInformation SystemNextEventIdInformation SystemEventIdsInformation SystemCrashDumpInformation SystemExceptionInformation SystemCrashDumpStateInformation SystemKernelDebuggerInformation SystemContextSwitchInformation SystemRegistryQuotaInformation SystemExtendServiceTableInformation SystemPrioritySeperation SystemPlugPlayBusInformation SystemDockInformation SystemPowerInformation SystemProcessorSpeedInformation SystemCurrentTimeZoneInformation SystemLookasideInformation End Enum <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> Public Structure OBJECT_ATTRIBUTES Private Length As ULong Private RootDirectory As Integer Private ObjectName As UNICODE_STRING Private Attributes As ULong Private SecurityDescriptor As IntPtr ' Points to type SECURITY_DESCRIPTOR Private SecurityQualityOfService As IntPtr ' Points to type SECURITY_QUALITY_OF_SERVICE End Structure Public Enum ADJUST_PRIVILEGE_TYPE AdjustCurrentProcess AdjustCurrentThread End Enum <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> Public Structure SERVICE_STATUS Public dwServiceType As Integer Public dwCurrentState As Integer Public dwControlsAccepted As Integer Public dwWin32ExitCode As Integer Public dwServiceSpecificExitCode As Integer Public dwCheckPoint As Integer Public dwWaitHint As Integer End Structure Public Enum FILE_INFO_BY_HANDLE_CLASS FileBasicInfo = 0 FileStandardInfo = 1 FileNameInfo = 2 FileRenameInfo = 3 FileDispositionInfo = 4 FileAllocationInfo = 5 FileEndOfFileInfo = 6 FileStreamInfo = 7 FileCompressionInfo = 8 FileAttributeTagInfo = 9 FileIdBothDirectoryInfo = 10 FileIdBothDirectoryRestartInfo = 11 FileIoPriorityHintInfo = 12 FileRemoteProtocolInfo = 13 FileFullDirectoryInfo = 14 FileFullDirectoryRestartInfo = 15 FileStorageInfo = 16 FileAlignmentInfo = 17 FileIdInfo = 18 FileIdExtdDirectoryInfo = 19 FileIdExtdDirectoryRestartInfo = 20 MaximumFileInfoByHandlesClass End Enum <StructLayout(LayoutKind.Sequential)> Public Structure FILE_STANDARD_INFO Public AllocationSize As Int64 Public EndOfFile As Int64 Public NumberOfLinks As UInt32 Public DeletePending As Boolean Public Directory As Boolean End Structure Public Enum SnapshotFlags As UInteger HeapList = &H1 Process = &H2 Thread = &H4 [Module] = &H8 Module32 = &H10 Inherit = &H80000000UI All = &H1F End Enum <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> Public Structure PROCESSENTRY32 Const MAX_PATH As Integer = 260 Friend dwSize As UInt32 Friend cntUsage As UInt32 Friend th32ProcessID As UInt32 Friend th32DefaultHeapID As IntPtr Friend th32ModuleID As UInt32 Friend cntThreads As UInt32 Friend th32ParentProcessID As UInt32 Friend pcPriClassBase As Int32 Friend dwFlags As UInt32 <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=MAX_PATH)> Friend szExeFile As String End Structure Public Enum SHUTDOWN_ACTION ShutdownNoReboot ShutdownReboot ShutdownPowerOff End Enum <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function NtTerminateProcess(ProcessHandle As Integer, ExitStatus As Long) As UInt32 End Function <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function NtLoadDriver(ByRef DriverServiceName As UNICODE_STRING) As Integer End Function <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function NtUnloadDriver(ByRef DriverServiceName As UNICODE_STRING) As Integer End Function <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function RtlAdjustPrivilege(Privilege As Integer, Enable As Boolean, CurrentThread As ADJUST_PRIVILEGE_TYPE, ByRef Enabled As Boolean) As Integer End Function <DllImport("ntdll.dll")> Public Shared Sub RtlInitUnicodeString(ByRef DestinationString As UNICODE_STRING, <MarshalAs(UnmanagedType.LPWStr)> SourceString As String) End Sub <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function ZwSetSystemInformation(Value1 As Integer, Value2 As IntPtr, Value3 As Integer) As Integer End Function <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function NtClose(ObjectHandle As Integer) As Integer End Function <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function RtlAllocateHeap(HeapHandle As IntPtr, Flags As ULong, Size As ULong) As Integer End Function <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function NtQuerySystemInformation(SystemInformationClass As SYSTEM_INFORMATION_CLASS, SystemInformation As IntPtr, SystemInformationLength As Integer, ByRef ReturnLength As Integer) As Integer End Function <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function RtlFreeHeap(HeapHandle As IntPtr, Flags As ULong, MemoryPointer As IntPtr) As Integer End Function <DllImport("advapi32.dll", CharSet:=CharSet.Ansi)> Public Shared Function RegCloseKey(hKey As Integer) As Integer End Function <DllImport("advapi32.dll", CharSet:=CharSet.Ansi)> Public Shared Function RegCreateKey(hKey As Integer, <MarshalAs(UnmanagedType.VBByRefStr)> ByRef lpSubKey As String, ByRef phkResult As Integer) As Integer End Function <DllImport("advapi32.dll", CharSet:=CharSet.Ansi)> Public Shared Function RegSetValueEx(hKey As Integer, <MarshalAs(UnmanagedType.VBByRefStr)> ByRef lpValueName As String, Reserved As Integer, dwType As Integer, <MarshalAs(UnmanagedType.VBByRefStr)> ByRef lpData As String, cbData As Integer) As Integer End Function <DllImport("shlwapi.dll", CharSet:=CharSet.Auto)> Public Shared Function SHDeleteKey(hkey As Integer, pszSubKey As [String]) As Integer End Function <DllImport("Advapi32.dll", CharSet:=CharSet.Auto)> Public Shared Function OpenSCManager(lpMachineName As [String], lpDatabaseName As [String], dwDesiredAccess As UInteger) As IntPtr End Function <DllImport("Advapi32.dll", CharSet:=CharSet.Auto)> Public Shared Function CreateService(hSCManager As IntPtr, lpServiceName As [String], lpDisplayName As [String], dwDesiredAccess As UInteger, dwServiceType As UInteger, dwStartType As UInteger, dwErrorControl As UInteger, lpBinaryPathName As [String], lpLoadOrderGroup As [String], lpdwTagId As [String], lpDependencies As [String], lpServiceStartName As [String], lpPassword As [String]) As IntPtr End Function <DllImport("Advapi32.dll", CharSet:=CharSet.Auto)> Public Shared Function OpenService(hSCManager As IntPtr, lpServiceName As [String], dwDesiredAccess As UInteger) As IntPtr End Function <DllImport("Advapi32.dll", CharSet:=CharSet.Auto)> Public Shared Function StartService(hService As IntPtr, dwNumServiceArgs As UInteger, lpServiceArgVectors As [String]) As IntPtr End Function <DllImport("Advapi32.dll", CharSet:=CharSet.Auto)> Public Shared Function CloseServiceHandle(hSCObject As IntPtr) As Boolean End Function <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function QueryServiceStatus(ByVal hService As IntPtr, ByRef dwServiceStatus As SERVICE_STATUS) As Boolean End Function <DllImport("Advapi32.dll", CharSet:=CharSet.Auto)> Public Shared Function ControlService(hService As IntPtr, dwControl As UInteger, ByRef lpServiceStatus As SERVICE_STATUS) As Boolean End Function <DllImport("Advapi32.dll", CharSet:=CharSet.Auto)> Public Shared Function DeleteService(hService As IntPtr) As IntPtr End Function <DllImport("ntdll.dll", CharSet:=CharSet.Unicode, SetLastError:=True)> Public Shared Function NtShutdownSystem(Action As SHUTDOWN_ACTION) As Integer End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function CreateToolhelp32Snapshot(dwFlags As Integer, th32ProcessID As Integer) As IntPtr End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function Process32First(hSnapshot As IntPtr, ByRef lppe As PROCESSENTRY32) As [Boolean] End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function Process32Next(hSnapshot As IntPtr, ByRef lppe As PROCESSENTRY32) As [Boolean] End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function CloseHandle(hObject As IntPtr) As [Boolean] End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function lstrcmpi(lpString1 As [String], lpString2 As [String]) As Integer End Function Public Shared Function GetPidByName(Proc As [String]) As UInteger Dim m_Snap As New IntPtr() Dim procEntry As New PROCESSENTRY32() procEntry.dwSize = CUInt(Marshal.SizeOf(GetType(PROCESSENTRY32))) m_Snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) If m_Snap = INVALID_HANDLE_VALUE Then Return 0 End If If Not Process32First(m_Snap, procEntry) Then Return 0 End If Do If lstrcmpi(procEntry.szExeFile, Proc) = 0 Then Return procEntry.th32ProcessID End If Loop While Process32Next(m_Snap, procEntry) CloseHandle(m_Snap) Return 0 End Function <DllImport("advapi32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function OpenSCManager(ByVal machineName As String, ByVal databaseName As String, ByVal desiredAccess As Int32) As IntPtr End Function <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> Public Shared Function CreateService(ByVal hSCManager As IntPtr, ByVal serviceName As String, ByVal displayName As String, ByVal desiredAccess As Int32, ByVal serviceType As Int32, ByVal startType As Int32, ByVal errorcontrol As Int32, ByVal binaryPathName As String, ByVal loadOrderGroup As String, ByVal TagBY As Int32, ByVal dependencides As String, ByVal serviceStartName As String, ByVal password As String) As IntPtr End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function CreateFile(lpFileName As [String], dwDesiredAccess As Integer, dwShareMode As Integer, lpSecurityAttributes As IntPtr, dwCreationDisposition As Integer, dwFlagsAndAttributes As Integer, hTemplateFile As IntPtr) As IntPtr End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function WriteFile(hFile As IntPtr, lpBuffer As Byte(), nNumberOfBytesToWrite As UInteger, ByRef lpNumberOfBytesWritten As Integer, lpOverlapped As IntPtr) As Boolean End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function LoadLibrary(lpFileName As [String]) As IntPtr End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function GetProcAddress(hModule As IntPtr, lpProcName As [String]) As IntPtr End Function <DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)> Public Shared Function FreeLibrary(hModule As IntPtr) As Boolean End Function End Class

Reply

RE: Useful Native Functions for VB.Net | Snippet #2
I just want to point out here that NT_SUCCESS is not 0. And the reason for this is because of the way __success works; other status returns that are not 0 are also not really considered as errors.
Code:
Public Const NT_SUCCESS As Long = &H0L

^ So this would be wrong. NT_SUCCESS is actually defined as:
Code:
typedef __success(return >= 0) LONG NTSTATUS; #define NT_SUCCESS(status) (((NTSTATUS)(status)) >= 0)

And this is a big misconception about NT status codes that a lot of people have. Future proofing code and proper code should never check for success by comparison with 0 for this reason. If you've ever looked at the relevant header files you would know what that >= 0 comparison is actually checking, and it's NOT the entire LONG value:
Code:
// // Values are 32 bit values layed out as follows: // // 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 // 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 // +---+-+-+-----------------------+-------------------------------+ // |Sev|C|R| Facility | Code | // +---+-+-+-----------------------+-------------------------------+ // // where // // Sev - is the severity code // // 00 - Success // 01 - Informational // 10 - Warning // 11 - Error // // C - is the Customer code flag // // R - is a reserved bit // // Facility - is the facility code // // Code - is the facility's status code //

Quote:NT_SUCCESS(Status)
Evaluates to TRUE if the return value specified by Status is a success type (0 − 0x3FFFFFFF) or an informational type (0x40000000 − 0x7FFFFFFF).

This is because other returns like STATUS_PENDING aren't really error values.

I'll leave the comment for __success here as well although it takes a couple reads to actually understand what the heck is meant due to the poor wording:
Code:
* __success(expr) T f() : indicates whether function f succeeded or * not. If is true at exit, all the function's guarantees (as given * by other annotations) must hold. If is false at exit, the caller * should not expect any of the function's guarantees to hold. If not used, * the function must always satisfy its guarantees. Added automatically to * functions that indicate success in standard ways, such as by returning an * HRESULT.

Therefore, NT_SUCCESS is actually not even a value, you shouldn't define it as such, it's more like a macro that tests for a CONDITION...

The other thing is that these P/Invokes should conventionally be within a pre-defined NativeMethods class probably. See: http://stackoverflow.com/a/37643042

Reply