I am just a beginner in coding. I know the basics of c++ and c#. I was making a dll injector. I also followed a tutorial for a part. One part of the thing I have from the tutorial has an error and it is "Too many initializer values". I don't know what that means and why it is there. The error is at the nullptr in the next line
void* allocated_memory(h_process, nullptr, MAX_PATH, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
It is at the first nullptr. If I remove that nullptr then I get the error at the MAX_PATH
biggest part of code:
#include <iostream>
#include <Windows.h>
#include <string>
#include <thread>
#include <libloaderapi.h>
void get_id(const char* windows_title, DWORD &process_id)
{
GetWindowThreadProcessId(FindWindow(NULL, windows_title), &process_id);
}
void error(const char* error_title, const char* error_message)
{
MessageBox(NULL, error_message, error_title, NULL);
exit(-1);
}
bool file_exists(std::string file_name)
{
struct stat buffer;
return (stat(file_name.c_str(), &buffer) == 0);
}
int main()
{
DWORD proc_id = NULL;
char dll_path(MAX_PATH);
const char* dll_name = "PW";
const char* window_title = "Pixel Worlds";
if (!file_exists(dll_name))
{
error("file_exists", "Something went wrong");
}
HANDLE h_process = OpenProcess(PROCESS_ALL_ACCESS, NULL, proc_id);
void* allocated_memory(h_process, nullptr, MAX_PATH, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
HANDLE h_thread = CreateRemoteThread(h_process, nullptr, NULL, LPTHREAD_START_ROUTINE(LoadLibraryA), allocated_memory, NULL, nullptr);
CloseHandle(h_process);
VirtualFreeEx(h_process, allocated_memory, NULL, MEM_RELEASE);
MessageBox(NULL, "Successfully injected", "Success", NULL);
}
You appear to be trying to use the VirtualAllocEx WinAPI routine but you have not named that function in your attempted call, which is just incorrect syntax.
In place of the line:
void* allocated_memory(h_process, nullptr, MAX_PATH, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
you need to declare your void* pointer and allocate the memory it points to with a call like the following:
void* allocated_memory = VirtualAllocEx(h_process, nullptr, MAX_PATH, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
Related
I am trying to download an image onto the user's desktop from a URL using Win32. I have taken care of all the HTTP request stuff and know for a fact that it is all working well. When I go to call CreateFile() the Visual Studios debugger just says "Exception: Application.exe has triggered a breakpoint" and that it will resume on the CreateFile() line. Also there is an error code "Critical error detected c0000374"
Here is my code:
VARIANT varResponse;
VariantInit(&varResponse);
...
hr = pIWinHttpRequest->get_ResponseBody(&varResponse);
...
if (SUCCEEDED(hr)) {
long upperBounds;
long lowerBounds;
unsigned char* buff;
//Make sure that varResponse is an array of unsigned bytes
if (varResponse.vt == (VT_ARRAY | VT_UI1)) {
long Dims = SafeArrayGetDim(varResponse.parray);
//It should only have one dimension
if (Dims == 1) {
//Get Array lower and upper bounds
SafeArrayGetLBound(varResponse.parray, 1, &lowerBounds);
SafeArrayGetUBound(varResponse.parray, 1, &upperBounds);
upperBounds++;
SafeArrayAccessData(varResponse.parray, (void**)&buff);
HANDLE hFile;
DWORD dwBytesWritten;
PWSTR filepath[MAX_PATH];
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Desktop, 0, NULL, &*filepath);
if (SUCCEEDED(hr)) {
//PathCombine(filepathForImage, filepathToDesktop, L"\\todaysDailyImage.jpg");
PathAppend(*filepath, L"todaysDailyImage.jpg");
MessageBox(NULL, *filepath, L"Check if filepath works", MB_OK);
}
hFile = CreateFile(*filepath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
//File failed
}
else {
WriteFile(hFile, buff, upperBounds - lowerBounds, &dwBytesWritten, NULL);
//File was written
}
CloseHandle(hFile);
CoTaskMemFree(filepath);
SafeArrayUnaccessData(varResponse.parray);
MessageBox(NULL, L"Everything was cleaned up", L"Update:", MB_OK);
}
}
}
Am I doing anything wrong?
The way you are using filepath is all wrong.
You are declaring it as an array of MAX_PATH (260) number of PWSTR pointers.
When you refer to an array by its name alone, you end up with a pointer to the 1st element of the array. So, &*filepath is the same as &*(&filepath[0]), which is effectively &filepath[0]. And *filepath is the same as *(&filepath[0]), which is effectively filepath[0]. So, as far as SHGetKnownFolderPath() and MessageBox() are concerned, they are only operating on the 1st PWSTR pointer in the array, and the other 259 array elements are ignored. That part is ok, but wasteful.
However, PathAppend() requires a destination buffer that is an array of MAX_PATH number of WCHAR elements. You are appending to the WCHAR[] array that SHGetKnownFolderPath() allocates as its output, which is not large enough to hold the filename you are trying to append to it. So, you are triggering errors because you are trying to modify memory that hasn’t been allocated to hold that modification.
You don’t need the PWSTR array at all. Try something more like this instead:
PWSTR folderpath;
HRESULT hr = SHGetKnownFolderPath(FOLDERID_Desktop, 0, NULL, &folderpath);
if (FAILED(hr)) {
// ...
}
else {
PWSTR filepath;
hr = PathAllocCombine(folderpath, L"todaysDailyImage.jpg", 0, &filepath);
if (FAIlED(hr)) {
// ...
}
else {
MessageBoxW(NULL, filepath, L"Check if filepath works", MB_OK);
hFile = CreateFileW(filepath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
//File failed
}
else {
WriteFile(hFile, buff, upperBounds - lowerBounds, &dwBytesWritten, NULL);
//File was written
CloseHandle(hFile);
}
LocalFree(filepath);
}
CoTaskMemFree(folderpath);
}
i try to read the Registry in my NPAPI-Plugin:
bool ScriptablePluginObject::Invoke(NPObject* obj, NPIdentifier methodName, const NPVariant* args, uint32_t argCount, NPVariant* result) {
ScriptablePluginObject *thisObj = (ScriptablePluginObject*) obj;
char* name = npnfuncs->utf8fromidentifier(methodName);
LPCWSTR game_path = getRegKey(L"SOFTWARE\\World of RPG", L"Path");
MessageBox(NULL, game_path, L"Debugging", MB_TOPMOST);
/* ... */
}
LPCWSTR ScriptablePluginObject::getRegKey(LPCWSTR location, LPCWSTR name) {
HKEY hKey;
LPBYTE folder = new BYTE[MAX_PATH];
DWORD dwSize = sizeof(folder);
long registry = RegOpenKeyEx(HKEY_LOCAL_MACHINE, location, 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
long entry = RegQueryValueEx(hKey, name, NULL, REG_NONE, folder, &dwSize);
if(registry != ERROR_SUCCESS) {
return L"Error1";
}
if(entry != ERROR_SUCCESS) {
return L"Error2";
}
RegCloseKey(hKey);
folder[dwSize / sizeof(folder[0])] = '\0';
return (LPCWSTR) folder;
}
But it's returned every call Error2. I've tried a lot of changes:
change the Path (with Start and/or Ending \\)
change parameters
I Want to get the Path of HKEY_LOCAL_MACHINE\SOFTWARE\World of RPG\Path:
Anyone can help me? What i'm doing wrong?
Here's the sample I mentioned in the comments above:
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
LSTATUS ReadRegistry ( LPCWSTR sPath, LPCWSTR sKey, LPWSTR pBuffer, DWORD *pBufferSize );
int _tmain(int argc, _TCHAR* argv[])
{
const int BUFFER_SIZE = 1024;
WCHAR sBuffer[BUFFER_SIZE]; // 2048 bytes
DWORD nBufferSize = BUFFER_SIZE * sizeof ( WCHAR );
ZeroMemory ( sBuffer, nBufferSize );
LSTATUS nResult = ReadRegistry ( L"SOFTWARE\\7-Zip", L"Path64",
sBuffer, &nBufferSize );
// check nResult for ERROR_SUCCESS to know if the call succeeded or not
return 0;
}
LSTATUS ReadRegistry ( LPCWSTR sPath, LPCWSTR sKey, LPWSTR pBuffer, LPDWORD pBufferSize )
{
HKEY hKey;
LSTATUS nResult = ::RegOpenKeyEx ( HKEY_LOCAL_MACHINE, sPath,
0, KEY_READ | KEY_WOW64_64KEY, &hKey );
if ( nResult == ERROR_SUCCESS )
{
nResult = ::RegQueryValueEx ( hKey, sKey, NULL, NULL,
(LPBYTE) pBuffer, pBufferSize );
RegCloseKey ( hKey );
}
return ( nResult );
}
Notice how the ReadRegistry function doesn't allocate memory - it takes a buffer and fills it with data. It's a lot easier to deal with memory if you always have the caller allocate memory. If the callee allocates memory, the caller may not know how memory was allocated and it may not know how to free it. (Of course, you can always assume the use of new and delete but things are simpler if only one side does this consistently. If the caller allocates memory, it'll know how to free it. The callee only needs to put data in the allocated space.
Also, notice how the return value of the API functions is checked before proceeding to the next call - this is important because this tells you if you got a useful registry handle back or not and whether you need to close it or not.
(This sample is really just C, not C++ but it still applies.)
In getRegKey(), your folder variable is a pointer, so sizeof(folder) is 4 (if compiling for 32bit) or 8 (if compiling for 64bit). Thus RegQueryValueEx() fails with an ERROR_MORE_DATA error code.
You are also using the wrong data type for the array. You need to use WCHAR instead of BYTE.
Change this:
LPBYTE folder = new BYTE[MAX_PATH];
DWORD dwSize = sizeof(folder);
To this:
LPWSTR folder = new WCHAR[MAX_PATH];
DWORD dwSize = sizeof(WCHAR) * MAX_PATH;
With that said, you are leaking the memory pointed to by folder, since you never delete[] it.
i tried to extract all items from SysListView32,
this is the code:
#define WIN32_LEAN_AND_MEAN
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <commctrl.h>
int main(void) {
HWND hwnd=FindWindow(TEXT("Window"), TEXT("Cheat Engine 6.1"));
HWND win=FindWindowEx(hwnd, NULL, TEXT("Window"), NULL);
HWND listview=FindWindowEx(win, NULL, TEXT("SysListView32"), NULL);
int count=(int)SendMessage(listview, LVM_GETITEMCOUNT, 0, 0);
int i;
LVITEM lvi, *_lvi;
char item[512], subitem[512];
char *_item, *_subitem;
unsigned long pid;
HANDLE process;
GetWindowThreadProcessId(listview, &pid);
process=OpenProcess(PROCESS_VM_OPERATION|PROCESS_VM_READ|PROCESS_VM_WRITE|PROCESS_QUERY_INFORMATION, FALSE, pid);
_lvi=(LVITEM*)VirtualAllocEx(process, NULL, sizeof(LVITEM), MEM_COMMIT, PAGE_READWRITE);
_item=(char*)VirtualAllocEx(process, NULL, 512, MEM_COMMIT, PAGE_READWRITE);
_subitem=(char*)VirtualAllocEx(process, NULL, 512, MEM_COMMIT, PAGE_READWRITE);
lvi.cchTextMax=512;
for(i=0; i<count; i++) {
lvi.iSubItem=0;
lvi.pszText=_item;
WriteProcessMemory(process, _lvi, &lvi, sizeof(LVITEM), NULL);
SendMessage(listview, LVM_GETITEMTEXT, (WPARAM)i, (LPARAM)_lvi);
lvi.iSubItem=1;
lvi.pszText=_subitem;
WriteProcessMemory(process, _lvi, &lvi, sizeof(LVITEM), NULL);
SendMessage(listview, LVM_GETITEMTEXT, (WPARAM)i, (LPARAM)_lvi);
ReadProcessMemory(process, _item, item, 512, NULL);
ReadProcessMemory(process, _subitem, subitem, 512, NULL);
printf("%s - %s\n", item, subitem);
}
VirtualFreeEx(process, _lvi, 0, MEM_RELEASE);
VirtualFreeEx(process, _item, 0, MEM_RELEASE);
VirtualFreeEx(process, _subitem, 0, MEM_RELEASE);
return 0;
}
Error:
cannot convert from 'char *' to 'LPWSTR' at line: lvi.pszText=_item;
Error 2:
IntelliSense: a value of type "char *" cannot be assigned to an entity of type "LPWSTR" at line: lvi.pszText=_subitem;
i tried TEXT(_subitem) , Still not working.
Use TCHAR* or wchar_t* instead of char*. Use TEXT() only for string literals.
So I had to two friends test the executable on their Vista & Win7 operating systems. Neither had the injected code executed (even when Run as Administrator) but the console open/closed. Does code injection via WriteProcessMemory and CreateRemoteThread still work on Vista or Win7?
The Code
Compiled using /RTCu on Visual Studio 2008 to prevent process crashing while on Windows XP after the remote thread terminates.
CodeInjector.h
#ifndef CODEINJECTOR_H
#define CODEINJECTOR_H
typedef HANDLE(WINAPI *GETPROC)();
typedef HMODULE(WINAPI *PLOADLIBRARYA)(const char *dll);
typedef LPVOID(WINAPI *PGETPROCADDRESS)(HMODULE mod, const char *func);
typedef int (WINAPI *FNMESSAGEBOX)(HWND, LPCSTR, LPCSTR, UINT);
typedef struct _IAT {
PLOADLIBRARYA pLoadLibraryA;
PGETPROCADDRESS pGetProcAddress;
FNMESSAGEBOX fnMessageBox;
} IAT;
typedef struct _DATA {
void *szData[256];
} DATA;
typedef struct _FNARGS {
LPVOID pIat;
LPVOID pData;
} FNARGS;
#endif /* CODEINJECTOR_H */
CodeInjector.cpp
#include "stdafx.h"
#include <iostream>
#include <string>
#include <windows.h>
#include "CodeInjector.h"
using namespace std;
HANDLE getHandleByName(const char* nameWnd)
{
HWND hWnd = FindWindowA(0, nameWnd);
if (hWnd == 0) {
std::cerr << "Cannot find window" << std::endl;
} else {
DWORD pId;
GetWindowThreadProcessId(hWnd, &pId);
HANDLE hToken;
TOKEN_PRIVILEGES tkp;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, 0, &tkp, sizeof (tkp), NULL, NULL);
}
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pId);
if (!hProc) {
std::cerr << "Cannot open process: " << GetLastError() << std::endl;
} else {
return hProc;
}cout << hProc;
getchar();
}
return false;
}
static DWORD WINAPI ThreadFunc(FNARGS *info)
{
if (info == NULL || info->pIat == NULL || info->pData == NULL) {
return 0;
}
IAT *iat = (IAT *)info->pIat;
DATA *data = (DATA *)info->pData;
iat->fnMessageBox(NULL, (char*)data->szData[1], (char*)data->szData[0], MB_OK);
return 0;
}
static void ThreadFuncEnd() {}
int main(int argc, char** argv)
{
HANDLE hProc = getHandleByName("Calculator");
DWORD CodeSize = (DWORD) & ThreadFuncEnd - (DWORD) & ThreadFunc;
IAT hIAT;
DWORD hLibModule;
HMODULE hKernel = LoadLibraryA("kernel32.dll");
HMODULE hUser32 = LoadLibraryA("user32.dll");
hIAT.pLoadLibraryA = (PLOADLIBRARYA)GetProcAddress(hKernel, "LoadLibraryA");
hIAT.pGetProcAddress = (PGETPROCADDRESS)GetProcAddress(hKernel, "GetProcAddress");
hIAT.fnMessageBox = (FNMESSAGEBOX)GetProcAddress(hUser32, "MessageBoxA");
LPVOID hIATMemAddr = VirtualAllocEx(hProc, NULL, sizeof (IAT), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProc, hIATMemAddr, (LPVOID) & hIAT, sizeof (IAT), NULL);
DATA hData;
LPVOID hDataMemAddr = VirtualAllocEx(hProc, NULL, sizeof (DATA), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
hData.szData[0] = VirtualAllocEx(hProc, NULL, 64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
hData.szData[1] = VirtualAllocEx(hProc, NULL, 64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
hData.szData[2] = VirtualAllocEx(hProc, NULL, 64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
hData.szData[3] = VirtualAllocEx(hProc, NULL, 64, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
char tmp[64];
strcpy(tmp, "Caption");
WriteProcessMemory(hProc, hData.szData[0], (LPVOID) & tmp, sizeof (tmp), NULL);
strcpy(tmp, "Message");
WriteProcessMemory(hProc, hData.szData[1], (LPVOID) & tmp, sizeof (tmp), NULL);
WriteProcessMemory(hProc, hDataMemAddr, (LPVOID) &hData, sizeof (DATA), NULL);
FNARGS tInfo;
tInfo.pIat = hIATMemAddr;
tInfo.pData = hDataMemAddr;
LPVOID hInfoMemAddr = VirtualAllocEx(hProc, NULL, sizeof (FNARGS), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProc, hInfoMemAddr, (LPVOID) & tInfo, sizeof (FNARGS), NULL);
LPVOID CodeMemAddr = VirtualAllocEx(hProc, NULL, CodeSize, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
WriteProcessMemory(hProc, CodeMemAddr, (LPVOID) & ThreadFunc, CodeSize, NULL);
HANDLE hRemoteThread = CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)CodeMemAddr, hInfoMemAddr, 0, NULL);
WaitForSingleObject(hRemoteThread, INFINITE);
GetExitCodeThread(hRemoteThread, &hLibModule);
CloseHandle(hProc);
return 0;
}
Not really a surprise. Vista and Windows 7 have increased security. Lots of malware used Code Injection as one of the steps to bypass security mechanisms on Windows XP, and I'm glad to see Microsoft fixed this.
I want to download all file from ftp directory i want use for that FtpFindFirstFile and FtpGetFile;
LPWIN32_FIND_DATA FileData;
TCHAR* APP_NAME = TEXT("ftpcli");
TCHAR* PATH_FTP = TEXT("ftp://127.0.01");
TCHAR* ADR_FTP = TEXT("127.0.0.1");
TCHAR* LC_FILE = TEXT("C:\\!");
TCHAR* PATH_FILE = TEXT("/Soft/DVD_Players/WinDVD6");
UINT a;
HINTERNET opn;
HINTERNET conn;
a = InternetAttemptConnect(0);
if (a == ERROR_SUCCESS ) {
if(InternetCheckConnection(PATH_FTP,FLAG_ICC_FORCE_CONNECTION, NULL)) {
opn = InternetOpen(APP_NAME, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, INTERNET_FLAG_ASYNC);
conn = InternetConnect(opn, ADR_FTP, INTERNET_DEFAULT_FTP_PORT, NULL, NULL, INTERNET_SERVICE_FTP, NULL, NULL);
FtpSetCurrentDirectory(conn, PATH_FILE);
FtpFindFirstFile(conn, NULL, &FileData, INTERNET_FLAG_NEED_FILE, NULL);
FtpGetFile(conn, FileData->cFileName, LC_FILE, FALSE, FILE_ATTRIBUTE_NORMAL, FTP_TRANSFER_TYPE_BINARY, NULL);
}
}
That code return error i know that because i do not identified memory on LPWIN32_FIND_DATA. But i do not know how do it.
You've declared a pointer to WIN32_FIND_DATA, you need a concrete instance of that structure. Fix:
WIN32_FIND_DATA FileData; // NOTE: not LP
At a minimum:
FileData->cFileName
should be
FileData.cFileName
I misread LPWIN32_FIND_DATA as WIN32_FIND_DATA; nobugs is right that this is just a pointer (and if using the pointer my advice here is wrong, but then there's no struct allocated.)