calling native(Nt) API in user mode - winapi

I am trying to call native API(NtOpenKey) in user mode. I am seeing linker problem. I am really confused, what is missing here. How can I achieve doing this? I am attaching my code here. ntdll.lib is added to the project(link)
Error 58 error LNK2001: unresolved external symbol "__declspec(dllimport) long __cdecl NtOpenKey(void * *,unsigned long,struct _OBJECT_ATTRIBUTES *)" (__imp_?NtOpenKey##YAJPEAPEAXKPEAU_OBJECT_ATTRIBUTES###Z) C:\Users\santhi.ragipati\documents\visual studio 2013\Projects\NtRegistry\NtRegistry\NtRegistry.obj NtRegistry
Thanks
Santhi
`// NtRegistry.cpp : Defines the entry point for the console application.
//
#include <tchar.h>
#include <Windows.h>
#include <Winternl.h>
#include <ntstatus.h>
NTSYSAPI NTSTATUS NTAPI NtOpenKey(
_Out_ PHANDLE KeyHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_ POBJECT_ATTRIBUTES ObjectAttributes
);
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE handleRegKey = NULL;
for (int n = 0; n < 1; n++)
{
NTSTATUS status = NULL;
UNICODE_STRING RegistryKeyName;
OBJECT_ATTRIBUTES ObjectAttributes;
RtlInitUnicodeString(&RegistryKeyName, L"\\Registry\\Machine\\Software\\MyCompany\\MyApp");
InitializeObjectAttributes(&ObjectAttributes,
&RegistryKeyName,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
NULL, // handle
NULL);
status = NtOpenKey(&handleRegKey, (ACCESS_MASK)KEY_READ, &ObjectAttributes);
if (NT_SUCCESS(status) == FALSE)
{
break;
}
} // Get the Frame location from the registry key.
// All done with the registry.
if (NULL != handleRegKey)
{
NtClose(handleRegKey);
}
return 0;
}
`

This was the giveaway:
NtOpenKey##YAJPEAPEAXKPEAU_OBJECT_ATTRIBUTES###Z
That's typical of C++ name mangling; since functions can be overloaded, but the function name used when exporting and importing must be unique, the name is modified to include a description of the argument list.
Adding extern "c" to the declaration will resolve the problem.
Incidentally, you probably don't want to set the OBJ_KERNEL_HANDLE flag, since it asks for a handle that you won't be able to use. I'm guessing Windows will ignore it, and give you a user-mode handle anyway, but better safe than sorry.

Related

NT Security API: SECURITY_DESCRIPTOR.Control, when can I see SE_OWNER_DEFAULTED?

From Windows NT security API, SE_OWNER_DEFAULTED is a flag bit from SECURITY_DESCRIPTOR_CONTROL.
MSDN states it quite briefly:
(SE_OWNER_DEFAULTED) Indicates that the SID of the owner of the security descriptor was provided by a default mechanism. This flag can be used by a resource manager to identify objects whose owner was set by a default mechanism.
I'm curious that when I can see this flag set.
I write NtfsOwner.cpp to display owner SID of an NTFS file/directory's security descriptor, and use GetSecurityDescriptorOwner to query that SE_OWNER_DEFAULTED flag, but have no chance seeing it even once.
Could somebody give me some clue. Could it be possible that SE_OWNER_DEFAULTED exhibits on other type of NT objects(not on a file/directory)?
#include <Windows.h>
#include <AclAPI.h>
#include <sddl.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <locale.h>
template<typename T1, typename T2>
bool IsSameBool(T1 a, T2 b)
{
if(a && b)
return true;
else if(!a && !b)
return true;
else
return false;
}
void myDisplayNtfsOwner(const TCHAR *szfn)
{
DWORD succ = 0;
HANDLE hFile = CreateFile(szfn,
READ_CONTROL, // dwDesiredAccess=GENERIC_READ etc
FILE_SHARE_READ|FILE_SHARE_WRITE, // shareMode
NULL, // SecuAttr, no need bcz we are opening existing file
OPEN_EXISTING, // dwCreationDisposition
FILE_FLAG_BACKUP_SEMANTICS, // this is required for open a directory
NULL);
if(hFile==INVALID_HANDLE_VALUE)
{
_tprintf(_T("Warning: CreateFile() failed!(WinErr=%d) But I will go on calling GetSecurityInfo(0xFFFFffff, ...)\n"),
GetLastError());
}
SECURITY_DESCRIPTOR *pSD = nullptr;
DWORD winerr = GetSecurityInfo(hFile, SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
NULL, NULL, NULL, NULL,
(PSECURITY_DESCRIPTOR*)&pSD);
assert(winerr==0);
SID* psidOwner = nullptr;
BOOL isOwnerDefaulted = 0;
succ = GetSecurityDescriptorOwner(pSD, (PSID*)&psidOwner, &isOwnerDefaulted);
assert(succ);
PTSTR strOwner = nullptr;
succ = ConvertSidToStringSid(psidOwner, &strOwner);
assert(succ);
_tprintf(_T("Owner SID is: %s\n"), strOwner);
_tprintf(_T("Is owner SID defaulted? %s\n"), isOwnerDefaulted?_T("yes"):_T("no"));
assert(IsSameBool(pSD->Control & SE_OWNER_DEFAULTED, isOwnerDefaulted));
LocalFree(strOwner);
LocalFree(pSD);
CloseHandle(hFile);
}
int _tmain(int argc, TCHAR* argv[])
{
setlocale(LC_ALL, "");
if(argc==1)
{
const TCHAR *s = _T("D:\\test\\foo.txt");
_tprintf(_T("Missing parameters.\n"));
_tprintf(_T("Example:\n"));
_tprintf(_T(" NtfsOwner1 %s\n"), s);
exit(1);
}
const TCHAR *szfn = argv[1];
myDisplayNtfsOwner(szfn);
return 0;
}

unresolved external symbol WdmlibIoCreateDeviceSecure referenced in function DriverEntry

I write a windows 10 driver. And following is the code, actually the code is a sample of a book.
is there anyone know what shold i do to deal with this issue.
#include <ntifs.h>
#include <wdmsec.h>
PDEVICE_OBJECT g_cdo = NULL;
const GUID CWK_GUID_CLASS_MYCDO =
{ 0x17a0d1e0L, 0x3249, 0x12e1, {0x92,0x16, 0x45, 0x1a, 0x21, 0x30, 0x29, 0x06} };
#define CWK_CDO_SYB_NAME L"\\??\\slbkcdo_3948d33e"
void DriverUnload(PDRIVER_OBJECT driver)
{
// ...
}
NTSTATUS DriverEntry(PDRIVER_OBJECT driver, PUNICODE_STRING reg_path)
{
NTSTATUS status;
ULONG i;
UCHAR mem[256] = { 0 };
UNICODE_STRING sddl = RTL_CONSTANT_STRING(L"D:P(A;;GA;;;WD)");
UNICODE_STRING cdo_name = RTL_CONSTANT_STRING(L"\\Device\\cwk_3948d33e");
UNICODE_STRING cdo_syb = RTL_CONSTANT_STRING(CWK_CDO_SYB_NAME);
KdBreakPoint();
status = IoCreateDeviceSecure(
driver,
0, &cdo_name,
FILE_DEVICE_UNKNOWN,
FILE_DEVICE_SECURE_OPEN,
FALSE, &sddl,
(LPCGUID)&CWK_GUID_CLASS_MYCDO,
&g_cdo);
if (!NT_SUCCESS(status))
return status;
// ...
return STATUS_SUCCESS;
}
the error message is:
LNK2019 unresolved external symbol WdmlibIoCreateDeviceSecure referenced in function DriverEntry MyDriver7 C:\Users\xxx\source\repos\MyDriver7\MyDriver7\Source.obj
You need to compile your project with Wdmsec.lib.
In Visual Studio, right click the project and go to Configuration Properties > Linker > Input > Additional Dependencies and add Wdmsec.lib.

Listening to messages in another Windows app

I'd like my program to listen to messages in another Windows app.
I am aware of SetWindowsHook, but am concerned about this line:
If the dwThreadId parameter is zero or specifies the identifier of a
thread created by a different process, the lpfn parameter must point
to a hook procedure in a DLL.
I don't know which hook procedures are in Windows DLLs, so am at a loss.
(I'm using Python with ctypes to use the WinAPI.)
Question: How can I get my program to listen for messages in another Windows process?
You need to create a DLL and add hook functions to the DLL.
I will use the following code in C++ to create the DLL:
#include <windows.h>
#include <iostream>
HINSTANCE hThisDLL;
HHOOK hMsgHook;
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
hThisDLL = hinstDLL;
return TRUE;
}
LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
//do what you want to do
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
extern "C" __declspec(dllexport) BOOL InstallHook()
{
if (!hMsgHook)
hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, &GetMsgProc, hThisDLL, 0);
return (hMsgHook != NULL);
}
extern "C" __declspec(dllexport) VOID UninstallHook()
{
if (hMsgHook)
{
UnhookWindowsHookEx(hMsgHook);
hMsgHook = NULL;
}
}
After generating the .dll file, you can load the dynamic library through the LoadLibrary function, and use the GetProcAddress function to get the function address in the dynamic library. Then call the hook function.
Here is the code with C++:
#include <iostream>
#include <windows.h>
typedef BOOL(WINAPI* LPInstallHook)();
typedef VOID(WINAPI* LPUninstallHook)();
int main()
{
HMODULE dll_handle;
LPInstallHook installProc;
LPUninstallHook uninstallProc;
HHOOK process_hook;
dll_handle = LoadLibrary(L"test.dll");
if (dll_handle)
{
installProc = (LPInstallHook)GetProcAddress(dll_handle, "InstallHook");
uninstallProc = (LPUninstallHook)GetProcAddress(dll_handle, "UninstallHook");
}
MSG msg;
installProc();
while (GetMessageW(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
uninstallProc();
if(dll_handle) FreeLibrary(dll_handle);
}
This is part of the code implemented in python, you can refer to it:
import ctypes
import os
from ctypes import *
user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
if __name__ == '__main__':
dllpath = os.path.join(path,"test.dll")
pDll = ctypes.WinDLL(dllpath)
pDll.InstallHook()
msg = ctypes.wintypes.MSG()
while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
user32.TranslateMessage(msg)
user32.DispatchMessageW(msg)
Of course, according to the documentation, you can set dwThreadId as the identifier of other threads. You can refer to the similar thread.

Programmatically turn airplane mode on or off Windows

I am writing an app where I need to turn airplane mode on or off on windows. I have seen this question, but the answers only get the status, or say you cannot do such a thing for Metro apps. I am not making a modern/metro app, so I don't need to worry about application sandboxing.
Is there an api to turn Airplane mode on/off, and how should I use it?
EDIT: In my use case, I know I can control it, and the user is ok with that.
Also, I found this msdn question with the following excerpt:
Windows 8(build 8250), I can turn on / off airplane mode in Metro Style Network Setting UI.
How to do this programmatically?
Microsoft defined HID Usage code for Wireless Radio Button (Usage: 0xC6).
Question: Is there some virtual key code for Wireless Radio Button? If so, Application can send this keycode by Keybd_event.
WLANAPI.dll export the API WlanStoreRadioStateOnEnteringAirPlaneMode , but there are no any document for this API.
Question: Can you provide detail information? Is it used to control Air Plane Mode, How to call this API?
So apparently (to give a summery of the answer), one can check the state of Airplane mode using the MobileBroadbandRadioState enum.
The HID route may be a possibility docs. Apparently it is a question of whether one can send the code 0xc6 to kbd_event.
EDIT2: Apparently there is a window called Network Flyout and I was thinking of enumerating the children to find the switch, but I haven't had much success. I'll have to use Spy++ some more to find out.
All of the following I discovered myself via reverse engineering.
The internal API used internally by windows to get/set Airplane mode makes use of COM calls to "RMsvc" service (which is located in "RMApi.dll"). That service is exporting a factory and interface which contains functions to get/set flight mode:
#include <Windows.h>
#include <assert.h>
#include <stdio.h>
static GUID const CLSID_RadioManagementAPI = { 0x581333f6, 0x28db, 0x41be, { 0xbc, 0x7a, 0xff, 0x20, 0x1f, 0x12, 0xf3, 0xf6 } };
static GUID const CID_IRadioManager = { 0xdb3afbfb, 0x08e6, 0x46c6, { 0xaa, 0x70, 0xbf, 0x9a, 0x34, 0xc3, 0x0a, 0xb7 } };
typedef IUnknown IUIRadioInstanceCollection; /* Didn't bother rev-engineering this one... */
typedef DWORD _RADIO_CHANGE_REASON;
typedef struct IRadioManagerVtbl IRadioManagerVtbl;
typedef struct IRadioManager {
IRadioManagerVtbl *lpVtbl;
} IRadioManager;
struct IRadioManagerVtbl {
/* IUnknown */
HRESULT (STDMETHODCALLTYPE *QueryInterface)(IRadioManager *This, GUID const *riid, LPVOID *ppvObj);
ULONG (STDMETHODCALLTYPE *AddRef)(IRadioManager *This);
ULONG (STDMETHODCALLTYPE *Release)(IRadioManager *This);
/* IRadioManager (aka. `CUIRadioManager') */
HRESULT (STDMETHODCALLTYPE *IsRMSupported)(IRadioManager *This, DWORD *pdwState);
HRESULT (STDMETHODCALLTYPE *GetUIRadioInstances)(IRadioManager *This, IUIRadioInstanceCollection **param_1);
HRESULT (STDMETHODCALLTYPE *GetSystemRadioState)(IRadioManager *This, int *pbEnabled, int *param_2, _RADIO_CHANGE_REASON *param_3);
HRESULT (STDMETHODCALLTYPE *SetSystemRadioState)(IRadioManager *This, int bEnabled);
HRESULT (STDMETHODCALLTYPE *Refresh)(IRadioManager *This);
HRESULT (STDMETHODCALLTYPE *OnHardwareSliderChange)(IRadioManager *This, int param_1, int param_2);
};
int main() {
HRESULT hr;
IRadioManager *irm;
hr = CoInitialize(NULL);
assert(!FAILED(hr));
irm = NULL;
hr = CoCreateInstance(&CLSID_RadioManagementAPI, NULL, 4,
&CID_IRadioManager, (void **)&irm);
assert(!FAILED(hr) && irm);
int bOldMode, b;
_RADIO_CHANGE_REASON c;
hr = irm->lpVtbl->GetSystemRadioState(irm, &bOldMode, &b, &c);
assert(!FAILED(hr));
printf("Old flight-mode state was: %s\n", bOldMode == 0 ? "on" : "off");
/* Set flight mode to the opposite state. */
hr = irm->lpVtbl->SetSystemRadioState(irm, bOldMode == 0 ? 1 : 0);
assert(!FAILED(hr));
irm->lpVtbl->Release(irm);
CoUninitialize();
return 0;
}

Qt - get all opened windows title

how can i check whether a specific window is open or not. I only got part of the window's name. i thinking of using EnumWindows() in QT console app but i get a few errors stating "main.obj:-1: error: unresolved external symbol imp__GetWindowTextW#12 referenced in function "int __stdcall EnumWindowsProc(struct HWND *,long)" (?EnumWindowsProc##YGHPAUHWND__##J#Z)"
Below is my sample code
BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam) {
char buff[255];
if (IsWindowVisible(hWnd)) {
GetWindowText(hWnd, (LPWSTR) buff, 254);
}
return TRUE;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
EnumWindows(EnumWindowsProc, 0);
return 0;
}
That's a linker error rather than a compile error.
You have correctly included windows.h but you also need to add the import libraries to your linker options. All three Win32 functions in your sample code require you to link user32.lib.
EnumWindowsProc is not from Qt, it's a windows API function, you need to include windows.h
I did not use Qt, and the code can pass complie, but the output seems NOT right. Anyway, here's my code
#include <conio.h>
#include <iostream>
#include <windows.h>
using namespace std;
char buff[255];
BOOL CALLBACK EnumWindowsProc(HWND hWnd, long lParam)
{
if (IsWindowVisible(hWnd))
{
GetWindowText(hWnd, (LPWSTR) buff, 254);
}
return TRUE;
}
int main()
{
EnumWindows(EnumWindowsProc, 0);
for(int i = 0; i != 254; ++i)
cout << buff[i];
getch();
return 0;
}
You can use:
Application.OpenForms["FormName"]
To check if the form is open or not.

Resources