this is my first semi-major C project. I'm a self taught programmer so if my code has any major flaws OR if you happen to have any tips for me, please point them out, I'm very eager to learn. Thank you.
Anyway, I decided to code a process injector for windows, as title says, and I every time I attempt to inject the windows XP SP2 calc into designated process, it crashes. The reason I had decided to make it XP based was because this is a test version/POC/whatever.
Is this because the shellcode is only applicable for specific processes?
I had attempted different processes, explorer.exe, firefox.exe, etc. Still crashes.
Oh, and FYI my ASM isn't the best so I borrowed some shellcode from shell-storm
Also, how does the code look? I had some problems understanding the MSDN API for some of the psapi / windows parameters. It seemed kind of vague, and it was kind of hard to find examples online for some of my questions.
#include <windows.h>
#include <stdio.h>
#include <psapi.h>
#define BYTESIZE 100
void ProcessIdentf(DWORD ProcessID);
//Required for Process Handling rights
int SeDebugMode(HANDLE ProcessEnabled, LPCTSTR Base_Name);
int main(void){
//x86 | Windows XP SP2 | calc.exe call
//POC data
unsigned char call_calc[] =
"\x31\xc0\xeb\x13\x5b\x88\x43\x0e\x53\xbb\xad\x23\x86\x7c\xff\xd3\xbb"
"\xfa\xca\x81\x7c\xff\xd3\xe8\xe8\xff\xff\xff\x63\x6d\x64\x2e\x65\x78"
"\x65\x20\x2f\x63\x20\x63\x6d\x64";
//Process HANDLE && Process Identifier WORD
HANDLE FfHandle;
int ProcID;
//VirtualAllocMemPnter
LPVOID lpv = NULL;
//Typecasted pointer to Shellcode
char* shellptr = call_calc;
//Handle for CreateRemoteThread function
HANDLE ControlStructRemote;
//Number of bytes successfully executed
SIZE_T bytescom;
//Data for Process enumeration
DWORD xyProcesses[1024]; //Max_Proc
DWORD abProcesses, cntbNeeded;
unsigned int c;
printf("POC version x00.\nInjects example x86 shellcode into process.\n");
SeDebugMode(GetCurrentProcess(), SE_DEBUG_NAME);
printf("SE_DEBUG_PRIVILEGE successfully enabled.\nPrinting process' eligable for injection\n");
Sleep(10000);
if(!EnumProcesses(xyProcesses, sizeof(xyProcesses), &cntbNeeded)){
exit(1);
}
abProcesses = cntbNeeded / sizeof(DWORD);
//Enumerate processes owned by current user
for(c = 0; c < abProcesses; c++){
if(xyProcesses[c] != 0){
ProcessIdentf(xyProcesses[c]);
}
}
printf("Process PID required\n");
scanf("%d", &ProcID);
FfHandle = OpenProcess(PROCESS_ALL_ACCESS,
FALSE,
ProcID);
lpv = VirtualAllocEx(FfHandle,
NULL,
BYTESIZE,
MEM_COMMIT,
0x40); //PAGE_EXECUTE_READWRITE
if(WriteProcessMemory(FfHandle, lpv, &shellptr, sizeof(shellptr), &bytescom) != 0){
ControlStructRemote = CreateRemoteThread(FfHandle,
0,
0,
(DWORD (__stdcall*) (void*)) shellptr,
0,
0,
0);
if(ControlStructRemote){
printf("POC shellcode successful.\n");
}
else{
printf("Failure, CreateRemoteThread could not spawn a remote thread or failed to exec in target process\n");
}
}
return 0;
}
void ProcessIdentf(DWORD ProcID){
//Enumerates PID and modules. Prints. Implement in loop
//unicode char, max ntfs datafile
TCHAR szProcessname[MAX_PATH] = TEXT("<unknown>");
//open proc handle
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS,
FALSE, ProcID);
//enum modules
if(NULL != hProcess){
HMODULE hMod;
DWORD cbNeed;
if(EnumProcessModules(hProcess,&hMod, sizeof(hMod),&cbNeed))
{
GetModuleBaseName(hProcess, hMod, szProcessname,
sizeof(szProcessname)/sizeof(TCHAR));
}
}
//print PID
printf("%s PID: %u\n", szProcessname, ProcID);
//close processhandle
CloseHandle(hProcess);
}
int SeDebugMode(HANDLE xyProcess, LPCTSTR DebugPriv){
HANDLE hTokenProc;
LUID xDebugVal;
TOKEN_PRIVILEGES tPriv;
if(OpenProcessToken(xyProcess,
TOKEN_ADJUST_PRIVILEGES,
&hTokenProc)){
if(LookupPrivilegeValue(NULL, DebugPriv, &xDebugVal)){
tPriv.PrivilegeCount = 1;
tPriv.Privileges[0].Luid = xDebugVal;
tPriv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hTokenProc,
FALSE,
&tPriv,
sizeof(TOKEN_PRIVILEGES),
NULL,
NULL
);
if(GetLastError() == ERROR_SUCCESS){
return TRUE;
}
}
}
return FALSE;
}
You create the remote thread at shellptr, but it should be lpv where you wrote the code to.
BTW, try to avoid PROCESS_ALL_ACCESS, only specify what exact access you need (it's all on MSDN for each API)
Related
I use this function as usual, but the debug traces (OutputDebugString) don't work from injecting dlls. And in the target application no thread is created (I look through the process hacker)
GetlastError says 0
CreateRemoteThread says tid
but WaitForSingleObject exits immediately (why if all ok!?)
... I'm confused %
OS windows 10 x64
app and dll - x86
code dll is:
#include <stdio.h>
#include <windows.h>
WINAPI DllMain(HINSTANCE h, DWORD reason, LPVOID res)
{
CHAR pszMessage[1024] = { 0 };
sprintf(pszMessage, ("L2Proj: GetCurrentProcessId() %d, hModule 0x%p, nReason %d\r\n"), GetCurrentProcessId(), h, reason);
OutputDebugString(pszMessage);
switch(reason) {
case DLL_PROCESS_ATTACH:
//MessageBoxA(NULL, "inject success", "done", MB_OK);
TerminateProcess(GetCurrentProcess(), -1);
break;
}
return TRUE;
}
PS TerminateProcess in dll doesn't work either
PPS GetExitCodeThread() after WaitForSingleObject ends is 0
What it the problem with?
ADDED
APP code is:
NOTE: This is just test code (no control over return values / wrong label name codestyle etc.), pls do not tell me about it.
I wrote step by step in the comments which functions return which values
// process of course has access
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
// handle is valid
if(!hProcess) {
return GetLastError();
}
DWORD id;
char str[] = "G:\\workspace\\proj\\test.dll";
void *l = (void*)GetProcAddress(
GetModuleHandle("kernel32.dll"), "LoadLibraryA");
// addr is valid
if(!l) {
return 35;
}
DWORD str_size = strlen(str) + 1;
// memory addr is valid
LPVOID lp = VirtualAllocEx(hProcess, NULL, str_size, MEM_COMMIT |
MEM_RESERVE, PAGE_READWRITE);
BOOL res = WriteProcessMemory(hProcess, lp, str, str_size, NULL);
// res is true
HANDLE h = CreateRemoteThread(hProcess,
NULL,
0,
(LPTHREAD_START_ROUTINE)l,
lp,
0,
&id);
// handle is valid
// id is valid (tid remote thread)
if(!h) {
return GetLastError();
}
DWORD err = GetLastError();
CHAR pszMessage[1024] = { 0 };
sprintf(pszMessage, ("L2Proj: GetProcessId() %d\r\n"), id);
OutputDebugString(pszMessage);
// ends immediately (no waiting)
WaitForSingleObject(h, INFINITE);
GetExitCodeThread(h, &id);
//id is 0 (exit code)
sprintf(pszMessage, ("L2Proj: GetExitCodeThread() %d (GetLastError=%d)\r\n"), id, err);
OutputDebugString(pszMessage);
// the only error after this function (VirtualFreeEx)
// GetLastError gives 87 (0x57) - ERROR_INVALID_PARAMETER
VirtualFreeEx(hProcess, lp, 0, MEM_RELEASE);
CloseHandle(h);
CloseHandle(hProcess);
I forgot, i use g++ (GCC) 9.3.0 - maybe the problem is because of this?
I solved the problem, just change the compiler.
Yes, the problem was with the compiler, everything works fine on the Microsoft compiler.
Thanks for answers.
problem in you not use debugger – RbMm yesterday
and yes, I always use the debugger, thanks a lot ...
I am trying to write a DLL injector to perform a DLL injector on a calculator process.
I wrote the DLL injector program in C and the DLL but the injector dosent inject the DLL or any other DLL (I tried to take some random windows DLL that the calculator doesn't use).
#include <stdio.h>
#include <Windows.h>
int main() {
LPCSTR dllpath = "C:\\Users\\......\\Dll1.dll";
printf("#### Starting ####\n");
printf("step 1: attaching the target process memory\n");
HANDLE hProcess = OpenProcess(
PROCESS_ALL_ACCESS,
FALSE,
6456 // target process id
);
if (hProcess != NULL) {
printf("step 2: allocate the target memory process\n");
LPVOID dllPathMemoryAddr = VirtualAllocEx(
hProcess,
NULL,
strlen(dllpath),
MEM_RESERVE | MEM_COMMIT,
PAGE_EXECUTE_READWRITE
);
if (dllPathMemoryAddr != NULL) {
printf("step 3: write to the process memory\n");
BOOL succeededWriting = WriteProcessMemory(
hProcess,
dllPathMemoryAddr,
dllpath,
strlen(dllpath),
NULL
);
if (succeededWriting) {
printf("step 4: execute.\n");
FARPROC loadLibAddr = GetProcAddress(
GetModuleHandle(TEXT("kernel32.dll")),
"LoadLibraryA"
);
HANDLE rThread = CreateRemoteThread(
hProcess,
NULL,
0,
(LPTHREAD_START_ROUTINE)loadLibAddr,
dllPathMemoryAddr,
0,
NULL
);
}
}
CloseHandle(hProcess);
}
return TRUE;
}
after running the injector I get this output:
#### Starting ####
step 1: attaching the target process memory
step 2: allocate the target memory process
step 3: write to the process memory
step 4: execute.
after that, I am still unable to see in process explorer the new DLL.
You are calling GetProcAddress() to get the address of LoadLibraryA(), this is returning the address of LoadLibraryA in your local process not the injected one. This is not guaranteed to be correct in the external process. You do not need to get the address manually, CreateRemoteThread will resolve the address for you.
Here is a very simple injector example that will explain how to do it
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
DWORD GetPid(char * targetProcess)
{
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap && snap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (Process32First(snap, &pe))
{
do
{
if (!_stricmp(pe.szExeFile, targetProcess))
{
CloseHandle(snap);
return pe.th32ProcessID;
}
} while (Process32Next(snap, &pe));
}
}
return 0;
}
int main()
{
char * dllpath = "C:\\Users\\me\\Desktop\\dll.dll";
char * processToInject = "csgo.exe";
long pid = 0;
while (!pid)
{
pid = GetPid(processToInject);
Sleep(10);
}
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
if (hProc && hProc != INVALID_HANDLE_VALUE)
{
void * loc = VirtualAllocEx(hProc, 0, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(hProc, loc, dllpath, strlen(dllpath) + 1, 0);
HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, loc, 0, 0);
CloseHandle(hThread);
}
CloseHandle(hProc);
return 0;
}
I found the problem. I compiled the DLL as 64 but accidentally compiled the DLL injector has complied as 32 bit.
I would like to print/make a stacktrace of a running process from within my c application (not c++) using the windows api.
Currently I have this code:
void StackTrace(int pid)
{
unsigned int i;
void *stack[STACK_BUFFER];
unsigned short frames;
SYMBOL_INFO *symbol;
HANDLE process;
process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
SymInitialize(process, NULL, TRUE);
frames = RtlCaptureStackBackTrace(0, STACK_BUFFER, stack, NULL);
symbol = (SYMBOL_INFO *)calloc(sizeof(SYMBOL_INFO) + 256 * sizeof(char), 1);
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
for (i = 0; i < frames; i++) {
SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol);
if (symbol->NameLen != 0)
printf("%s at %09x\n", symbol->Name, symbol->Address);
}
free(symbol);
}
But the problem is that when I run it on a process it always gives me the same results, even when the application is stack tracing itself. Can you help me with this?
EDIT: The problem is that it always gives the same symbol name and address.
You're capturing the stack trace of your current thread when you're using RtlCaptureStackBackTrace in this way. I think that what you're looking for is: StackWalkEx
My OS is Windows 8.1 64 bit . My program is to inject a DLL file to a target process,and when this DLL file attached to a process , it will create a .txt file on D: and write some words into it and save .It is just a test.But when I compile my program as a 32 bit program and my DLL code is compiled as 32 bit , it succeed , it can create the file and save the content . But when I compile my code of DLL and my program as 64 bit , it hasnot throw any exception , all seems that it succeed . But you cannot find the .txt file it create . So , it fails , not excuting the things you want to do .
The follow is my code of my DLL
#include "stdafx.h"
#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
BOOL create();
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
create();
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
BOOL create()
{
wchar_t FileName[] = L"D:\\x64injecttest.txt";
HANDLE hFile = ::CreateFile(FileName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, NULL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("createfile fails,the error code is:%u\n", GetLastError());
system("PAUSE");
return 0;
}
char str[] = "if you see this file,then you have success\n";
WriteFile(hFile, str, strlen(str) + 1, NULL, NULL);
CloseHandle(hFile);
return TRUE;
}
The follow is the code of my program
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<TlHelp32.h>
LPTHREAD_START_ROUTINE lpThreadProc; //pointes to the address of LoadLibraryW API
typedef DWORD(WINAPI *pFunction)(PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, LPVOID ObjectAttributes, HANDLE ProcessHandle, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, BOOL CreateSuspended, DWORD dwStackSize, DWORD dw1, DWORD dw2, LPVOID pUnknown); //I inject DLL to other process with the NtCreateThreadEx API , and this function pointer would point to the address of this API
DWORD SearchForTarget(wchar_t target[])
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);
HANDLE hSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap == INVALID_HANDLE_VALUE)
{
printf("fails when createtoolhelp32snapshot,the error code is:%u\n", GetLastError());
system("PAUSE");
exit(-1);
}
BOOL b = ::Process32First(hSnap, &pe32);
while (b)
{
printf("the process name is:%ws\n", pe32.szExeFile);
printf("the process id is:%u\n", pe32.th32ProcessID);
if (wcscmp(pe32.szExeFile, target) == 0)
return pe32.th32ProcessID;
b = Process32Next(hSnap, &pe32);
}
return -1;
}
BOOL InjectDLL(DWORD pid)
{
wchar_t DLLPath[] = L"C:\\Users\\Dell-pc\\Desktop\\x64InjectTest\\Debug\\DLL.dll";
DWORD length = wcslen(DLLPath);
DWORD trueLength = length * 2 + 2;
HANDLE hProcess = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
if (hProcess == INVALID_HANDLE_VALUE)
{
printf("openprocess fails,the error code is:%u\n", GetLastError());
system("PAUSE");
exit(-1);
}
LPVOID pBaseAddress = ::VirtualAllocEx(hProcess, NULL, trueLength, MEM_COMMIT, PAGE_READWRITE);
if (pBaseAddress == NULL)
{
printf("virtualallocex fails,the error code is:%u\n", GetLastError());
system("PAUSE");
exit(-1);
}
BOOL b = WriteProcessMemory(hProcess, pBaseAddress, DLLPath, trueLength, NULL);
if (b == 0)
{
printf("writeprocessmemory fail,the error code is:%u\n", GetLastError());
system("PAUSE");
exit(-1);
}
HMODULE hModule = ::LoadLibrary(L"kernel32.dll");
lpThreadProc = (LPTHREAD_START_ROUTINE)::GetProcAddress(hModule, "LoadLibraryW");
HMODULE hNtdll = ::LoadLibrary(L"ntdll.dll");
pFunction pFunc = (pFunction)GetProcAddress(hNtdll, "NtCreateThreadEx");
printf("it is ready to create thread\n");
HANDLE hRemoteThread;
pFunc(&hRemoteThread, 0x1FFFFF, NULL, hProcess, lpThreadProc, pBaseAddress, FALSE, NULL, NULL, NULL, NULL);
if (hRemoteThread == NULL)
{
printf("nrcreateprocessex fails,the error code is:%u\n", GetLastError());
system("PAUSE");
exit(-1);
}
WaitForSingleObject(hRemoteThread, INFINITE);
return TRUE;
}
int main()
{
wchar_t target[] = L"notepad.exe"; //inject my DLL to notepad.exe
DWORD pid = SearchForTarget(target);
if (pid == -1)
{
printf("not find the target \n");
system("PAUSE");
return -1;
}
InjectDLL(pid);
system("PAUSE");
return 0;
}
I compile my code (both my program and my DLL ) as 32 bit , and run it on my Windows 8.1 64 bit OS , it succeed . But when I compile it (both my program and my DLL) as 64 bit , it hasnot throw any exception , and it seems it succeed , only except it has not create the file and write some words into it (and this is what should do when the DLL attached to the process ) . So , anyone know where the problem is ? One more thing , I use Visual Studio 2013 .
I'd guess that the line causing you the 32/64-bit problem in your example is the following.
lpThreadProc = (LPTHREAD_START_ROUTINE)::GetProcAddress(hModule,
"LoadLibraryW");
This gives you the address of LoadLibraryW in your current process, not that target process. Given the target process is 64-bit, the address is 99.99999% going to be different.
Even within 32-bit processes you shouldn't generally assume that DLLs will always load into the same address footprint.
To get around your issue you will probably have to enumerate modules within the target process and find your entry point from there. There are API's to help with this. A google for GetRemoteProcAddress will also point you in the right direction.
That aside, there are many other issues with your loader. Personally I'd advise you to use one that someone else has already written. There used to be plenty of good loaders around that cover many of the caveats and have multiple injection mechanisms too.
Thanks everyone , I have solved the problem . About the function NtCreateThreadEx , the type of the 8th , 9th and 10 th paramter (the stacksize parameter, the dw1 parameter , the dw2 parameter) should be SIZE_T , not DWORD . If it is DWORD , the it has no problem when you compile the code as 32 bit , but it would not work if you compile it as 64 bit .
So , this line of code should be written as below
typedef NTSTATUS (WINAPI *pFunction)(PHANDLE ThreadHandle, ACCESS_MASK DesiredAccess, LPVOID ObjectAttributes, HANDLE ProcessHandle, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, BOOL CreateSuspended, SIZE_T dwStackSize, SIZE_T dw1, DWORD SIZE_T, LPVOID pUnknown);
Basically, I have a program which will be launched more than once. So, there will be two or more processes launched of the program.
I want to use the Win32 API and kill/terminate all the processes with a specific name.
I have seen examples of killing A process, but not multiple processes with the exact same name(but different parameters).
Try below code, killProcessByName() will kill any process with name filename :
#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
void killProcessByName(const char *filename)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof (pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes)
{
if (strcmp(pEntry.szExeFile, filename) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD) pEntry.th32ProcessID);
if (hProcess != NULL)
{
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
int main()
{
killProcessByName("notepad++.exe");
return 0;
}
Note: The code is case sensitive to filename, you can edit it for case insensitive.
I just ran into a similar problem. Here's what I came up with...
void myClass::killProcess()
{
const int maxProcIds = 1024;
DWORD procList[maxProcIds];
DWORD procCount;
char* exeName = "ExeName.exe";
char processName[MAX_PATH];
// get the process by name
if (!EnumProcesses(procList, sizeof(procList), &procCount))
return;
// convert from bytes to processes
procCount = procCount / sizeof(DWORD);
// loop through all processes
for (DWORD procIdx=0; procIdx<procCount; procIdx++)
{
// get a handle to the process
HANDLE procHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procList[procIdx]);
// get the process name
GetProcessImageFileName(procHandle, processName, sizeof(processName));
// terminate all pocesses that contain the name
if (strstr(processName, exeName))
TerminateProcess(procHandle, 0);
CloseHandle(procHandle);
}
}
void kill(std::string filename, int delay)
{
filename += ".exe";
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes) {
if (filename.c_str() == pEntry.szExeFile) {
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0, (DWORD)pEntry.th32ProcessID);
if (hProcess != NULL) {
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
// usage
int main()
{
kill("notepad");
}
I know this is old but i feel as if i should explain some of the issues and bad practice with the 2011 anwer. There is absolutely no reason for you to be writing c in c++ unless you need to. The use of const char array is unnecessary as std::string::c_str() already returns a pointer to the string. As you can see in my snippet... - filename is no longer a const char, instead its a string because its native c++ and good practice - strcmp check is removed as there is no reason to compare string differences. Instead we check if they're equivalent - We append ".exe" to filename so you can type the process name without the .exe There is simply no reason to write c in c++ unless its mandatory.