I writing small application in pure C++. But now I encourage strange problem. I wanted to add my application to autostart but it not working. I use this code to access to Registry:
BOOL SetKeyData(HKEY hRootKey, WCHAR *subKey, DWORD dwType, WCHAR *value, LPBYTE data, DWORD cbData)
{
HKEY hKey;
if(RegCreateKeyW(hRootKey, subKey, &hKey) != ERROR_SUCCESS)
return FALSE;
LSTATUS status = RegSetValueExW(hKey, value, 0, dwType, data, cbData);
if(status != ERROR_SUCCESS)
{
RegCloseKey(hKey);
return FALSE;
}
RegCloseKey(hKey);
return TRUE;
}
At first I thought that problem is in data that I serve, so i converted WCHAR with path to LPBYTE like this and execute this function in this way:
size_t i;
char *pMBBuffer = (char *)malloc( MAX_PATH );
wcstombs_s(&i, pMBBuffer, MAX_PATH, my_program, MAX_PATH-1 );
SetKeyData(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", REG_SZ, L"zwApplication", (LPBYTE)pMBBuffer, i))
I get status code ERROR_ACCESS_DENIED. Maybe problem is policy in Windows 7, but I thought that I have full access to everything in HKEY_LOCAL_MACHINE. How to solve this problem?
Writing to HKEY_LOCAL_MACHINE requires that your app runs with elevated privileges. Which means your app would require to set this in its manifest file.
Without this, you can only write to HKEY_CURRENT_USER, or read from HKEY_LOCAL_MACHINE - but for your autostart requirement, that would work just as fine.
Related
I try to hook some functions using Microsoft Detours. The method I'm using is CreateRemoteThread + LoadLibrary.
Yet, I've encountered that the exact same code works on notepad.exe, some chrome processes etc., but not on wmplayer.exe(Windows Media Player), Calculator.exe somehow. Is it correct to say that these applications probably tried to prevent this type of DLL injection? I can hardly come up with other possibilities.
Most of these code are copied from the Detours tutorial
The code can be seen and cloned from this repository in case anyone want to experiment them.
DLL:
INT APIENTRY DllMain(HMODULE hDLL, DWORD Reason, LPVOID Reserved)
{
try {
std::ofstream file("D:\\output.txt");
file << "Hello!\n";
file.close();
}
catch (...) {
std::ofstream file("D:\\error.txt");
file << "Hello!\n";
file.close();
}
}
Injector:
int main(void)
{
if (fileExists("D:\\output.txt"))
{
printf("Removing...\n");
remove("D:\\output.txt");
}
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hTool32 = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (Process32First(hTool32, &pe32))
{
while ((Process32Next(hTool32, &pe32)) == TRUE) {
char exeName[] = "Calculator.exe";
//char exeName[] = "notepad.exe";
if (strcmp(pe32.szExeFile, exeName) == 0)
{
printf("Found %s at %d\n", exeName, pe32.th32ProcessID);
char* DirPath = new char[MAX_PATH];
char* FullPath = new char[MAX_PATH];
GetCurrentDirectory(MAX_PATH, DirPath);
sprintf_s(FullPath, MAX_PATH, "%s\\..\\x64\\Debug\\TestDLL.dll", DirPath);
printf("%s File exists: %d\n", FullPath, fileExists(FullPath));
HANDLE hProcess = OpenProcess(
PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, pe32.th32ProcessID);
LPVOID LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
LPVOID LLParam = (LPVOID)VirtualAllocEx(hProcess, NULL, strlen(FullPath),
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
BOOL status = WriteProcessMemory(hProcess, LLParam, FullPath, strlen(FullPath), NULL);
auto handle = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddr,
LLParam, NULL, NULL);
CloseHandle(hProcess);
delete[] DirPath;
delete[] FullPath;
std::cin.get();
}
}
}
CloseHandle(hTool32);
return 0;
}
when the variable exeName is set to "notepad.exe", the file "D:\output.txt" will be created, while setting the variable to "Calculator.exe" won't.
If my guess is correct, is using other injection method(ex. SetWindowsHookEx) the only way I can make these work?
On Windows 10, "Calculator" is Windows App and according to Detours documentation detours doesn't work for Windows App for following reason
Why can't my Windows Store app for Windows 8 include Detours?
Windows Store apps may use only a subset of the Win32 API. Detours
requires several Win32 APIs that are forbidden in for Windows App
Certification. Forbidden APIs used by Detours include VirtualAlloc,
VirtualProtect, and FlushInstructionCache.
As per Microsoft documentation
Windows apps:: All apps installed in C:\Program Files\WindowsApps.
Path of "Calculator" on Windows 10 is
C:\Program
Files\WindowsApps\microsoft.windowscalculator_10.2103.8.0_x64__8wekyb3d8bbwe\Calculator.exe
Personally I think these applications indeed prevented from being injected by the CreateRemoteThread + LoadLibrary method since it's the most basic approach, but this guess needs further proof. After I switched to use the SetWindowsHookEX method in this repository, the DllMain will be called successfully.
I'm trying to get the user that is associated with a PID on windows.
I'm looking at the source for NTop https://github.com/gsass1/NTop as an example.
I can build and debug NTop source on Clion and the following code works correctly.
HANDLE ProcessTokenHandle;
if(OpenProcessToken(Process.Handle, TOKEN_READ, &ProcessTokenHandle)) {
DWORD ReturnLength;
GetTokenInformation(ProcessTokenHandle, TokenUser, 0, 0, &ReturnLength);
if(GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
PTOKEN_USER TokenUserStruct = xmalloc(ReturnLength);
if(GetTokenInformation(ProcessTokenHandle, TokenUser, TokenUserStruct, ReturnLength, &ReturnLength)) {
SID_NAME_USE NameUse;
DWORD NameLength = UNLEN;
TCHAR DomainName[MAX_PATH];
DWORD DomainLength = MAX_PATH;
LookupAccountSid(0, TokenUserStruct->User.Sid, Process.UserName, &NameLength, DomainName, &DomainLength, &NameUse);
// FIXME: we cut user name here for display purposes because something like %9.9s does not work with MS's vsprintf function?
Process.UserName[9] = 0;
}
free(TokenUserStruct);
}
CloseHandle(ProcessTokenHandle);
}
When trying the same thing using rust winapi I get ERROR_NOACCESS every time no matter what I do.
Here's some example code that returns 0 as response code from OpenProcessToken and GetLastError will be ERROR_NOACCESS. It doesn't matter whether or not I run the program as administrator or not.
let pid: u32 = 8664; // process that is owned by me but can be any process, it will never work
let process_handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
let mut process_token_handle: PHANDLE = null_mut();
let s = OpenProcessToken(process_handle, TOKEN_READ, process_token_handle);
let last_error = GetLastError();
Anyone have any idea why this code would work in NTop using the C api and not work using rust winapi?
I'm trying to write a program that uses CreateRemoteThread to inject a dll.
The problem is that CreateRemoteThread is refusing to work. GetLastError() is returning 5 which is ERROR_ACCESS_DENIED. I cant figure why!
I am working from this video http://www.youtube.com/watch?v=H3O3hmXkt1I .
#include <iostream>
#include <direct.h>
#include <Windows.h>
#include <TlHelp32.h>
using namespace std;
char* GetCurrentDir()
{
char* szRet = (char*)malloc(MAX_PATH);
_getcwd(szRet, MAX_PATH);
return szRet;
}
LPCTSTR SzToLPCTSTR(char* szString)
{
LPTSTR lpszRet;
size_t size = strlen(szString)+1;
lpszRet = (LPTSTR)malloc(MAX_PATH);
mbstowcs_s(NULL, lpszRet, size, szString, _TRUNCATE);
return lpszRet;
}
void WaitForProcessToAppear(LPCTSTR lpcszProc, DWORD dwDelay)
{
HANDLE hSnap;
PROCESSENTRY32 peProc;
BOOL bAppeared = FALSE;
while(!bAppeared)
{
if((hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) != INVALID_HANDLE_VALUE)
{
peProc.dwSize = sizeof(PROCESSENTRY32);
if(Process32First(hSnap, &peProc))
while(Process32Next(hSnap, &peProc) && !bAppeared)
if(!lstrcmp(lpcszProc, peProc.szExeFile))
bAppeared = TRUE;
}
CloseHandle(hSnap);
Sleep(dwDelay);
}
}
DWORD GetProcessIdByName(LPCTSTR lpcszProc)
{
HANDLE hSnap;
PROCESSENTRY32 peProc;
DWORD dwRet = -1;
if((hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)) != INVALID_HANDLE_VALUE)
{
peProc.dwSize = sizeof(PROCESSENTRY32);
if(Process32First(hSnap, &peProc))
while(Process32Next(hSnap, &peProc))
if(!lstrcmp(lpcszProc, peProc.szExeFile))
dwRet = peProc.th32ProcessID;
}
CloseHandle(hSnap);
return dwRet;
}
BOOL InjectDll(DWORD dwPid, char* szDllPath)
{
DWORD dwMemSize;
HANDLE hProc;
LPVOID lpRemoteMem, lpLoadLibrary;
BOOL bRet = FALSE;
if((hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPid)) != NULL)
{
dwMemSize = strlen(szDllPath);
if((lpRemoteMem = VirtualAllocEx(hProc, NULL, dwMemSize, MEM_COMMIT, PAGE_READWRITE)) != NULL)
if(WriteProcessMemory(hProc, lpRemoteMem, szDllPath, dwMemSize, NULL))
{
lpLoadLibrary = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
if(CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)lpLoadLibrary, lpRemoteMem, 0, NULL) != NULL)
{
bRet = TRUE;
}
cout << GetLastError();
}
}
CloseHandle(hProc);
return bRet;
}
int main()
{
char szProc[MAX_PATH], szDll[MAX_PATH];
char* szDllPath = (char*)malloc(MAX_PATH);
LPTSTR lpszProc = NULL;
for(;;)
{
cout << "Process: ";
cin >> szProc;
cout << "DLL: ";
cin >> szDll;
szDllPath = GetCurrentDir();
strcat_s(szDllPath, MAX_PATH, "\\");
strcat_s(szDllPath, MAX_PATH, szDll);
cout << "Waiting for process.. ." << szDllPath << " " << szDll << endl;
WaitForProcessToAppear(SzToLPCTSTR(szProc), 100);
if(InjectDll(GetProcessIdByName(SzToLPCTSTR(szProc)), szDllPath))
cout << "Injection Succeeded!" << endl;
else
cout << "Injection Failed!" << endl;
cout << "\n";
}
return 0;
After a fair amount of googling I cant find a reason why this should not be working.
Does CreateRemoteThread not work under Windows 7 ?
If it does, have I made any obvious mistakes ?
The reason it fails is because your code is 32-bit and your target process is 64-bit.
It doesn't matter how many privileges you own. Windows won't let that happen.
I had the same problem. Either you spawn a system 32-bit exe and inject that or port your code to 64-bit (which means it won't work on 32-bit systems).
EDIT
A long time ago, I found a nice way of injecting code into and from any processor mode-target. It involves dynamically switching the processor mode to that of (any)the target. Dubbed "heaven's gate". To do this you have to use inline assembly. So basically, you can have both 64-bit and 32-bit code in a 32-bit exe, detect if the machine is 64-bit, then jump into 64-bit mode and run the 64-bit code. You'd then walk the imports to find ntdll and load 64-bit kernel.dll and other libraries.
Link: https://www.google.com/search?q=heaven's+gate+windows
Immediate problems I see are that you are not getting the access token which should be done as so:
HANDLE hToken;
TOKEN_PRIVILEGES tp;
HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId() );
tp.PrivilegeCount = 1;
LookupPrivilegeValue( NULL, _T("SeDebugPrivilege"), &tp.Privileges[0].Luid );
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
OpenProcessToken( hProcess, TOKEN_ADJUST_PRIVILEGES, &hToken );
AdjustTokenPrivileges( hToken, FALSE, &tp, NULL, NULL, NULL );
CloseHandle( hToken );
I don't have time to look through all your code right now, but here is something I ripped out of one of my previous projects:
// returns open process handle
HANDLE InjectDLL( DWORD dwPID, LPCWSTR szDLLPath, HMODULE* lphInjected ) {
int cszDLL;
LPVOID lpAddress;
HMODULE hMod;
HANDLE hThread;
HANDLE hProcess = OpenProcess( PROCESS_CREATE_THREAD |
PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION |
PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, dwPID );
if( hProcess == NULL ) {
return NULL;
}
cszDLL = ( wcslen( szDLLPath ) + 1 ) * sizeof( WCHAR );
// Injection
lpAddress = VirtualAllocEx( hProcess, NULL, cszDLL, MEM_COMMIT, PAGE_EXECUTE_READWRITE );
if( lpAddress == NULL ) {
return NULL;
}
WriteProcessMemory( hProcess, lpAddress, szDLLPath, cszDLL, NULL );
hMod = GetModuleHandle( L"kernel32.dll" );
if( hMod == NULL ) {
return NULL;
}
hThread = CreateRemoteThread( hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE)( GetProcAddress( hMod,
"LoadLibraryW" ) ), lpAddress, 0, NULL );
// Locate address our payload was loaded
if( hThread != 0 ) {
WaitForSingleObject( hThread, INFINITE );
GetExitCodeThread( hThread, ( LPDWORD )lphInjected );
VirtualFreeEx( hProcess, lpAddress, 0, MEM_RELEASE );
CloseHandle( hThread );
}
return hThread != 0 ? hProcess : NULL;
}
See if it helps. Will look again later.
OK, your code is likely to fail in windows 7 and Vista because of "Protected processes", that is, processes which only can be manipulated by other Protected Processes, like explorer.exe, etc... In Windows 7 x32 there is a way: since you are able to load unsigned drivers,... well, you are done (search for Alex Ionescu in google). In Windows 7 x64, though, you can't (duh!)
"The fourth parameter of the CreateRemoteThread() is an address. In your case it is the LoadLibraryA address. However, in windows 7, Kernel32.dll/LoadLibraryA base address will various in different process;"
Well, that's not remotely true, because DLLs are shared at the same addresses in every process, despite ASLR. DLLs can be rebased, though, but you can call GetProcAddress before calling CreateRemoteThread, so it is very unlikely that the DLL will get rebased meanwhile.
I think CreateRemoteThread() dll injection method can not work in windows 7.
The fourth parameter of the CreateRemoteThread() is an address. In your case it is the LoadLibraryA address. However, in windows 7, Kernel32.dll/LoadLibraryA base address will various in different process; Therefore, the CreateRemoteThread() will not work since the address is not what u expected. This is my own opinion, hope it will help. :)
CreateRemoteThread function does not work in Win Vista/7. You have to use NTCreateThread function,which is undocumented, for that.
TLDR : your code is okey , change the Visual Studio debug/compile target to x64.
I've faced the same problem before, your code is Okey, The problem is , the Visual Studio(or any sane person) execute its programs in x86 mode (32bit) by default, because it would be nice to compile your program in a way that runs in both x86 or x64 architecture but not in the process injection scenario! because of its system calls.
In the code injection case, you should change the build and debug setting of the VS to compile/debug for x64 processor in properties of your project in the project explorer,
or if you cross compiling your program, you should use x64 compiler.
If you are looking for global process injection method, there was a method called Heaven’s Gate or The 0x33 Segment Selector, which was used in Vawtrak banking malware.
You could see this link about Heaven’s Gate method, which says:
In other words, it gives one the ability to create “naked” 64-bit
code, which will be able to run covertly, including issuing system
calls, without the majority of products able to intercept and/or
introspect its execution
I am trying to find a programmatic way to tell if a binary is x86, x64, or ia64.
Platform: Windows.
Language: c/c++.
Background: Before trying to load a third-party dll, I need to find out its bitness.
Appreciate any pointers.
For EXEs
use GetBinaryType(...)
Here is same question for manged exe.
For DLLs (and EXEs)
Use the ImageNtHeader(...) to get the PE data of the file and then check the IMAGE_FILE_HEADER.Machine field.
Here is some code I found using Google Code Search
No Cleanup and NO error checking
// map the file to our address space
// first, create a file mapping object
hMap = CreateFileMapping(
hFile,
NULL, // security attrs
PAGE_READONLY, // protection flags
0, // max size - high DWORD
0, // max size - low DWORD
NULL ); // mapping name - not used
// next, map the file to our address space
void* mapAddr = MapViewOfFileEx(
hMap, // mapping object
FILE_MAP_READ, // desired access
0, // loc to map - hi DWORD
0, // loc to map - lo DWORD
0, // #bytes to map - 0=all
NULL ); // suggested map addr
peHdr = ImageNtHeader( mapAddr );
I open-sourced a project on Github that checks for VC++ redistributable DLLs specifically and there's a code snippet I created based off of the function in Shay's answer that successfully finds, loads, and inspects DLLs for x86 / x64 compatibility.
Full code snippet below:
/******************************************************************
Function Name: CheckProductUsingCurrentDirectory
Description: Queries the current working directory for a given binary.
Inputs: pszProductFolderToCheck - the product name to look up.
pBinaryArchitecture - the desired processor architecture
of the binary (x86, x64, etc..).
Results: true if the requested product is installed
false otherwise
******************************************************************/
bool CheckProductUsingCurrentDirectory(const LPCTSTR pszProductBinaryToCheck, Architecture pBinaryArchitecture){
bool bFoundRequestedProduct = false;
//Get the length of the buffer first
TCHAR currentDirectory[MAX_PATH];
DWORD currentDirectoryChars = GetCurrentDirectory(MAX_PATH, currentDirectory);
//exit if couldn't get current directory
if (currentDirectoryChars <= 0) return bFoundRequestedProduct;
TCHAR searchPath[MAX_PATH];
//exit if we couldn't combine the path to the requested binary
if (PathCombine(searchPath, currentDirectory, pszProductBinaryToCheck) == NULL) return bFoundRequestedProduct;
WIN32_FIND_DATA FindFileData;
HANDLE hFind= FindFirstFile(searchPath, &FindFileData);
//exit if the binary was not found
if (hFind == INVALID_HANDLE_VALUE) return bFoundRequestedProduct;
HANDLE hFile = CreateFile(searchPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, NULL);
if (hFile == INVALID_HANDLE_VALUE) goto cleanup;
HANDLE hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY | SEC_IMAGE, 0, 0, pszProductBinaryToCheck);
if (hMapping == INVALID_HANDLE_VALUE) goto cleanup;
LPVOID addrHeader = MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0);
if (addrHeader == NULL) goto cleanup; //couldn't memory map the file
PIMAGE_NT_HEADERS peHdr = ImageNtHeader(addrHeader);
if (peHdr == NULL) goto cleanup; //couldn't read the header
//Found the binary, AND its architecture matches. Success!
if (peHdr->FileHeader.Machine == pBinaryArchitecture){
bFoundRequestedProduct = true;
}
cleanup: //release all of our handles
FindClose(hFind);
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
if (hMapping != INVALID_HANDLE_VALUE)
CloseHandle(hMapping);
return bFoundRequestedProduct;
}
This question and Shay's answer were helpful to me while I was creating this, so I thought I'd post the project here.
You can check the PE header yourself to read the IMAGE_FILE_MACHINE field. Here's a C# implementation that shouldn't be too hard to adapt to C++.
How do I determine the (local-) path for the "Program Files" directory on a remote computer? There does not appear to any version of SHGetFolderPath (or related function) that takes the name of a remote computer as a parameter.
I guess I could try to query HKLM\Software\Microsoft\Windows\CurrentVersion\ProgramFilesDir using remote-registry, but I was hoping there would be "documented" way of doing it.
Many of the standard paths require a user to be logged in, especially the SH* functions as those are provided by the "shell", that is, Explorer. I suspect the only way you're going to get the right path is through the registry like you already mentioned.
This is what I ended up doing: (pszComputer must be on the form "\\name". nPath is size of pszPath (in TCHARs))
DWORD GetProgramFilesDir(PCTSTR pszComputer, PTSTR pszPath, DWORD& nPath)
{
DWORD n;
HKEY hHKLM;
if ((n = RegConnectRegistry(pszComputer, HKEY_LOCAL_MACHINE, &hHKLM)) == ERROR_SUCCESS)
{
HKEY hWin;
if ((n = RegOpenKeyEx(hHKLM, _T("Software\\Microsoft\\Windows\\CurrentVersion"), 0, KEY_READ, &hWin)) == ERROR_SUCCESS)
{
DWORD nType, cbPath = nPath * sizeof(TCHAR);
n = RegQueryValueEx(hWin, _T("ProgramFilesDir"), NULL, &nType, reinterpret_cast<PBYTE>(pszPath), &cbPath);
nPath = cbPath / sizeof(TCHAR);
RegCloseKey(hWin);
}
RegCloseKey(hHKLM);
}
return n;
}