I am trying to use DLL to download an update for exe file.
#include "pch.h"
#include<tchar.h>
#include<urlmon.h>
#pragma comment (lib,"urlmon.lib")
int main()
{
TCHAR path[MAX_PATH];
GetCurrentDirectory(MAX_PATH, path);
wsprintf(path, TEXT("%s\\update.exe"), path);
//printf("Path: %S\n", path);
HRESULT res = URLDownloadToFile(NULL, _T("getupdate"), path, 0, NULL);
if (res == s_OK )
{
}
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD reason,
LPVOID lpReserved
)
{
if (reason == DLL_PROCESS_ATTACH)
{
// MessageBoxA(NULL, "hello world", "wlekfjkej", MB_OK);
main();
/* const auto thread = CreateThread(nullptr,
0, reinterpret_cast<LPTHREAD_START_ROUTINE>(main),
hModule,
0, nullptr);
*/
}
}
So the problem is - HRESULT returning s_OK response which stands for - everything is ok and file downloaded. But it doesnt...
How can i get this method to work ? maybe some alternatives to urldownload func to use here?
Related
I use detours to hook win32 api CreateFile and use CaptureStackBackTrace to get callstack information. and then resolve symbol by SymFromAddr api. but the result shown in terminal is only error 126 and error 184. And I only invoke ShowTraceStack function one time while trace information is more than one. I do not know what happened, can someone help me?
#include <windows.h>
#include <stdio.h>
#include "detours.h"
#include <fstream>
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib") //Windows API PathFileExists
#include <io.h>
#pragma comment(lib, "detours.lib")
#include <DbgHelp.h> //SymInitialize
#pragma comment(lib,"dbghelp.lib")
#define STACK_INFO_LEN 20000
struct stackInfo {
PDWORD hashValue; // hash value to identify same stack
char* szBriefInfo; // callstack info
};
stackInfo ShowTraceStack(char* szBriefInfo)
{
static const int MAX_STACK_FRAMES = 200;
void* pStack[MAX_STACK_FRAMES];
static char szStackInfo[STACK_INFO_LEN * MAX_STACK_FRAMES];
static char szFrameInfo[STACK_INFO_LEN];
HANDLE process = GetCurrentProcess(); // The handle used must be unique to avoid sharing a session with another component,
SymInitialize(process, NULL, TRUE);
PDWORD hashValue = (PDWORD)malloc(sizeof(DWORD)); // allow memory for hashVavlue, it will be rewrited in function CaptureStackBackTrace
WORD frames = CaptureStackBackTrace(0, MAX_STACK_FRAMES, pStack, hashValue);
//printf("hash value is: %ud \n", &hashValue);
if (szBriefInfo == NULL) {
strcpy_s(szStackInfo, "stack traceback:\n");
}
else {
strcpy_s(szStackInfo, szBriefInfo);
}
for (WORD i = 0; i < frames; ++i) {
DWORD64 address = (DWORD64)(pStack[i]);
DWORD64 displacementSym = 0;
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
DWORD displacementLine = 0;
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
if (SymFromAddr(process, address, &displacementSym, pSymbol) &&
SymGetLineFromAddr64(process, address, &displacementLine, &line))
{
_snprintf_s(szFrameInfo, sizeof(szFrameInfo), "\t%s() at %s:%d(0x%x)\n",
pSymbol->Name, line.FileName, line.LineNumber, pSymbol->Address);
}
else
{
_snprintf_s(szFrameInfo, sizeof(szFrameInfo), "\terror: %d\n", GetLastError());
}
strcat_s(szStackInfo, szFrameInfo);
}
stackInfo traceStackInfo;
traceStackInfo.hashValue = hashValue;
traceStackInfo.szBriefInfo = szStackInfo;
printf("%s", szStackInfo);
return traceStackInfo;
}
HANDLE(*oldCreateFile)(LPCWSTR,
DWORD,
DWORD,
LPSECURITY_ATTRIBUTES,
DWORD,
DWORD,
HANDLE) = CreateFileW;
HANDLE WINAPI newCreateFile(
_In_ LPCWSTR lpFileName,
_In_ DWORD dwDesiredAccess,
_In_ DWORD dwShareMode,
_In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes,
_In_ DWORD dwCreationDisposition,
_In_ DWORD dwFlagsAndAttributes,
_In_opt_ HANDLE hTemplateFile
) {
ShowTraceStack((char*)"trace information.");
return oldCreateFile(
L".\\newFiles.txt", // L".\\NewFile.txt", // Filename
//lpFileName,
dwDesiredAccess, // Desired access
dwShareMode, // Share mode
lpSecurityAttributes, // Security attributes
dwCreationDisposition, // Creates a new file, only if it doesn't already exist
dwFlagsAndAttributes, // Flags and attributes
NULL);
}
void hook() {
DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)oldCreateFile, newCreateFile);
DetourTransactionCommit();
}
void unhook()
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)oldCreateFile, newCreateFile);
DetourTransactionCommit();
}
void myProcess() {
HANDLE hFile = CreateFile(TEXT(".\\CreateFileDemo.txt"),
GENERIC_WRITE | GENERIC_READ,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
OutputDebugString(TEXT("CreateFile fail!\r\n"));
}
// write to file
const int BUFSIZE = 4096;
char chBuffer[BUFSIZE];
memcpy(chBuffer, "Test", 4);
DWORD dwWritenSize = 0;
BOOL bRet = WriteFile(hFile, chBuffer, 4, &dwWritenSize, NULL);
ShowTraceStack((char*)"trace information.");
if (bRet)
{
OutputDebugString(TEXT("WriteFile success!\r\n"));
}
}
int main(){
hook();
myProcess();
unhook();
}
I'm trying to inject a dll into a process. The dll does nothing except return TRUE.
I attached a debugger to the process that I want to inject into and confirmed that LoadLibraryA is called correctly but returns NULL.
Now I think that this might have something to do with my dll's dependencies. So I checked them and found out that it requires vcruntime140.dll.
The process that I want to inject my dll into does not load that dll.
#include "pch.h"
extern "C" int __stdcall APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
#include "Source.h"
const char* DllName = "InjectMe.dll";
int main()
{
DWORD processID = 0;
printf("Process ID: ");
scanf_s("%i", &processID);
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
if (handle == nullptr) {
printf("Process could not be opened.");
return -1;
}
LPVOID memDllName = VirtualAllocEx(handle, nullptr, strlen(DllName) + 1, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
assert(memDllName != nullptr);
assert(WriteProcessMemory(handle, memDllName, DllName, strlen(DllName) + 1, nullptr));
LPVOID loadLibraryAddr = GetProcAddress(GetModuleHandleA("kernel32.dll"), "LoadLibraryA");
assert(loadLibraryAddr != nullptr);
HANDLE thread = CreateRemoteThreadEx(handle, nullptr, 0, (LPTHREAD_START_ROUTINE)loadLibraryAddr, memDllName, CREATE_SUSPENDED, nullptr, nullptr);
assert(thread != nullptr);
ResumeThread(thread);
DWORD returnCode = WaitForSingleObject(thread, 5000);
CloseHandle(thread);
if (returnCode == WAIT_TIMEOUT) {
printf("DLL was not loaded. Thread timed out.");
return -1;
}
else if (returnCode == WAIT_OBJECT_0) {
printf("DLL was successfully injected into the process.");
}
CloseHandle(handle);
std::cin.get();
return 0;
}
You must use a full file path not a relative file path when calling LoadLibrary()
const char* DllName = "InjectMe.dll";
needs to be changed to something like this
const char* DllName = "c:\\Users\User\\Desktop\\InjectMe.dll";
Also make sure you run as administrator if OpenProcess fails or sometimes you also need to use SeDebugPrivelage
In order to test if it is a pathing issue, try the following. Keep the
const char* DllName = "InjectMe.dll";
Then put the InjectMe.dll and your .exe in the same directory and try to run your exe. If the dll is loaded successfully, then it is a pathing issue.
To work around that, you can either specify the full path like GuidedHacking said, OR you can put your InjectMe.dll in the same directory as the .vcxproj and .cpp files (not where the .sln file is)
I want to make a message box appear in notepad , so I found a simple dll injection example. The injector itself is not mine and seems to work fine (gets the process's id , creates a remote thread , gets absolute path of the dll file). The problem, I think, is in the implementation of the dll. The projects compile without any warnings, but the expected outcome isn't achieved. Can you take a look and help me understand the problem? (I have put the release version of the dll in the injector project folder)
dllmain.cpp:
// dllmain.cpp : Defines the entry point for the DLL application.
#include "stdafx.h"
#include "dll.h"
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
DLLEXPORT void mess() {
MessageBoxA(NULL, "HELLO THERE", "From Notepad", NULL);
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH: mess(); break;
case DLL_THREAD_ATTACH: mess(); break;
case DLL_THREAD_DETACH: mess(); break;
case DLL_PROCESS_DETACH: mess(); break;
}
return TRUE;
}
dll.h:
#ifndef _DLL_H_
#define _DLL_H_
# define DLLEXPORT __declspec (dllexport)
# define DLLIMPORT __declspec (dllimport)
DLLEXPORT void mess(void);
#endif
and the injection.cpp for reference, it contains a function which finds the wanted process id, a function which creates the remote thread and a main:
#include "stdafx.h"
#include <windows.h>
#include <tlhelp32.h>
#include <shlwapi.h>
#include <conio.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#define WIN32_LEAN_AND_MEAN
#define CREATE_THREAD_ACCESS (PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ)
DWORD GetProcessId(IN PCHAR szExeName)
{
DWORD dwRet = 0;
DWORD dwCount = 0;
HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshot != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
BOOL bRet = Process32First(hSnapshot, &pe);
while (bRet)
{
if (!strcmp( szExeName, pe.szExeFile))
{
dwCount++;
dwRet = pe.th32ProcessID;
}
bRet = Process32Next(hSnapshot, &pe);
}
if (dwCount > 1)
dwRet = 0xFFFFFFFF;
CloseHandle(hSnapshot);
}
return dwRet;
}
BOOL CreateRemoteThreadInject(DWORD ID, const char * dll)
{
HANDLE Process;
LPVOID Memory;
LPVOID LoadLibrary;
if (!ID) return false;
Process = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, FALSE, ID);
LoadLibrary = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
Memory = (LPVOID)VirtualAllocEx(Process, NULL, strlen(dll) + 1, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(Process, (LPVOID)Memory, dll, strlen(dll) + 1, NULL);
CreateRemoteThread(Process, NULL, NULL, (LPTHREAD_START_ROUTINE)LoadLibrary, (LPVOID)Memory, NULL, NULL);
CloseHandle(Process);
VirtualFreeEx(Process, (LPVOID)Memory, 0, MEM_RELEASE);
return true;
}
int main()
{
char dll[MAX_PATH] ;
GetFullPathName("testdll.dll", MAX_PATH, dll, NULL);
DWORD ID = GetProcessId("notepad.exe");
if (!CreateRemoteThreadInject(ID, dll)) cout<<"failure";
else cout << "success";
return 0;
}
Thanks.
Be carefull on x64 x86 binaries
On windows 7 / 8 / 10 notepad.exe is a 64 bits process, so you need to compile your DLL & injector in x64
I'm trying make a hook in MessageBoxA api in a remote process made by me using IAT hook tecnique. I'm using Process Hacker software for inject my dll file into my process and until here works fine.
My unique trouble is that MessageBoxA never is intercepted when i will call this api from my application.
I have discovered that this api don't can be found in table of import of my process.
So, i want know any suggestion about how i can find this api on table.
Here is code that i use:
#include <windows.h>
#include <string.h>
#include <stdio.h>
void HookFunction(char* funcName, LPDWORD function);
LPDWORD FoundIAT(char* funcName);
int WINAPI HookMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType);
BOOL APIENTRY DllMain (HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
if(dwReason == DLL_PROCESS_ATTACH)
{
MessageBox(NULL, "Injeted with success!", "Hello", NULL);
HookFunction("MessageBoxA", (LPDWORD)&HookMessageBoxA);
}
return TRUE;
}
void HookFunction(char* funcName, LPDWORD function)
{
LPDWORD pOldFunction = FoundIAT(funcName);
DWORD accessProtectionValue , accessProtec;
int vProtect = VirtualProtect(pOldFunction, sizeof(LPDWORD), PAGE_EXECUTE_READWRITE, &accessProtectionValue);
*pOldFunction = (DWORD)function;
vProtect = VirtualProtect(pOldFunction, sizeof(LPDWORD), accessProtectionValue, &accessProtec);
}
int WINAPI HookMessageBoxA(HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, UINT uType)
{
return MessageBoxA(hWnd, "Hello", "DLL answering here!", uType);
}
LPDWORD FoundIAT(char* funcName)
{
DWORD test = 0;
LPVOID pMapping = GetModuleHandle(NULL);
if (pMapping == NULL)
exit(-1);
PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER) pMapping;
if (DosHeader->e_magic != IMAGE_DOS_SIGNATURE)
exit(-1);
PIMAGE_NT_HEADERS NtHeaders = (PIMAGE_NT_HEADERS) ((char*) DosHeader + DosHeader->e_lfanew);
if (NtHeaders->Signature != IMAGE_NT_SIGNATURE)
exit(-1);
PIMAGE_DATA_DIRECTORY DataDirectory = &NtHeaders->OptionalHeader.DataDirectory[1];
PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR) ((char*) DosHeader + DataDirectory->VirtualAddress);
PIMAGE_THUNK_DATA32 OriginalFirstThunk = (PIMAGE_THUNK_DATA32)((char*) DosHeader + ImportDescriptor->OriginalFirstThunk);
while(OriginalFirstThunk != 0)
{
DWORD name = (DWORD)((char*) pMapping + ImportDescriptor->Name);
OriginalFirstThunk = (PIMAGE_THUNK_DATA32)((char*) DosHeader + ImportDescriptor->OriginalFirstThunk);
PIMAGE_THUNK_DATA32 FirstThunk = (PIMAGE_THUNK_DATA32)((char*) DosHeader + ImportDescriptor->FirstThunk);
while(OriginalFirstThunk->u1.AddressOfData != 0)
{
PIMAGE_IMPORT_BY_NAME NameImg = (PIMAGE_IMPORT_BY_NAME)((char*) DosHeader + (DWORD)OriginalFirstThunk->u1.AddressOfData);
test = (DWORD)OriginalFirstThunk->u1.Function & (DWORD)IMAGE_ORDINAL_FLAG32;
if (test == 0)
{
if(strcmp(funcName, (const char*)NameImg->Name) == 0)
{
MessageBox(NULL, NameImg->Name, "", NULL);
return (LPDWORD)&(FirstThunk->u1.Function);
}
}
OriginalFirstThunk++;
FirstThunk++;
}
ImportDescriptor++;
}
return 0;
}
Source
EDIT 1:
I have seen with more datails, that now this code is able to find MessageBoxA api :D, but still when i'll call this api from my application (made in Delphi), the hook don't work.
:-(
My Delphi code here:
procedure TForm1.btn1Click(Sender: TObject);
begin
MessageBoxA(Application.Handle, 'Delphi application here!', 'Hello',0);
end;
EDIT 2:
This can be a definitive solution, but link is offline. Someone can help me about how it can be adapted to my code above please?
I had written a file monitor using ms detours.i have to hook file related calls like creatfile,readfile in any targetexecutable and collect stats from those calls.
I have an injector
void CFileStat::MonitorProcess()
{
int npos=filename.ReverseFind('\\');
CString name=filename.Mid(npos+1);
WCHAR* DirPath = new WCHAR[MAX_PATH];
WCHAR* FullPath = new WCHAR[MAX_PATH];
GetCurrentDirectory(MAX_PATH, DirPath);
DWORD processID = FindProcessId(name);
if ( processID == 0 )
AfxMessageBox(L"Could not find ");
else
AfxMessageBox(L"Process ID is ");
swprintf_s(FullPath, MAX_PATH, L"%s\\%s", DirPath,strhookdll);
LPCTSTR lpszPrivilege = L"SeDebugPrivilege";
// Change this BOOL value to set/unset the SE_PRIVILEGE_ENABLED attribute
BOOL bEnablePrivilege = TRUE;
HANDLE hToken;
// Open a handle to the access token for the calling process. That is this running program
if(!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
printf("OpenProcessToken() error %u\n", GetLastError());
return ;
}
BOOL test = SetPrivilege(hToken, lpszPrivilege, bEnablePrivilege);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
if( ! hProcess )
{
return;
}
LPVOID LoadLibraryAddr = (LPVOID)GetProcAddress(GetModuleHandle(L"kernel32.dll"),
"LoadLibraryA");
LPVOID LLParam = (LPVOID)VirtualAllocEx(hProcess, NULL, lstrlen(FullPath),
MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
if( ! LLParam )
{
printf( "ERROR: Problems with VirtualAllocEx. Error code: %d\n", GetLastError() );
return;
}
int n=WriteProcessMemory(hProcess, LLParam, FullPath, lstrlen(FullPath), NULL);
if(n == 0) {
printf("Error: there was no bytes written to the process's address space.\n");
}
HANDLE threadID = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE) LoadLibraryAddr,
LLParam, NULL, NULL);
if(threadID == NULL) {
printf("Error: the remote thread could not be created.\n");
}
else
{
printf("Success: the remote thread was successfully created.\n");
}
WaitForSingleObject(threadID, INFINITE);
CloseHandle(hProcess);
delete [] DirPath;
delete [] FullPath;
I have the hook dll
#include <iostream>
#include <windows.h>
#include "detours.h"
#include"FileDetour.h"
#pragma comment(lib, "detours.lib")
void AddHook(PVOID* func,PVOID intercept);
void DeleteHook(PVOID* func,PVOID intercept);
static HANDLE (WINAPI * PCreateFile)(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD
dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD
dwFlagsAndAttributes, HANDLE hTemplateFile) = CreateFile;
HANDLE WINAPI InterceptCreateFile(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD
dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition,
DWORD dwFlagsAndAttributes, HANDLE hTemplateFile);
BOOL APIENTRY DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpReserved )
{
FILE *file;
fopen_s(&file, "D:\\temp.txt", "a+");
DWORD Error=0;
// Perform actions based on the reason for calling.
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
// Initialize once for each new process.
// Return FALSE to fail DLL load.
fprintf(file, "DLL attach function called.\n");
DisableThreadLibraryCalls(hinstDLL);
OutputDebugString(L"Attaching filedetour.dll");
// DetourRestoreAfterWith();
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(&(PVOID&)PCreateFile, InterceptCreateFile);
Error=DetourTransactionCommit();
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
// Do thread-specific cleanup.
break;
case DLL_PROCESS_DETACH:
fprintf(file, "DLL dettach function called.\n");
OutputDebugString(L"De-Attaching MyDLL.dll");
DWORD Error=0;
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(&(PVOID&)PCreateFile,InterceptCreateFile);
Error=DetourTransactionCommit();
break;
}
fclose(file);
return TRUE; // Successful DLL_PROCESS_ATTACH.
}
HANDLE WINAPI InterceptCreateFile(LPCWSTR lpFileName, DWORD dwDesiredAccess, DWORD
dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD
dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile)
{
OutputDebugString(lpFileName);
return PCreateFile(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
}
CreateRemotethread returns successfully and I am going to waitforsingleobject in the injector function.
but I am getting no evidence of dll being injected into the target exe process space.i tried ollydbg.the debug is not hitting the hook dll project named "filedetour" when i debug the target exe as well the injector process .Neither the text file temp.txt is being created.when i debug the target exe for one or two lines , I get a debug window message the thread is exiting.The waitforsingleobejct in the injector process immediately signals.
in short there is no evidence a dll was injected sucessfuly and that dllmain was hit at all.
how to debug the entire process?iwant to debug the hook dll throroughly from the target exe as the hook dll collects stats from the file operations.
what are the files I have to copy from the hook dll project(dll,lib,.h) and any extra settings to be made to the injector project?
I am new to this topic.