Reflective DLL injected code crashing on ofstream.open() - dll

I am trying to load a library via reflective DLL injection, but it crashes on calling ofstream.open(); calling fopen() yields the same result.
For reflective dll injection i basically follow the steps described at https://0x00sec.org/t/reflective-dll-injection/3080:
Load the dll contents in a buffer
Create a file mapping and map view of file, then copying the NT headers and sections there.
Copy the contents of the mapping to a buffer and close the mapping.
Rebuild the import table.
Rebuild relocations.
Allocate memory in a target suspended process and copy the buffer there.
CreateRemoteThread to start the dllMain (while the target process is still suspended).
The code gets loaded and the dllmain is executed.
My dllmain looks like this:
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
logFile.open("hookLog.txt", std::ios::out);
logFile << "DLL Attached\n";
HRESULT nResult = InitCoCreateInstanceHook();
logFile << "Hook initialized with result: " << std::to_string(nResult) << "\n";
logFile.flush();
}
And it crashes while opening the log file. I know exeption handling is not set up when I execute the code, could that be the issue? Am I missing something else?
Thanks in advance.

Related

Using custom DLL with Lua 5.1

I'm trying to use a custom DLL from within Lua. I have a simple DLL, for example, like
extern "C"
{
static int function_1(lua_State* L)
{
std::cout << "[DLL]this is a custom function" << std::endl;
lua_pushnumber(L, 10);
return 1;
}
__declspec(dllexport) int __cdecl luaopen_myDLL(lua_State* L)
{
L = luaL_newstate();
luaL_openlibs(L);
std::cout << "[DLL] being initialized!" << std::endl;
lua_register(L, "fun1", function_1);
luaL_dofile(L, "./run.lua");
return 1;
}
}
written in VS and built as dll.
After running within Lua
package.loadlib("./myDLL.dll", "luaopen_myDLL")()
or
require("myDLL")
the DLL is loaded and runs like expected and also runs the specified run.lua that execute function_1 just fine.
The run.lua has nothing special in it, just something like
f = function_1()
print("[Lua] Function_1 says", f, "\n");
My current issues now are:
I cannot run function_1() from the initial Lua script calling the DLL. Trying to do that I get
attempt to call global 'function_1' (a nil value)
i must use L = luaL_newstate(); inside my C code. For some reason, it doesn't work with the passed lua_State*, which I think is the reason why I cannot call the registered functions from the LUA script loading my DLL. Before running luaL_newstate() my lua_State has a valid address which doesn't change after the newstate.
I could theoretically run any Lua script from within my C library executing the registered functions, but this seems more like a dirty workaround to me.
My question now is if I'm missing something essential?
p.s.: I'm using Lua 5.1
The code below should work. It may not work because of the following reasons:
your binary you use to run initial Lua script (that has require("myDLL") in it) has a different Lua version and/or does not use shared dll.
your Lua headers you use in your C++ code have different Lua version from original lua.exe
you link your project against different Lua version
you compile Lua again with your solution (you must use only headers and already provided .lib file with Lua distribution, if you want to use lua.exe)
To make your code available in Lua you must use Lua headers for proper Lua version and link against proper .lib file and use lua.exe that uses shared library (lua.dll, I guess).
static int function_1(lua_State* L)
{
std::cout << "[DLL]this is a custom function" << std::endl;
lua_pushnumber(L, 10);
return 1;
}
extern "C" int __declspec(dllexport) luaopen_quik(lua_State *L) {
std::cout << "[DLL] being initialized!" << std::endl;
lua_register(L, "fun1", function_1);
luaL_dofile(L, "./run.lua");
return 0;
}
P. S. please provide your solution files so I can help further because it is not an issue with the code. -- it's the linkage issue.

Troubleshooting an Exit Code 80131506 appcrash when marshalling an unmanaged array to a managed one

I have a managed application that has to read binary data from proprietary files with an unmanaged third-party Win32-only DLL. I keep infrequent crashes where my application simply exits without any exception etc. In the application log in the system, I get the well-known exit code 80131506. Directly after this entry, I get an "Application error" where the faulting module is clr.dll.
In my managed code, where I have the control, I added lots of debug logging (Thanks, log4net) and found out that it crashes at this piece of code:
double* buf = new double[bufSize];
try {
for(SliceIterator iter = numericSlice.begin(); valuesLeft > 0;) {
size_t transferred;
numericSlice.getValuesToArray(iter, buf, bufSize, transferred); // transferred is set to the number of values which were written to the buf array, iter is advanced automatically
valuesLeft -= transferred;
array<double>^ out = gcnew array<double>(transferred);
System::Runtime::InteropServices::Marshal::Copy(IntPtr((void*)buf), out, 0, transferred); // <- crashes here
valueReadCallback(domainId, channelId, out);
}
} finally {
delete buf;
}
The SliceIterator and numericSlice with its getValuesToArray method come from the unmanaged DLL, and what I want to accomplish is that I want to drag the contents of the buf array to the out array which is a managed one. The valueReadCallback is a System.Action that I get into the method where this code is called as a parameter. I have to do it this complicated because the vendor of the third party DLL implemented his own reference counting which goes wonky when I use it in managed code. So I have to stay in just one scope while I do all the nasty unmanaged stuff, collect everything and somehow blast it out to the managed side while still in there.
Now, my questions are: Am I doing this right? Does the Marshal::Copy really do a deep copy or just some "clever" re-referencing?

