getting a list of kernel objects windows - c

HI!
I bet more than a week and I can not form a complete picture of how you can get a list of kernel objects .My algorithm is as follows :
1) Connecting NTDLL.dll (LoadLibrary)
2) GetProcAddress (variable_Library_name, "NtQueryDirectoryObject")
and the pre-announcement structures : _OBJDIR_INFORMATION,
_OBJECT_ATTRIBUTES
3) Trying to apply a function NtOpenDirectoryObject for a list of
objects
Here is a piece of code that is responsible for the use of the function NtOpenDirectoryObject:
OBJDIR_INFORMATION *ssinfo =(OBJDIR_INFORMATION* ) HeapAlloc(GetProcessHeap(), 0, 0x800);
///////////////////////
HANDLE hFile,hThread,hMapFile;
HMODULE hNtdll ,hKernel;
DWORD dwThreadId;
OBJECT_ATTRIBUTES obj;
WCHAR * uString=L"\\BaseNamedObjects";
UNICODE_STRING str;
DWORD i,a,iStrLen,b=0;
char sObjName[30],sTmp[50];
LPVOID lpMapAddress;
FARPROC pWinExec,pExitThread;
bool bFound;
char* sCommand;
/////////////////////////////////////////////////////////////////
NtQueryDirectoryObject = (NTQUERYDIRECTORYOBJECT )GetProcAddress(hinstLib,"NtQueryDirectoryObject");
InitializeObjectAttributes (&obj, &str, 0, 0, 00);
NtOpenDirectoryObject(&hFile,0x20001,&obj);
The full code (including struct definitions) is at: http://pastebin.com/pDNb3GTn
When calling a function with parameters NtOpenDirectoryObject get an exception c0000005, which means that access is blocked .
tell me please, am I doing smth wrong, and where is my mistake. Is it possible to not to use the native api? Thank you for your help

Exception c0000005 is an Access Violation. That does not mean that access was blocked. It means invalid memory was accessed, such as if a NULL/uninitialized pointer were accessed, or if you are not aligning data correctly and accessing something out of bounds of what you have allocated.
As Andrew mentioned, you are not initializing the UNICODE_STRING at all. Try this instead:
hNtdll = LoadLibrary("ntdll.dll");
NtOpenDirectoryObject = (NTOPENDIRECTORYOBJECT) GetProcAddress(hNtdll, "NtOpenDirectoryObject");
...
if (NtOpenDirectoryObject)
{
// add these three lines
str.Length = lstrlenW(uString) * sizeof(WCHAR);
str.MaximumLength = str.Length;
str.Buffer = uString;
InitializeObjectAttributes (&obj, &str, 0, NULL, NULL);
NtOpenDirectoryObject(&hFile, 0x20001, &obj);
}

Related

Vulkan vkCreateInstance - Access violation writing location 0x0000000000000000

