Dll Injector not detecting Dll - c++

I recently coded an injector where as long as the dll is in the same directory as the exe injector it will inject but even when the dLL is in the same path it still returns with the error file not found.
Very new to c++ so not exactly sure how to fix it, only this I know that the problem must lie in the dll_name
The c++ code is listed here
#include <Windows.h>
#include <string>
#include <thread>
#include <libloaderapi.h>
using namespace std;
void get_proc_id(const char* window_title, DWORD &process_id)
{
GetWindowThreadProcessId(FindWindow(NULL, window_title), &process_id); // Find Process ID by using title of window
}
void error(const char* error_title, const char* error_message)
{
MessageBox(NULL, error_message, error_title, NULL);
exit(-1);
//if error occurs output false
}
bool file_exists(string file_name) // Makes sure file exists
{
struct stat buffer;
return (stat(file_name.c_str(), &buffer) == 0);
//Information goes through buffer if = 0 , it worked
//Creates random buffer of stat sturc doesnt matter what goes in - making sure function is successful, gets info about file and checks if it workeed
}
int main()
{
DWORD proc_id = NULL;
char dll_path[MAX_PATH];
const char* dll_name = "TestDll2.dll"; //Name of Dll
const char* window_title = "Untitled - Paint"; //Must Match Title Name
if (!file_exists(dll_name));
{
error("file_exists", "File does not exist");
}
if (!GetFullPathName(dll_name, MAX_PATH, dll_path, nullptr))
{
error("GetFullPathName", "Failed to get full file path");
}
get_proc_id(window_title, proc_id);
if (proc_id == NULL)
{
error("get_proc_id", "Failed to get process ID");
}
HANDLE h_process = OpenProcess(PROCESS_ALL_ACCESS, NULL, proc_id);
if (!h_process)
{
error("OpenProcess", "Failed to open handle to process");
}
void* allocated_memory = VirtualAllocEx(h_process, nullptr, MAX_PATH, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); //Calling Virutal Allocation, passing handle to process - reserving memory by going thru reserve and need to commit to it so we can write
if (!allocated_memory)
{
error("VirtualAllocEx", "Failed to allocate memory");
}
if (!WriteProcessMemory(h_process, allocated_memory, dll_path, MAX_PATH, nullptr)) // Write DLL path into the target program
{
error("WriteProcessMemory", "Failed to write process memory");
}
//If above works we call loadlibarya which is where the dll is stored
HANDLE h_thread = CreateRemoteThread(h_process, nullptr, NULL, LPTHREAD_START_ROUTINE(LoadLibraryA), allocated_memory, NULL, nullptr);
if (!h_thread)
{
error("CreateRemoteThread", "Failed to create remote thread");
}
CloseHandle(h_process);
VirtualFreeEx(h_process, allocated_memory, NULL, MEM_RELEASE);
MessageBox(0, "Successfully Injected!", "Sucess", 0);
} ```

Try to use C++ STL function or Windows native API:
#include <string>
#include <filesystem>
#include <Shlwapi.h>
#pragma comment(lib, "Shlwapi.lib")
bool IsExists(const std::string &FilePathName)
{
return std::filesystem::exists(FilePathName);
}
bool IsExists(const std::string &FilePathName)
{
return PathFileExistsA(FilePathName.c_str());
}

The file is being searched in the current directory, not in the directory of the exe file. These might not be the same. You have to find the path to the exe file in order to search for files in its directory. On Windows you could do something like this:
#include <psapi.h>
// ....
HANDLE Handle = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE, GetCurrentProcessId() );
if ( Handle ) {
TCHAR buffer[MAX_PATH];
if ( GetModuleFileNameEx( Handle, 0, buffer, MAX_PATH ) ) {
std::filesystem::path exePath( buffer ); // TODO this might need encoding conversion
auto exeDir = exePath.parent_path();
auto dllPath = exeDir / "TestDll2.dll";
if ( std::filesystem::exists( dllPath ) ) {
// ...
}
}
}
You can also try GetProcessImageFileName if GetModuleFileNameEx does not work. Apparently it does not work in 32-bit applications on a 64-bit system (see comments in this answer).

Related

How to save a persistent value for application access across multiple runs?

As the title states, I would like to store a variable (which will always be an positive integer < 10,000) for my application to access and process as needed across multiple runs.
My current implementation simply saves the value to a file, in the current directory, and then reads it in when needed.
#include<fstream>
int x = 5;
std::ofstream write_file(file_handle);
write_file << value;
write_file.close();
However, I'm not too keen on the idea of having an orphaned text file if the user decides to place the .exe on their desktop.
So, what other options do I have to store the value?
I'm primarily concerned with Windows 8+.
There is nothing wrong with using a file, but you don't have to (and should not) store it in the same folder as the .exe file, as it may not work depending on where the .exe is located (for instance, non-admins can't write to Program Files).
Windows sets aside special folders in the user's profile just for application-generated data, so you should store the file in one of those folders instead. Use the Win32 SHGetFolderPath() or SHGetKnownFolderPath() function to discover where those special folders are located, and then you should create a sub-folder for your application's use (you can even use SHGetFolderPathAndSubDir() for that purpose).
For example:
#include <fstream>
#include <filesystem>
#include <windows.h>
#include <shlobj.h>
namespace fs = std::filesystem;
fs::path pathToMyValueFile()
{
WCHAR szPath[MAX_PATH];
if (SHGetFolderPathAndSubDirW(NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, L"MyApp", szPath) != S_OK) {
throw ...;
}
return fs::path(szPath) / L"value.dat";
/* alternatively:
if (SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL, SHGFP_TYPE_CURRENT, szPath) != S_OK)
throw ...;
fs::path folder = fs::path(szPath) / L"MyApp";
fs::create_directory(folder);
return folder / L"value.dat";
*/
}
...
int value = 0;
std::ifstream read_file(pathToMyValueFile());
if (read_file.is_open()) {
read_file >> value;
read_file.close();
}
...
int value = 5;
std::ofstream write_file(pathToMyValueFile());
if (write_file.is_open()) {
write_file << value;
write_file.close();
}
In the future, if the user ever uninstalls your app, be sure to delete that subfolder.
Otherwise, you can store the value in the Windows Registry instead. Create a new key for your application under HKEY_CURRENT_USER\Software or HKEY_LOCAL_MACHINE\Software as needed, and then you can create values inside that key.
For example:
#include <fstream>
#include <windows.h>
int readMyValue()
{
int value;
HKEY hKey;
LSTATUS lRes = RegOpenKeyExA(HKEY_CURRENT_USER, "Software\\MyApp", 0, KEY_QUERY_VALUE, &hKey);
if (lRes == ERROR_SUCCESS)
{
DWORD size = sizeof(value);
lRes = RegQueryValueExA(hKey, "Value", NULL, NULL, (LPBYTE)&value, size);
RegCloseKey(hKey);
}
if (lRes != ERROR_SUCCESS)
{
if (lRes != ERROR_FILE_NOT_FOUND)
throw ...;
value = 0;
}
return value;
}
void saveMyValue(int value)
{
HKEY hKey;
LSTATUS lRes = RegCreateKeyExA(HKEY_CURRENT_USER, "Software\\MyApp", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_SET_VALUE, NULL, &hKey, NULL);
if (lRes == ERROR_SUCCESS)
{
DWORD size = sizeof(value);
lRes = RegSetValueExA(hKey, "Value", 0, REG_DWORD, (BYTE*)&value, sizeof(value));
RegCloseKey(hKey);
}
if (lRes != ERROR_SUCCESS)
throw ...;
/* alternatively:
if (RegSetKeyValueA(HKEY_CURRENT_USER, "Software\\MyApp", "Value", REG_DWORD, &value, sizeof(value)) != ERROR_SUCCESS)
throw ...;
*/
}
...
int value = readMyValue();
...
int value = 5;
saveMyValue(value);
If your app is uninstalled later, be sure to delete the Registry key.

Hook and unhook one file DLL

I try hook file DLL into console app. This code
#include "pch.h"
#include <vector>
#include <string>
#include <windows.h>
#include <Tlhelp32.h>
using std::vector;
using std::string;
int main(void)
{
while (true)
{
vector<string>processNames;
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
HANDLE hTool32 = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
BOOL bProcess = Process32First(hTool32, &pe32);
if (bProcess == TRUE)
{
while ((Process32Next(hTool32, &pe32)) == TRUE)
{
processNames.push_back(pe32.szExeFile);
if (strcmp(pe32.szExeFile, "ConsoleApplication4.exe") == 0)
{
char* DirPath = new char[MAX_PATH];
char* FullPath = new char[MAX_PATH];
GetCurrentDirectory(MAX_PATH, DirPath);
sprintf_s(FullPath, MAX_PATH, "%s\\..\\ConsoleApplication1\\ConsoleApplication1.dll", DirPath);
FILE *pFile;
if (fopen_s(&pFile, FullPath, "r") || !pFile)
{
OutputDebugString("[Hook] File name or file does not exist");
OutputDebugString(FullPath);
return -1;
}
fclose(pFile);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
if (!hProcess)
{
OutputDebugString("[Hook] Open process fail");
return -1;
}
//attach
LPVOID LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
if (!LoadLibraryAddr)
{
OutputDebugString("[Hook] Load LoadLibraryA fail");
return -1;
}
LPVOID LLParam = (LPVOID)VirtualAllocEx(hProcess, NULL, strlen(FullPath), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if (!WriteProcessMemory(hProcess, LLParam, FullPath, strlen(FullPath), NULL))
{
OutputDebugString("[Hook] Write process fail");
return -1;
}
HANDLE hHandle = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, LLParam, NULL, NULL);
if (!hHandle)
{
OutputDebugString("[Hook] Hooked fail");
return -1;
}
system("pause");
//detach
LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "FreeLibrary");
if (!LoadLibraryAddr)
{
OutputDebugString("[Hook] Load FreeLibrary fail");
return -1;
}
hHandle = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibraryAddr, LLParam, NULL, NULL);
if (!hHandle)
{
OutputDebugString("[Hook] detach fail");
return -1;
}
CloseHandle(hProcess);
delete[] DirPath;
delete[] FullPath;
system("pause");
return 0;
}
}
}
CloseHandle(hTool32);
}
return 0;
}
I have some question for this:
- Why this code can not detach file dll ?
- Why I change LoadLibraryA -> LoadLibrary : load LoadLibrary fail ?
- Why I change LoadLibraryA -> LoadLibraryW : file dll no attach ?
- Code in Mutibyte run is good, but convert to Unicode, file dll no attach ?
Thanks,
The reason this works in multibyte but won't compile with unicode character set is because you're passing a regular c string which is a regular char array. When you set your build type to use multibyte LoadLibrary() resolves to the ansi version which is LoadLibraryA(). If you want to use Unicode in your project properties it will resolve to LoadLibraryW() and you will need to pass a unicode char array, typically wchar_t[].
Even while compiling in unicode mode, you can still call LoadLibraryA() and pass a c string but you must specifically call the A (ansi) version of the function rather than rely on the #ifdef preprocessor statements which resolve them for you.

GetFullPathName wont get DLL Path

I am trying to load a DLL from resource and use SetWindowsHook to inject DLL to all Process GetFullPathName doesnt Seem to Work in this case, Now i am asking what would I do to get the DLL Path in this case, My code looks like this. I am new to using This and hence i cannot seem to get the DLL Path
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>
#include "resource.h"
void ExtractnRun()
{
char* name = getenv("USERNAME");
char info[1500];
char aNewFile[1500];
sprintf(info,"C:\\Users\\%s\\AppData\\Local\\MicroSoftX",name);
//_mkdir(info);
if (CreateDirectoryA(info, NULL))
{
MessageBoxA(NULL, "Directory Created", "", MB_OK);
}
// Extract From Resource
HRSRC hrsrc = FindResource(0, MAKEINTRESOURCE(IDR_DLL21),"DLL2");
DWORD size = SizeofResource(0, hrsrc);
PVOID buff = LockResource(LoadResource(0, hrsrc));
DWORD dwBytesToWrite = (DWORD)strlen((char*)buff);
DWORD dwBytesWritten = 0;
sprintf(aNewFile, "C:\\Users\\%s\\AppData\\Local\\MicroSoftX\\mshelp.dll", name);
HANDLE hFile = CreateFileA(aNewFile, GENERIC_WRITE, 0, NULL,CREATE_ALWAYS ,FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile)
{
MessageBoxA(NULL, "File Created!", "", MB_OK);
}
/*FILE* f = fopen(aNewFile, "wb");
fwrite(buff,1,size,f);
fclose(f);
*/
if (WriteFile(hFile, buff, size, &dwBytesWritten, NULL))
{
MessageBoxA(NULL, "Data Written to DLL", "", MB_OK);
}
/*STARTUPINFOA si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
*/
char dll[MAX_PATH];
GetFullPathName((LPCSTR)hFile, MAX_PATH, dll, NULL); // Shows Error here Cannot get Full Path of DLL
printf("%s\n",dll);
HMODULE MYdll = LoadLibrary(dll);
if (MYdll == NULL)
{
printf("dll cannot be found!\n");
getchar();
printf("DLL : %s", MYdll);
}
HOOKPROC addr = (HOOKPROC)GetProcAddress(MYdll, "SayHelloWorld");
if (addr == NULL)
{
printf("Cannot find Address!\n");
getchar();
}
HHOOK handle = SetWindowsHookEx(WH_KEYBOARD, addr, MYdll, 0);
if (handle == NULL)
{
printf("Hook Failed!\n");
getchar();
}
printf("Program Hooked!\n");
getchar();
UnhookWindowsHookEx(handle);
//printf("%s\n",dll);
system("PAUSE");
}
int main()
{
ExtractnRun();
return 0;
}
The Exception Error i get looks like this :
Exception thrown at 0x7764171A (ntdll.dll) in ResourceExample.exe:
0xC0000005: Access violation reading location 0x0000009C.
If there is a handler for this exception, the program may be safely
continued.
What am I not getting correctly?
You can not pass the file handler to the "GetFullPahtName". It should be file name to find full path.
GetFullPathName((LPCSTR)hFile, MAX_PATH, dll, NULL);
Please refer the below link for more details.
https://msdn.microsoft.com/en-us/library/windows/desktop/aa364963(v=vs.85).aspx

Is there any way of stopping _popen opening a dos window?

I am using _popen to start a process to run a command and gather the output
This is my c++ code:
bool exec(string &cmd, string &result)
{
result = "";
FILE* pipe = _popen(cmd.c_str(), "rt");
if (!pipe)
return(false);
char buffer[128];
while(!feof(pipe))
{
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
_pclose(pipe);
return(true);
}
Is there any way of doing this without a console window opening (as it currently does at the _popen statement)?
On Windows, CreateProcess with a STARTUPINFO structure that has dwFlags to include STARTF_USESSHOWWINDOW. Then setting STARTUPINFO.dwFlags to SW_HIDE will cause the console window to be hidden when triggered. Example code (which may be poorly formatted, and contains a mix of C++ and WinAPI):
#include <windows.h>
#include <iostream>
#include <string>
using std::cout;
using std::endl;
void printError(DWORD);
int main()
{
STARTUPINFOA si = {0};
PROCESS_INFORMATION pi = { 0 };
si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
si.wShowWindow = SW_HIDE;
BOOL result = ::CreateProcessA("c:/windows/system32/notepad.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
if(result == 0) {
DWORD error = ::GetLastError();
printError(error);
std::string dummy;
std::getline(std::cin, dummy);
return error;
}
LPDWORD retval = new DWORD[1];
::GetExitCodeProcess(pi.hProcess, retval);
cout << "Retval: " << retval[0] << endl;
delete[] retval;
cout << "Press enter to continue..." << endl;
std::string dummy;
std::getline(std::cin, dummy);
return 0;
}
void printError(DWORD error) {
LPTSTR lpMsgBuf = nullptr;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
error,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
cout << reinterpret_cast<char*>(lpMsgBuf) << endl;
LocalFree(lpMsgBuf);
}
As far as I know, you can't1: you are starting a console application (cmd.exe, that will run the specified command), and Windows always creates a console window when starting a console application.
although, you can hide the window after the process started, or even create it hidden if you pass the appropriate flags to CreateProcess; problem is, _popen do not pass these flags, so you have to use the Win32 APIs instead of _popen to create your pipe.
[Final Edit]
a similar SO question merges everything said above and gets you your output
C++ popen command without console
[Edited again]
erk. sorry I got excited about spawning processes. I reread your q. and apart from the extra window you're actually trying to get the processes's stdout/stderr. I'd just like to add that for that purpose, all my suggestions are sadly irrelevant. but I'll leave them here for reference.
[Edited]
For no good specific reason (except that "open" works for both windows and macs), I use ShellExecute for spawning processes rather than CreateProcess. I'll research that later..but here is my StartProcess function.
Hidden or Minimized seem to produce the same result. the cmd window does come into being but it is minimized and doesn't ever pop up on the desktop which might be your primary goal.
#if defined(PLATFORM_WIN32)
#include <Windows.h>
#include <shellapi.h>
#elif defined(PLATFORM_OSX)
#include <sys/param.h>
#endif
namespace LGSysUtils
{
// -----------------------------------------------------------------------
// pWindow : {Optional} - can be NULL
// pOperation : "edit", "explore", "find", "open", "print"
// pFile : url, local file to execute
// pParameters : {Optional} - can be NULL otherwise a string of args to pass to pFile
// pDirectory : {Optional} - set cwd for process
// type : kProcessWinNormal, kProcessWinMinimized, kProcessWinMaximized, kProcessHidden
//
bool StartProcess(void* pWindow, const char* pOperation, const char* pFile, const char* pParameters, const char* pDirectory, LGSysUtils::eProcessWin type)
{
bool rc = false;
#if defined(PLATFORM_WIN32)
int showCmd;
switch(type)
{
case kProcessWinMaximized:
showCmd = SW_SHOWMAXIMIZED;
break;
case kProcessWinMinimized:
showCmd = SW_SHOWMINIMIZED;
break;
case kProcessHidden:
showCmd = SW_HIDE;
break;
case kProcessWinNormal:
default:
showCmd = SW_NORMAL;
}
int shellRC = (int)ShellExecute(reinterpret_cast<HWND>(pWindow), pOperation,pFile,pParameters,pDirectory,showCmd);
//Returns a value greater than 32 if successful, or an error value that is less than or equal to 32 otherwise.
if( shellRC > 32 )
{
rc = true;
}
#elif defined(PLATFORM_OSX)
char cmd[1024];
sprintf(cmd, "%s %s", pOperation, pFile);
int sysrc = system( cmd );
dbPrintf("sysrc = %d", sysrc);
rc = true;
#endif
return rc;
}
}
[and previously mentioned]
If you are in control of the source code for the application that is launched, you could try adding this to the top of your main.cpp (or whatever you have named it)
// make this process windowless/aka no console window
#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
You could also feed those options to the linker directly. The above is easier to play with for different build configurations imho.

How to get the process name in C++

How do I get the process name from a PID using C++ in Windows?
I guess the OpenProcess function should help, given that your process possesses the necessary rights. Once you obtain a handle to the process, you can use the GetModuleFileNameEx function to obtain full path (path to the .exe file) of the process.
#include "stdafx.h"
#include "windows.h"
#include "tchar.h"
#include "stdio.h"
#include "psapi.h"
// Important: Must include psapi.lib in additional dependencies section
// In VS2005... Project > Project Properties > Configuration Properties > Linker > Input > Additional Dependencies
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE Handle = OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE,
8036 /* This is the PID, you can find one from windows task manager */
);
if (Handle)
{
TCHAR Buffer[MAX_PATH];
if (GetModuleFileNameEx(Handle, 0, Buffer, MAX_PATH))
{
// At this point, buffer contains the full path to the executable
}
else
{
// You better call GetLastError() here
}
CloseHandle(Handle);
}
return 0;
}
You can obtain the process name by using the WIN32 API GetModuleBaseName after having the process handle. You can get the process handle by using OpenProcess.
To get the executable name you can also use GetProcessImageFileName.
All the above methods require psapi.dll to be loaded (Read the remarks section) and iterating through process snapshot is an option one should not even consider for getting a name of the executable file from an efficiency standpoint.
The best approach, even according to MSDN recommendation, is to use QueryFullProcessImageName.
std::string ProcessIdToName(DWORD processId)
{
std::string ret;
HANDLE handle = OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION,
FALSE,
processId /* This is the PID, you can find one from windows task manager */
);
if (handle)
{
DWORD buffSize = 1024;
CHAR buffer[1024];
if (QueryFullProcessImageNameA(handle, 0, buffer, &buffSize))
{
ret = buffer;
}
else
{
printf("Error GetModuleBaseNameA : %lu", GetLastError());
}
CloseHandle(handle);
}
else
{
printf("Error OpenProcess : %lu", GetLastError());
}
return ret;
}
If you are trying to get the executable image name of a given process, take a look at GetModuleFileName.
Check out the enumprocess functions in the tool help library:
http://msdn.microsoft.com/en-us/library/ms682629(v=vs.85).aspx
Good example # http://msdn.microsoft.com/en-us/library/ms682623(v=vs.85).aspx
Try this function :
std::wstring GetProcName(DWORD aPid)
{
PROCESSENTRY32 processInfo;
processInfo.dwSize = sizeof(processInfo);
HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (processesSnapshot == INVALID_HANDLE_VALUE)
{
std::wcout << "can't get a process snapshot ";
return 0;
}
for(BOOL bok =Process32First(processesSnapshot, &processInfo);bok; bok = Process32Next(processesSnapshot, &processInfo))
{
if( aPid == processInfo.th32ProcessID)
{
std::wcout << "found running process: " << processInfo.szExeFile;
CloseHandle(processesSnapshot);
return processInfo.szExeFile;
}
}
std::wcout << "no process with given pid" << aPid;
CloseHandle(processesSnapshot);
return std::wstring();
}