How to find the entry point(or base address) of a process - take care of ASLR

Because of ASLR(Address space layout randomization, since Windows Vista), the base address of an exe is random, so it can't be found in PE file anymore.
In Visual C++ now the /DYNAMICBASE option is default enabled, so the base address
of an exe is random - everytime the loader loads it, it happens.
After did some research on google, I am trying to use this pattern,
But it doesn't work.
Please have a look at this simple code sample:
#include <iostream>
#include <vector>
#include <stdio.h>
#include <windows.h>
#include <psapi.h>
int main()
{
STARTUPINFOA startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
PROCESS_INFORMATION processInformation = {0};
if (CreateProcessA("UseCase01.exe", NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &startupInfo, &processInformation))
{
std::vector<HMODULE> buf(128);
DWORD needed = 0;
for (;;) {
if (EnumProcessModulesEx(processInformation.hProcess, &buf[0], DWORD(buf.size()*sizeof(HMODULE)), &needed, LIST_MODULES_ALL) == FALSE) {
DWORD ec = GetLastError();
std::cout << ec << std::endl;
break;
}
else if (needed <= buf.size() * sizeof(HMODULE)) {
break;
}
else {
const size_t oldSize = buf.size();
buf.resize(oldSize * 2);
}
}
ResumeThread(processInformation.hThread);
}
}
My OS is Windows 7 64bit pro, my compiler is VS2013, this is a 32bit console program, and the UseCase01.exe is also a 32bit console program too.
EnumProcessModulesEx always fails, the error code returned by GetLastError() is 299, MSDN says what about this error code: ERROR_PARTIAL_COPY, "Only part of a ReadProcessMemory or WriteProcessMemory request was completed."
About this error code, on the EnumProcessModules's page of MSDN, "If this function is called from a 32-bit application running on WOW64, it can only enumerate the modules of a 32-bit process. If the process is a 64-bit process, this function fails and the last error code is ERROR_PARTIAL_COPY (299)."
But I am sure my program is 32bit, And, I tested on 64bit program, it fails with error 299 too, so it doesn't make sence.
"The handle returned by the CreateProcess function has PROCESS_ALL_ACCESS access to the process object." - from MSDN, so it can't be a access rights problem ?
Then I try to use CreateToolhelp32Snapshot, it fails with error code 299 too, both 32bit and 64bit.
I just can't figure it out.
My goal is find the entry point of the sub-process in a safe way, whatever it's 32bit or 64bit process.
I found this is the "deepest" answer about this question: http://winprogger.com/getmodulefilenameex-enumprocessmodulesex-failures-in-wow64/
Unfortunately, 64bit program will fails too, not only for Wow64, so it doesn't make sence.
If this is infeasible, what is the good way (find base address or entry point of a suspended sub-process)?
You are creating the process suspended. While the key kernel data structures will be created, no modules will be loaded (that would involve executing code in module entry points (dllmain)).
Thus the error makes sense: the data structures to track modules loaded will be empty, and quite possibly not allocated at all.
Put some wait it will help you it looks currently resource is not available.
On all Windows operating systems (32/64bit):
DWORD ImageBaseAddress = ((LPDWORD)PEB)[2]

DLL gives Abnormal program termination on creating ADO object

I have a few datamodules, created with C++ Builder 6. Each of them uses another datamodule that initializes the connection with the database. I'm trying to make a DLL out of those datamodules.
The error is thrown on creation of DataModule_Users and says 'Abnormal program termination'.
Where do I go wrong?
Thanks in advance
datamodule_dll.bpf
USEFORM("DataModule_Connection.cpp", DataModule_Connection); /* TDataModule: File Type */
USEFORM("DataModule_Users.cpp", DataModule_Users); /*TDataModule: File Type */
//------------------------------------------------------------------
This file is used by the project manager only and should be treated like the project file
DllEntryPoint
datamodule_DLL.cpp
int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved)
{
return 1;
}
extern "C" __declspec(dllexport) const char * GetUserName(const char * ID);
const char * GetUserName(const char * ID) {
CoInitialize(NULL); // datasets use COM
// This is used by DataModule_Users (normally this is done with Application->CreateForm();
DataModule_Connection = new DataModule_Connection( 0 /* Owner */ );
DataModule_Users = new DataModule_Users( 0 /* Owner */ );
return DataModule_Users->GetUserName(ID);
}
I will quote Remy Lebeau:
COM is initialized on a per-thread basis. Once a thread's COM model
(apartment vs multithreaded) has been set, it cannot be changed later.
If your DLL calls CoInitialize() before the caller does, your
parameters would take priority, which might not meet the caller's
needs. If you want to control the COM settings for your DMs without
affecting the caller, you have to move the DMs to their own thread.
Besides, DllEntryPoint() is not an appropriate place to initialize
them anyway. The OS restricts what DllEntryPoint() is allowed to do.
This solved the issue. I had to call coInitialize() before I load the library.