I am trying to write a basic program using Vulkan, but I keep getting a runtime error.
Exception thrown at 0x00007FFDC27A8DBE (vulkan-1.dll) in VulkanTest.exe: 0xC0000005: Access violation writing location 0x0000000000000000.
This seems to be a relatively common issue, resulting from a failure to initialize the arguments of the vkCreateInstance function. I have tried all of the solutions I found proposed to others, even initializing things I am fairly certain I don't need to, and I still haven't been able to solve the problem. The program is written in C using the MSVC compiler.
#include "stdio.h"
#include "SDL.h"
#include "vulkan\vulkan.h"
#include "System.h"
int main(int argc, char *argv[])
{
//Initialize SDL
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
printf("Error");
}
printf("Success");
//Initialize Vulkan
VkInstance VulkanInstance;
VkApplicationInfo VulkanApplicationInfo;
VulkanApplicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
VulkanApplicationInfo.pNext = 0;
VulkanApplicationInfo.pApplicationName = "VulkanTest";
VulkanApplicationInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
VulkanApplicationInfo.pEngineName = "VulkanTest";
VulkanApplicationInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
VulkanApplicationInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo VulkanCreateInfo = {0,0,0,0,0,0,0,0};
VulkanCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
VulkanCreateInfo.pNext = 0;
VulkanCreateInfo.pApplicationInfo = &VulkanApplicationInfo;
VulkanCreateInfo.enabledLayerCount = 1;
VulkanCreateInfo.ppEnabledLayerNames = "VK_LAYER_KHRONOS_validation";
vkEnumerateInstanceExtensionProperties(0, VulkanCreateInfo.enabledExtensionCount,
VulkanCreateInfo.ppEnabledExtensionNames);
//Create Vulkan Instance
if(vkCreateInstance(&VulkanCreateInfo, 0, &VulkanInstance) != VK_SUCCESS)
{
printf("Vulkan instance was not created");
}
//Create SDL Window
SDL_Window* window;
window = SDL_CreateWindow("VulkanTest", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 0, 0, SDL_WINDOW_VULKAN || SDL_WINDOW_FULLSCREEN_DESKTOP);
SDL_Delay(10000);
return 0;
}
Are you sure the call to vkCreateInstance() is what is crashing? I have not tried to debug the code you have shown (that is your job), but just looking at the calls that the code is making, it should be the call to vkEnumerateInstanceExtensionProperties() that is crashing (if it even compiles at all!).
The 2nd parameter of vkEnumerateInstanceExtensionProperties() expects a uint32_t* pointer, but you are passing in a uint32_t value (VulkanCreateInfo.enabledExtensionCount) that has been initialized to 0. So, that would make the pPropertyCount parameter be a NULL pointer (if it even compiles).
You are passing VulkanCreateInfo.ppEnabledExtensionNames in the 3rd parameter (if that even compiles), and ppEnabledExtensionNames has been initialized to NULL. Per the documentation for vkEnumerateInstanceExtensionProperties():
If pProperties is NULL, then the number of extensions properties available is returned in pPropertyCount. Otherwise, pPropertyCount must point to a variable set by the user to the number of elements in the pProperties array, and on return the variable is overwritten with the number of structures actually written to pProperties.
Since pPropertCount is NULL, vkEnumerateInstanceExtensionProperties() has nowhere to write the property count to! That would certainly cause an Access Violation trying to write to address 0x0000000000000000.
The documentation clears states:
pPropertyCount must be a valid pointer to a uint32_t value
On top of that, your call to vkEnumerateInstanceExtensionProperties() is just logically wrong anyway, because the 3rd parameter expects a pointer to an array of VkExtensionProperties structs, but VulkanCreateInfo.ppEnabledExtensionNames is a pointer to an array of const char* UTF-8 strings instead.
In other words, you should not be using vkEnumerateInstanceExtensionProperties() to initialize criteria for the call to vkCreateInstance(). You are completely misusing vkEnumerateInstanceExtensionProperties(). You probably meant to use SDL_Vulkan_GetInstanceExtensions() instead, eg:
uint32_t ExtensionCount = 0;
if (!SDL_Vulkan_GetInstanceExtensions(NULL, &ExtensionCount, NULL))
{
...
}
const char **ExtensionNames = (const char **) SDL_malloc(sizeof(const char *) * ExtensionCount);
if (!ExtensionNames)
{
...
}
if (!SDL_Vulkan_GetInstanceExtensions(NULL, &ExtensionCount, ExtensionNames))
{
SDL_free(ExtensionNames);
...
}
VulkanCreateInfo.enabledExtensionCount = ExtensionCount;
VulkanCreateInfo.ppEnabledExtensionNames = ExtensionNames;
if (vkCreateInstance(&VulkanCreateInfo, 0, &VulkanInstance) != VK_SUCCESS)
{
...
}
SDL_free(ExtensionNames);
...

using writeprivateprofilestringw and readprivateprofilestringw in unicode not working

