Im using OllyDbg to reverse engineer an executable for my lab assignment. My professor has asked a question asking for the APIs responsible for writing output to the command prompt. The DLLS used were ntdll, kernel32, msvcr100
There are more than a couple of ways to achieve this but the famous two are WriteConsole and WriteFile.
From MSDN documentation:
WriteConsole
Writes a character string to a console screen buffer beginning at the
current cursor location.
BOOL WINAPI WriteConsole(
_In_ HANDLE hConsoleOutput,
_In_ const VOID *lpBuffer,
_In_ DWORD nNumberOfCharsToWrite,
_Out_ LPDWORD lpNumberOfCharsWritten,
_Reserved_ LPVOID lpReserved
);
WriteFile
Writes data to the specified file or input/output (I/O) device. This
function is designed for both synchronous and asynchronous operation.
BOOL WINAPI WriteFile(
_In_ HANDLE hFile,
_In_ LPCVOID lpBuffer,
_In_ DWORD nNumberOfBytesToWrite,
_Out_opt_ LPDWORD lpNumberOfBytesWritten,
_Inout_opt_ LPOVERLAPPED lpOverlapped
);
...
...
Characters can be written to the screen buffer using WriteFile with a
handle to console output. The exact behavior of the function is
determined by the console mode. The data is written to the current
cursor position. The cursor position is updated after the write
operation.
Related
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]
I am trying to use UrlDownloadToFile OR InternetOpenUrl to visit some link on the Internet from an DLL file. While it works on an .exe file, but it didn't work from a DLL file, and even no any error information. It just failed without any information.
Anyone could give me any help? Thanks in advance.
My code are as below:
extern "C" __declspec(dllexport) int __stdcall Hello()
{
HINTERNET hInt=NULL, hUrl=NULL;
hInt = InternetOpenA("Test Agent", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
hUrl = InternetOpenUrlA(hInt, "http://www.google.com.au", NULL, 0, INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE, 0);
if (hUrl)
{
InternetCloseHandle(hUrl);
}
InternetCloseHandle(hInt);
return 0;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
Hello();
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
It failed at:
hUrl = InternetOpenUrlA(hInt, "http://www.google.com.au", NULL, 0, INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_CACHE_WRITE, 0);
Or:
typedef HRESULT (__stdcall * lpURLDownloadToFile) (LPUNKNOWN pCaller, LPCTSTR szURL, LPCTSTR szFileName, DWORD dwReserved, LPBINDSTATUSCALLBACK lpfnCB);
extern "C" __declspec(dllexport) int __stdcall Hello()
{
HMODULE hModule = LoadLibraryW(L"urlmon.dll");
lpURLDownloadToFile urlD = (lpURLDownloadToFile)GetProcAddress( hModule, "URLDownloadToFileW" );
HRESULT aa = urlD(NULL, L"http://www.google.com.au", L"C:\\Test\\a.html", 0, NULL);
return 0;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
Hello();
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
It failed at:
HRESULT aa = urlD(NULL, L"http://www.google.com.au", L"C:\\Test\\a.html", 0, NULL);
Update:
If I insert a line like "MessageBox" just above where it fails, the MessageBox will be displayed successfully.
If I insert a line like "MessageBox" just after where it fails, the MessageBox will not be displayed. And there is no any error code returned if I tried to display "hUrl" or "aa".
Don't do that in DllMain. See DllMain entry point
The entry-point function should perform only simple initialization or
termination tasks. It must not call the LoadLibrary or LoadLibraryEx
function (or a function that calls these functions), because this may
create dependency loops in the DLL load order. This can result in a
DLL being used before the system has executed its initialization code.
EDIT, as you want to inject the Dll and run code in it.
One way to make an injected Dll to start executing code, without relying on DllMain is as follow:
Use a message hook, limited to one thread.
Find a HWND belonging to the process you want to inject. For Internet Explorer, you may enumerate the Top Level Windows, using EnumWindows A main IE Windows has a class IEframe. Use EnumChildWindows to find a window of class Internet_Explorer Server. Use GetWindowThreadProcessId to get the associated TID (Thread Identifier).
Use SetWindowsHookEx to install a thread hook. You may choose a WH_CALLWNDPROC
or a WH_GETMESSAGE hook. Pass the TID obtained in 1. Your DLL is injected, and is processing messages.
Use PostMessage or SendMessage or PostThreadMessage, depending on the hook type you choose in 2, with a registered message. See RegisterWindowMessage
In your hook function, filter for the registered message (obtain it's value in your DllMain and store it in a global variable) and when this message is received, call your custom code.
Warning: this technique is well suited for short living code, you are in a hook function. That's maybe not the place for downloading from the Internet.
Another way is to create a thread in DllMain, using _beginthreadex
In the thread, you may have a classic RegisterClass / CreateWindow / GetMessage/ DispatchMessage sequence, and your EXE will be able to Send/Post messages to your Dll.
Warning: depending on how you injected the Dll, you must be very carreful about premature unloading of your Dll. If the thread still runs, there may be crashes. Being clean and stable with theses things is not easy. But, if you are just playing/experimenting, don't bother and just LoadLibrary (not in DllMain) you own library a second time, it will stay here forever.
You can mix the two techniques, that is: use a thread message hook to inject the Dll and start a thread in the hook function.
Basically, I am trying to control a USB device (a linear actuator control board) using the supplied DLL (mpusbapi.dll) and header file (mpusbapi.h). However, I can't for the life of me figure out which parameters I need to pass into MPUSBWrite().
In particular, the 2nd, 3rd and 4thparameters of MPUSBWrite(). The first parameter is clearly the handle that is returned by MPUSBOpen() and the last parameter is a timeout in ms.
I have a hunch it has something to do with page 6 of LAC advance config.
Any help is GREATLY appreciated. Thanks!
mpusbapi.h file
#ifndef _MPUSBAPI_H_
#define _MPUSBAPI_H_
#define MPUSB_FAIL 0
#define MPUSB_SUCCESS 1
#define MP_WRITE 0
#define MP_READ 1
// MAX_NUM_MPUSB_DEV is an abstract limitation.
// It is very unlikely that a computer system will have more
// then 127 USB devices attached to it. (single or multiple USB hosts)
#define MAX_NUM_MPUSB_DEV 127
DWORD (*MPUSBGetDLLVersion)(void);
DWORD (*MPUSBGetDeviceCount)(PCHAR pVID_PID);
HANDLE (*MPUSBOpen)(DWORD instance, // Input
PCHAR pVID_PID, // Input
PCHAR pEP, // Input
DWORD dwDir, // Input
DWORD dwReserved); // Input <Future Use>
DWORD (*MPUSBRead)(HANDLE handle, // Input
PVOID pData, // Output
DWORD dwLen, // Input
PDWORD pLength, // Output
DWORD dwMilliseconds); // Input
DWORD (*MPUSBWrite)(HANDLE handle, // Input
PVOID pData, // Input
DWORD dwLen, // Input
PDWORD pLength, // Output
DWORD dwMilliseconds); // Input
DWORD (*MPUSBReadInt)(HANDLE handle, // Input
PVOID pData, // Output
DWORD dwLen, // Input
PDWORD pLength, // Output
DWORD dwMilliseconds); // Input
BOOL (*MPUSBClose)(HANDLE handle);
#endif
LACTesting.cpp file
#include <windows.h> // This is a windows header file. The functions I mentioned above are declared here
#include "mpusbapi.h" // This is the header file supplied. It declares the function prototypes that are defined in the DLL
#include <iostream>
#include "ioctls.h"
using namespace std;
int main(int argc, char* argv)
{
// Try to load the library
HMODULE mpbusDLL = NULL;
mpbusDLL = LoadLibrary(L"mpusbapi.dll");
if (mpbusDLL != NULL) {
// If the library could be loaded, then load the functions using GetProcAddress()
// Load the function 'MPUSBOpen' from the DLL
MPUSBOpen = (HANDLE(*)(DWORD, PCHAR, PCHAR, DWORD, DWORD)) GetProcAddress(mpbusDLL, "_MPUSBOpen");
MPUSBOpen=(HANDLE(*)(DWORD,PCHAR,PCHAR,DWORD,DWORD))GetProcAddress(mpbusDLL,"_MPUSBOpen");
MPUSBGetDLLVersion=(DWORD(*)(void))GetProcAddress(mpbusDLL,"_MPUSBGetDLLVersion");
MPUSBGetDeviceCount=(DWORD(*)(PCHAR))GetProcAddress(mpbusDLL,"_MPUSBGetDeviceCount");
MPUSBWrite=(DWORD(*)(HANDLE,PVOID,DWORD,PDWORD,DWORD))GetProcAddress(mpbusDLL,"_MPUSBWrite");
MPUSBRead=(DWORD(*)(HANDLE,PVOID,DWORD,PDWORD,DWORD))GetProcAddress(mpbusDLL,"_MPUSBRead");
MPUSBReadInt=(DWORD(*)(HANDLE,PVOID,DWORD,PDWORD,DWORD))GetProcAddress(mpbusDLL,"_MPUSBReadInt");
MPUSBClose=(BOOL(*)(HANDLE))GetProcAddress(mpbusDLL,"_MPUSBClose");
}
//If the DLL didn't load, let me know!
else cout<<"DLL didn't load"<<endl;
//Declarations
HANDLE LACHandle;
PCHAR pipeName=MCHPUSB_PIPE_NAME;// intializes pipeName to "\\MCHP_EP"
PCHAR VidPid="vid_04d8&pid_fc5f";
LACHandle=MPUSBOpen(0,VidPid,pipeName,1,0);//open device connection
//Not sure if I pass in the correct arguements for MBUSBOpen. VidPid and pipeName are correct.
cout<<"Device ID "<<VidPid<<"is open with "<<MPUSBGetDeviceCount(VidPid)<<" device(s)."<<endl;
//sMPUSBWrite(LACHandle,,3,,1000); <- this is where I am having issues.
//I can't figure out how to use MPUSBWrite
MPUSBClose(LACHandle);// closes device connection
}
I think you should take a look at
Win32 Data Types
then work on Windows System Programming samples, then you will clearly understand the logic.
To your question, as i see the code i can guess
// yourData which want to write
PVOID pData
// sizeof(yourData) google "sizeof"
DWORD dwLen
/* I have no idea about this, but its output you can see it
after running function */
PDWORD pLength
Hope this helps
We have an out of process COM application that was written in C++ that implements are networking protocol. When a packet of data is received a callback is invoked into the application that registered for the packet.
The callback interface is defined as such:
[helpstring("method MessageHandler")] HRESULT MessageHandler([in,size_is(nSize)] char * szBuf, int nSize, DWORD dwTransCode, DWORD dwSenderID, BSTR bstrFromIP);
Using this in C++ has not been an issue. We now have a case where we have a C++/CLI application that needs to receive callbacks. After hacking away until the compiler was happy, I arrived at the following implementation:
ref class MessageHandlerClass : public MessageRouterCallback
{
public:
virtual void MessageHandler(signed char %buffer, int size, unsigned int msgId, unsigned int fromId, System::String^ fromIp)
{
switch (msgId)
{
case MaintenanceMsgs::maintenance_event_message::ID:
{
SomeStructure msg;
myHandler->HandleMaintenanceEvent(&msg);
}
}
}
This is my first foray into C++/CLI.
First Question: What they heck does '%' mean in 'signed char %buffer'?
Second Question: I can place a breakpoint and see that the callback is getting called. I can look at the 'buffer' argument in the memory debugger and it contains the data I expect. I have been VERY unsuccessful at pulling that data out and placing it into the variable 'msg'. I know I can't do a cast like in C++, but every example I've been tried (Mostly InteropServices::Marshal and some pin_ptr stuff) doesn't seem to get me anywhere.
SomeStructure is declared in a header file and is included by both the C++ and the C++/CLI application. SomeStructure contains 2 unsigned shorts followed by three character arrays.
Any direction on where to go from here would be greatly appreciated.
Ok. It just 'clicked'... So I'll answer my own question here.
First Question: What they heck does '%' mean in 'signed char %buffer'?
The '%' just means its 'tracked' and will be garbage collected, or at least that's what I think it means :)
Second Question: How to marshal.
First I had to get to the 'internal pointer' and C++/CLI provides the & operator for that. Then I was able to simply memcpy the data over.
pin_ptr<signed char> p = &buffer;
MaintenanceMsgs::maintenance_event_message msg;
memcpy((void*)&msg, (void*)p, sizeof(msg));
myHandler->HandleMaintenanceEvent(&msg);
Is this safe?
Dear MFC/ActiveX/COM cracks, I have 'inherited' the source of an old MFC application (originally created with Visual Studio 6)
which builds and runs so far in VS 2010, but has embedded some ActiveX controls as source code, apparently generated by the
Visual Studio wizard (.h and .cpp files, see below);
however not in an own subproject so that a .dll or .ocx file are generated.
Here is the relevant part of the header file of one such control:
#if !defined(AFX_CHARTFX_H__F8A080E0_0647_11D4_92B0_0000E886CDCC__INCLUDED_)
#define AFX_CHARTFX_H__F8A080E0_0647_11D4_92B0_0000E886CDCC__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
/////////////////////////////////////////////////////////////////////////////
// CChartfx wrapper class
class CChartfx : public CWnd
{
protected:
DECLARE_DYNCREATE(CChartfx)
public:
CLSID const& GetClsid()
{
static CLSID const clsid
= { 0x8996b0a1, 0xd7be, 0x101b, { 0x86, 0x50, 0x0, 0xaa, 0x0, 0x3a, 0x55, 0x93 } };
return clsid;
}
virtual BOOL Create(LPCTSTR lpszClassName,
LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect,
CWnd* pParentWnd, UINT nID,
CCreateContext* pContext = NULL)
{ return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID); }
BOOL Create(LPCTSTR lpszWindowName, DWORD dwStyle,
const RECT& rect, CWnd* pParentWnd, UINT nID,
CFile* pPersist = NULL, BOOL bStorage = FALSE,
BSTR bstrLicKey = NULL)
{ return CreateControl(GetClsid(), lpszWindowName, dwStyle, rect, pParentWnd, nID,
pPersist, bStorage, bstrLicKey); }
//rest of header file omitted
Note that this class inherits from CWnd and not some
OCX class. But since all MFC windows are COM components (as I read somewhere) and this is generated
code it should have worked some time ago. I also read that this may be really a migration gap
which occurred somewhere before 2005.
Also note the DECLARE_DYNCREATE, so I think this is late binding, using the IDispatch interface.
So MFC will call a Create() function for us.
The above control is used via aggregation by an encompassing CDialog (also created with VS wizard):
//... analysedlg.h - leading auto-generated stuff omitted
class CAnalyseDlg : public CDialog
{
CChartfx m_chhrtfx;
//... enum for resource ID, DoDataExchange, message map, other members…
}
The dialog, in turn, is embedded in a view class of the application (again, via a member variable) and
created by invoking DoModal() in a menu item event handler.
So, when I click on the corresponding menu item, I get an m_hWnd NULL assertion and when hitting
'retry' in the popped up dialogue, the following stack (excerpt):
mfc100d.dll!COleControlContainer::FillListSitesOrWnds(_AFX_OCC_DIALOG_INFO * pOccDlgInfo) line 925 + 0x23 Bytes C++
mfc100d.dll!COccManager::CreateDlgControls(CWnd * pWndParent, const char * lpszResourceName, _AFX_OCC_DIALOG_INFO * pOccDlgInfo) line 410 C++
mfc100d.dll!CDialog::HandleInitDialog(unsigned int __formal, unsigned int __formal) line 715 + 0x22 Bytes C++
mfc100d.dll!CWnd::OnWndMsg(unsigned int message, unsigned int wParam, long lParam, long * pResult) line 2383 + 0x11 Bytes C++
mfc100d.dll!CWnd::WindowProc(unsigned int message, unsigned int wParam, long lParam) line 2087 + 0x20 Bytes C++
mfc100d.dll!AfxCallWndProc(CWnd * pWnd, HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) line 257 + 0x1c Bytes C++
mfc100d.dll!AfxWndProc(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) line 420 C++
mfc100d.dll!AfxWndProcBase(HWND__ * hWnd, unsigned int nMsg, unsigned int wParam, long lParam) line 420 + 0x15 Bytes C++
user32.dll!766162fa()
[missing frames omitted by me]
mfc100d.dll!CWnd::CreateDlgIndirect(const DLGTEMPLATE * lpDialogTemplate, CWnd * pParentWnd, HINSTANCE__ * hInst) line 366 + 0x2a Bytes C++
mfc100d.dll!CDialog::DoModal() line 630 + 0x20 Bytes C++
In the VS debug output there are the following lines:
CoCreateInstance of OLE control {8996B0A1-D7BE-101B-8650-00AA003A5593} failed.
>>> Result code: 0x80040154
>>> Is the control is properly registered?
Warning: Resource items and Win32 Z-order lists are out of sync. Tab order may be not defined well.
So apparently the call to CoCreateInstance had already been done and silently failed without an assertion
which would have been nice to have had. Does anybody know where this is?
My central question is whether it is correct that in this case normally MFC would take care for
registering the control even if it is not in an .dll or .ocx project and that it must have worked
like this in the past. I read somewhere that CreateDlgIndirect with a DialogTemplate is a way of
creating ActiveX controls without needing a .dll or .ocx file. In the above stack, this is called,
too, but not for the ActiveX control, but for the dialogue instead.
Does anyone know more about this issue and how to fix it?
If I do have to manually register the controls, e.g. using regsvr32.exe or via source code,
is there a way without .dll or .ocx files? Or do I have to repackage the ActiveX components in
their own projects (what would be more component-based/modular anyway)?
I hope my problem description is precise enough and I would be very thankful for any answer.
Kind regards.
I've just run into this when using an old ActiveX control. Apparently it was apartment threaded and I was trying to call CoInitializeEx() with COINIT_MULTITHREADED.