Symbian: kern-exec 3 panic on RLibrary::Load

I have troubles with dynamic loading of libraries - my code panics with Kern-Exec 3. The code is as follows:
TFileName dllName = _L("mydll.dll");
TFileName dllPath = _L("c:\\sys\\bin\\");
RLibrary dll;
TInt res = dll.Load(dllName, dllPath); // Kern-Exec 3!
TLibraryFunction f = dll.Lookup(1);
if (f)
f();
I receive panic on TInt res = dll.Load(dllName, dllPath); What can I do to get rid of this panic? mydll.dll is really my dll, which has only 1 exported function (for test purposes). Maybe something wrong with the DLL? Here's what it is:
def file:
EXPORTS
_ZN4Init4InitEv # 1 NONAME
pkg file:
#{"mydll DLL"},(0xED3F400D),1,0,0
;Localised Vendor name
%{"Vendor-EN"}
;Unique Vendor name
:"Vendor"
"$(EPOCROOT)Epoc32\release\$(PLATFORM)\$(TARGET)\mydll.dll"-"!:\sys\bin\mydll.dll"
mmp file:
TARGET mydll.dll
TARGETTYPE dll
UID 0x1000008d 0xED3F400D
USERINCLUDE ..\inc
SYSTEMINCLUDE \epoc32\include
SOURCEPATH ..\src
SOURCE mydllDllMain.cpp
LIBRARY euser.lib
#ifdef ENABLE_ABIV2_MODE
DEBUGGABLE_UDEBONLY
#endif
EPOCALLOWDLLDATA
CAPABILITY CommDD LocalServices Location MultimediaDD NetworkControl NetworkServices PowerMgmt ProtServ ReadDeviceData ReadUserData SurroundingsDD SwEvent TrustedUI UserEnvironment WriteDeviceData WriteUserData
source code:
// Exported Functions
namespace Init
{
EXPORT_C TInt Init()
{
// no implementation required
return 0;
}
}
header file:
#ifndef __MYDLL_H__
#define __MYDLL_H__
// Include Files
namespace Init
{
IMPORT_C TInt Init();
}
#endif // __MYDLL_H__
I have no ideas about this... Any help is greatly appreciated.
P.S. I'm trying to do RLibrary::Load because I have troubles with static linkage. When I do static linkage, my main program doesn't start at all. I decided to check what happens and discovered this issue with RLibrary::Load.
A KERN-EXEC 3 panic is caused by an unhandled exception (CPU fault) generated by trying to invalidly access a region of memory. This invalid memory access can be for both code (for example, bad PC by stack corruption) or data (for example, accessing freed memory). As such these are typically observed when dereferencing a NULL pointer (it is equivalent to a segfault).
Certainly the call to RLibrary::Load should never raise a KERN-EXEC 3 due to programmatic error, it is likely to be an environmental issue. As such I have to speculate on what is happening.
I believe the issue that is observed is due to stack overflow. Your MMP file does not specify the stack or heap size the initial thread should use. As such the default of 4Kb (if I remember correctly) will be used. Equally you are using TFileName - use of these on the stack is generally not recommended to avoid... stack overflow.
You would be better off using the _LIT() macro instead - this will allow you to provide the RLibrary::Load function with a descriptor directly referencing the constant strings as located in the constant data section of the binary.
As a side note, you should check the error value to determine the success of the function call.
_LIT(KMyDllName, "mydll.dll");
_LIT(KMyDllPath, "c:\\sys\\bin\\");
RLibrary dll;
TInt res = dll.Load(KMyDllName, MyDllPath); // Hopefully no Kern-Exec 3!
if(err == KErrNone)
{
TLibraryFunction f = dll.Lookup(1);
if (f)
f();
}
// else handle error
The case that you can't use static linkage should be a strong warning to you. It shows that there is something wrong with your DLL and using dynamic linking won't change anything.
Usually in these cases the problem is in mismatched capabilities. DLL must have at least the same set of capabilities that your main program has. And all those capabilities should be covered by your developer cert.