I try to write a push-pop like program using Read/WriteprivateprofilestringW functions and there are problems I don’t think I can see by myself. If you are kind please have a look at my lines and point me so I get it to run correctly.
When I run it with an already created file, the output of writeprivateprofilestringw's section field name is wrong. I think it’s because I’m using LPWSTR data type but nothing I tried solves it.
output:
[win32 app\Release\fonemeW.dic]
dictsionar=dicţionar
expected output:
[dictionar]
dictsionar=dicţionar
////////////////////////////////////////////////////////////////////////
//
// push word into dictionary
//
////////////////////////////////////////////////////////////////////////
void pushWordW(LPWSTR szWord, LPWSTR szFonems){
WCHAR* szDic=(WCHAR)calloc(MAX_PATH, sizeof(WCHAR));
LPWSTR sztemp=L"dictionar";
wcscpy(szDic, L"fonemeW.txt");
getDicFile(&szDic);
WritePrivateProfileStringW(L"dictionar", szFonems, szWord, szDic);
}
////////////////////////////////////////////////////////////////////////
//
// pull word from the dictionary as query fonem string
//
///////////////////////////////////////////////////////////////////////
void pullWordW(TCHAR* szWord[MAX_PATH], LPWSTR szFonems){
WCHAR* szDic=(WCHAR)calloc(MAX_PATH, sizeof(WCHAR));
wcscpy(szDic, L"fonemeW.dic");
getDicFile(&szDic);
GetPrivateProfileStringW(L"dictionar", szFonems, L"", szWord[0], 0, szDic);
if(wcslen(szWord[0])==0)
MessageBox(0, "Word not in the dictionar", "titlu popWordW", 0);
}
////////////////////////////////////////////////////////////////////////
//
// test the push-pop (from the dictionary) procedures
//
////////////////////////////////////////////////////////////////////////
void testPP(void){
LPWSTR szWord=L"dictionar";
szWord[3]=0x0163;
LPWSTR szFonem=L"dictsionar";
MessageBoxW(0, szWord, L"titlu testPP", 0);
pushWordW(szWord, szFonem);//push word into dictionar
wcscpy(szFonem, L"diade-muh");//query dictionar
pullWordW(&szWord, szFonem);//pop word from dictionary based on fonem transliteration
MessageBoxW(0, szWord, L"titlu testPP", 0);
}
edit i editted the declaration of szWord and there seems to be no problems anymore.
You did not show the implementation for getDicFile(), so I can only assume it works correctly (though the code will leak memory if getDicFile() returns a pointer to dynamically allocated memory).
I don't see any problem with the implementation of your pushWordW() function. It should not be using a filename as the INI section name. So this implies that you are actually passing an incorrect/corrupted pointer to the lpAppName parameter of WritePrivateProfileString().
However, I do see problems with the implementation of your pullWordW() and testPP() functions.
in testPP(), szWord initially points to a string literal, which is read-only. Thus, the statement szWord[3]=0x0163; should have caused a run-time error trying to write to read-only memory. So, either change the literal to L"dicţionar" so you do not need szWord[3]=0x0163; anymore, or else change the declaration of szWord to WCHAR[] instead of LPWSTR, or use malloc(), to allocate writable memory that the literal can then be copied into (in the latter case, don't forget to free() it when you are done using it).
in testPP(), szFonem initially points to a read-only string literal as well. Thus, the statement wcscpy(szFonem, L"diade-muh"); should similarly be causing a run-time error trying to write to read-only memory.
when testPP() calls pullWordW(), passing szWord using the & operator implies that pullWordW() is expected to update szWord with a new memory address pointing at the data returned by GetPrivateProfileStringW(). The problem is, GetPrivateProfileStringW() expects a pre-allocated buffer of writable memory to store the data into, but the pointer you are actually passing to it is a pointer to the read-only literal that szWord was initially set to. Again, it should be causing a run-time error. But it actually won't, because you are setting the nSize parameter of GetPrivateProfileStringW() to 0, telling it that there is no space available at the memory address for it to store data into. So no run-time errror. But, let's just say for the sake of argument that it could write data. pullWordW() is not updating its szWord parameter to point at any new memory address. And even if it did, who is responsible for allocating that memory, and who is responsible for freeing it? Your code is not defining those rules anywhere.
The fact that you are not encountering run-time errors that crash your app likely means that memory is being corrupted instead, in which case all bets are off.
Fix your code to use memory correctly. For example:
////////////////////////////////////////////////////////////////////////
//
// get dictionary filename
//
////////////////////////////////////////////////////////////////////////
bool getDicFile(LPWSTR szDic, int nDic){
// copy whatever your actual dictionary filename is...
return (wcscpy_s(szDic, nDic, L"fonemeW.dic") == 0);
}
////////////////////////////////////////////////////////////////////////
//
// push word into dictionary
//
////////////////////////////////////////////////////////////////////////
void pushWordW(LPWSTR szWord, LPWSTR szFonems){
WCHAR szDic[MAX_PATH+1];
if (getDicFile(szDic, MAX_PATH+1)){
WritePrivateProfileStringW(L"dictionar", szFonems, szWord, szDic);
}
}
////////////////////////////////////////////////////////////////////////
//
// pull word from the dictionary as query fonem string
//
///////////////////////////////////////////////////////////////////////
bool pullWordW(LPWSTR szWord, int nWord, LPWSTR szFonems){
LPWSTR szDic[MAX_PATH+1];
if (getDicFile(szDic, MAX_PATH+1)){
return (GetPrivateProfileStringW(L"dictionar", szFonems, L"", szWord, nWord, szDic) > 0);
}
return false;
}
////////////////////////////////////////////////////////////////////////
//
// test the push-pop (from the dictionary) procedures
//
////////////////////////////////////////////////////////////////////////
void testPP(void){
WCHAR szWord[256] = L"dictionar";
szWord[3]=0x0163;
WCHAR szFonem[12] = L"dictsionar";
MessageBoxW(0, szWord, L"titlu testPP", 0);
pushWordW(szWord, szFonem);//push word into dictionar
wcscpy_s(szFonem, 12, L"diade-muh");//query dictionar
if (pullWordW(szWord, 256, szFonem)){//pop word from dictionary based on fonem transliteration
MessageBoxW(0, szWord, L"titlu testPP", 0);
} else {
MessageBoxW(0, L"Word not in the dictionar", L"titlu popWordW", 0);
}
}

Threading in C with CreateThread()

I am very much a novice to C, and I am trying to make a program to run MIDI sequences, and basically, I have two functions, both running a different MIDI pattern, and I need them to run in parallel. Due to the nature of the functions (one running a sequence and the other playing random notes), I am almost 100% sure that I can't have then running in the same function.
I've been scouring the internet for some clue on how to do this with pthreads (which apparently don't work on Windows?) and CreateThread(), but I can't seem to get it to work. I am currently trying to use CreateThread() and trying to bring in the integers required for the random midi sequence and I am getting an error concerning 'LPTHREAD_START_ROUTINE' which reads: 'expected 'LPTHREAD_START_ROUTINE' but argument is of type 'DWORD (*)(int, int, int)'.
A sort of pseudocode of what I'm working on is here:
DWORD WINAPI solo_thread(int key, int tempo, int scale)
{
///// this contains the random midi notes
}
int backing(int key, int tempo, int backing)
{
HANDLE thread = CreateThread(NULL, 0, solo_thread, NULL, 0, NULL);
if (thread) {
////// this contains the midi sequence
}
Hopefully I have explained my problem well... But I am well aware that the most likely case is that I am going about this CreateThread() thing in all the wrong ways.
Thanks!
The signature of the thread entry function is, from the ThreadProc() reference page:
DWORD WINAPI ThreadProc(
_In_ LPVOID lpParameter
);
and solo_thread() does not have that signature.
If it is necessary to supply multiple arguments to the function create a struct containing multiple members representing the desired arguments. The argument to the thread must outlive the thread otherwise the thread will be accessing a dangling pointer. The common solution is to dynamically allocate the argument and have the thread free() it when it no longer requires it.
Example:
struct Thread_data
{
int key;
int tempo;
int scale;
};
DWORD WINAPI solo_thread(void* arg)
{
struct Thread_data* data = arg;
/* Use 'data'. */
free(data);
return 0;
}
int backing(int key, int tempo, int backing)
{
struct Thread_data* data = malloc(*data);
if (data)
{
data->key = key;
data->tempo = tempo;
data->scale = backing;
HANDLE thread = CreateThread(NULL, 0, solo_thread, &data, 0, NULL);
}

How do I embed and use resource files in a C program using VS11?

This is my first attempt at using a resource file. I have seen a lot of answers that apply to C# but not C. Any suggestions?
Assuming you mean the method used by Sysinternals and others to carry the drivers or needed DLLs (or even the x64 version of the program itself) in the resource section of a program (e.g. Sysinternals' Process Explorer), using Microsoft Visual C you can use this code:
BOOL ExtractResTo(HINSTANCE Instance, LPCTSTR BinResName, LPCTSTR NewPath, LPCTSTR ResType)
{
BOOL bResult = FALSE;
HRSRC hRsrc;
if(hRsrc = FindResource(HMODULE(Instance), BinResName, ResType))
{
HGLOBAL hGlob
if(HGLOBAL hGlob = LoadResource(Instance, hRsrc))
{
DWORD dwResSize = SizeofResource(Instance, hRsrc);
HANDLE hFileWrite = CreateFile(NewPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_ARCHIVE, 0);
if(hFileWrite != INVALID_HANDLE_VALUE)
__try
{
DWORD dwSizeWritten = 0;
bResult = (WriteFile(hFileWrite, LockResource(hGlob), dwResSize, &dwSizeWritten, NULL) && (dwSizeWritten == dwResSize));
}
__finally
{
CloseHandle(hFileWrite);
}
}
}
return bResult;
}
This saves the given resource (BinResName) of resource type (ResType) from the module (e.g. a DLL) Instance to file NewPath. Obviously if your C doesn't understand __try and __finally you'll have to adjust the code accordingly.
Taken from here (in SIDT.rar) and adjusted for C. The code is under the liberal BSD license according to the website.
Now if you wanted to get the pointer to the data (ppRes) and its size (pwdResSize):
BOOL GetResourcePointer(HINSTANCE Instance, LPCTSTR ResName, LPCTSTR ResType, LPVOID* ppRes, DWORD* pdwResSize)
{
// Check the pointers to which we want to write
if(ppRes && pdwResSize)
{
HRSRC hRsrc;
// Find the resource ResName of type ResType in the DLL/EXE described by Instance
if(hRsrc = FindResource((HMODULE)Instance, ResName, ResType))
{
HGLOBAL hGlob;
// Make sure it's in memory ...
if(hGlob = LoadResource(Instance, hRsrc))
{
// Now lock it to get a pointer
*ppRes = LockResource(hGlob);
// Also retrieve the size of the resource
*pdwResSize = SizeofResource(Instance, hRsrc);
// Return TRUE only if both succeeded
return (*ppRes && *pdwResSize);
}
}
}
// Failure means don't use the values in *ppRes and *pdwResSize
return FALSE;
}
Call like this:
LPVOID pResource;
DWORD pResourceSize;
if(GetResourcePointer(hInstance, _T("somename"), _T("sometype"), &pResource, &pResourceSize))
{
// use pResource and pResourceSize
// e.g. store into a string buffer or whatever you want to do with it ...
}
Note, this also works for resources with integer IDs. You can detect these by using the macro IS_INTRESOURCE.
The resource script, e.g. myresources.rc, itself is trivial:
#include <winnt.rh>
"somename" "sometype" "path\to\file\to\embed"
RCDATA instead of sometype is a reasonable choice
#include <winnt.rh> // for RCDATA to be known to rc.exe
"somename" RCDATA "path\to\file\to\embed"
... in which case you would adjust the above call to be:
GetResourcePointer(hInstance, _T("somename"), RT_RCDATA, &pResource, &pResourceSize)
Complete example making use of GetResourcePointer above. Let's say you have a pointer variable char* buf and you know your resource is actual text, then you need to make sure that it is zero-terminated when used as a string, that's all.
Resource script:
#include <winnt.rh>
"test" RCDATA "Test.txt"
The code accessing it
char* buf = NULL;
LPVOID pResource;
DWORD pResourceSize;
if(GetResourcePointer(hInstance, _T("test"), RT_RCDATA, &pResource, &pResourceSize))
{
if(buf = calloc(pResourceSize+1, sizeof(char)))
{
memcpy(buf, pResource, pResourceSize);
// Now use buf
free(buf);
}
}
Unless, of course you meant to simply link a .res file which works by passing it to the linker command line.

How can I get a function entry point in PE file

If I have exampleA.exe process and I use the FindEntryPointAddress() function to get the main() entry point of exampleB.exe process
FindEntryPointAddress() is a function of exampleA.exe
DWORD FindEntryPointAddress( TCHAR *exeFile )
{
BY_HANDLE_FILE_INFORMATION bhfi;
HANDLE hMapping;
char *lpBase;
HANDLE hFile = CreateFile(exeFile, GENERIC_READ, FILE_SHARE_READ, NULL,OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
;
if (!GetFileInformationByHandle(hFile, &bhfi))
;
hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, bhfi.nFileSizeHigh, bhfi.nFileSizeLow, NULL);
if (!hMapping)
;
lpBase = (char *)MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, bhfi.nFileSizeLow);
if (!lpBase)
;
PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)lpBase;
if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) // 0x00004550(IMAGE_NT_SIGNATURE)
;
PIMAGE_NT_HEADERS32 ntHeader = (PIMAGE_NT_HEADERS32)(lpBase + dosHeader->e_lfanew);
if (ntHeader->Signature != IMAGE_NT_SIGNATURE)
;
DWORD pEntryPoint = ntHeader->OptionalHeader.ImageBase + ntHeader->OptionalHeader.AddressOfEntryPoint;
UnmapViewOfFile((LPCVOID)lpBase);
CloseHandle(hMapping);
CloseHandle(hFile);
printf( "test.exe entry point: %p\n", pEntryPoint );
return pEntryPoint;
} // FindEntryPointAddress()
Know I have a question is how can I edit the FindEntryPointAddress() to get the func() entrypoint of exampleB.exe
exampleB.exe
void func()
{
char str[10];
strcpy( str, "iambuffer\n" );
printf( "%s", str );
} // func()
int main()
{
func();
return 0;
} // main()
thanks a lot
Unless the function is exported (see e.g. __declspec(dllexport)) you're out of luck. Without an entry in the export table, it's not possible to get the address of a function other than the entry point.
Moreover, even if you find some data related to the function elsewhere (for example, in the debugging symbols) you might be still unable to get the address, as it's possible that the function got inlined everywhere or was eliminated for whatever other reason and its related data were not. Exported functions are not affected by that, due to the fact that the compiler and linker are careful enough to always emit them.
If you are looking into making a custom GetProcAddress, look here, however, unless you have pdb's or the functions symbol is in the EAT (export address table), you'll be unable to find it.

Resources