How to inject a Windows API call use ollydbg in Windows7 x64 - windows

I am using Windows7 x64, and OllyDbg 2.01(alpha 2)
I have an exe, and I want to popup a MessageBox to show some information during execution, and there is a great tutorial shows you how to do this: How to inject code into a exe file, basically, it is about adding a MessageBoxA API call with the wanted information:
PUSH 0 ; BUTTONS = <OK ONLY>
PUSH 1008751 ; CAPTION = Our adress of the "INJECTED NOTEPAD"
PUSH 1008751 ; MESSAGE = Same like above.
PUSH 0 ; ICON = <NO ICON>
CALL MessageBoxA ; Run MessageBoxA with the Params above.
It does work when in live debug session: I injected the code, and then debug it - the message box does pops up. But after I save the executable
(RMB->Edit->Select all; RMB->Edit->Copy to executable; In the new window, RMB->save file), and then execute, it just crashed.
Here are what I've observed:
Before save, the CALL MessageBoxA is actually CALL 74DAFD1E, which
means 74DAFD1E is the address of API MessageBoxA, but after save, the
address is changed to some other value.
Also, do you think ASLR would virtually stop up from injecting windows API call?
Any ideas? how could I managed to show the information I wanted from that exe?
Thanks in advance!

This is caused by ASLR, to make it work in Windows7, one approach is to disable ASLR (at your own risk).
You can download the Enhanced Mitigation Experience Toolkit (EMET) tool, install and run EMET_GUI.exe, in the pop up dialog, disable the ASLR and reboot:
You may want to re-enable ASLR after finishing your work, as it has impact on your OS's security.

Related

How can I add more 3th DLL function references in .rdata section of EXE program?

I'm working on extending the old WinAPI program (I don't have source code - only EXE) with the possibility to write debug messages on standard output. That program already uses kernel32.dll library and in the .rdata section I see a lot of references to different functions in 3th part DLLs. In order to do that I need WriteConsole function which lives in kernel32.dll. I used the simplest strategy and just copied the memory address of WriteConsole in kernel32.dll in time of debugger breakpoint. After restart of program, I was disappointed that the address doesn't point anymore into kernel32.dll WriteConsole. Instead, it pointed into another random DLL.
I wonder what is recommended and easiest option to setup properly address to that external function?
I sow that x32dgb have a section with symbols - can I use some x32dbg feature to add other functions pointers from existing DLLs?
Thank you :-)
I'll show how to add WriteConsoleA entry to IAT. This is the ANSI version of WriteConsole, when you need to output UNICODE strings, use WriteConsoleW. From your screenshot I see that currently your binary uses ANSI versions of kernel32.dll functions, for example GetStartupInfoA.
Download PETools. Run it, select Tools->Pe Editor and select your binary. A dialog box appears. Click Directories button, a new dialog box appears. Click ... button for import directory. Import directory window opens. Right click on a dll in the upper list, select Add Imports....
Enter KERNEL32.dll as dll name, WriteConsoleA in the API name edit, click + button. Click OK. Close all the windows and save changes by
clicking close, save and OK buttons. Your binary will have a new entry in IAT for WriteConsoleA function.

Why does my DLL not seem to be called?

I have a COM DLL, coded in Delphi. It should be invoked via an Active X control when a web page loads in MS IE (via soem JavaScript on the page).
Btw, this all works fine with an existing serial port interface, but I am recoding teh DLL to read from USB; all else is unchaged.
It works fine in the Delphi IDE, but not "in the field". The active X control should request it to read some input from a USB port and should then send that to the web page.
Reading from the USB device works, as I can open Notepad and see the value being written there.
The DLL will display a form, and a dialog box, and will write to the system debug trace. Since I am seeing none of these when loading the web page in MS IE, I think we can assume that Aective X control is not calling into the DLL.
In MS IE I have enabled all Active X options.
in c:\Windows\System32 (which is equivalent to c:\Windows\SysWOW64), I have regsvr32.exe -u my_dll.dll and then regsvr32.exe my_dll.dll both of which the system announced to be successful
I searched, and there is only one copy of my_dll.dll under c:\Windows
and it has the correct size and date/time
my %path% is %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem; for system and empty for user
Any idea what I am doing wrong? Or how I can go about tracking it down?
If you are loading the ActiveX control in webpage through javascript, you will have to package the control for web deployment. See this example for how to do this in your javascript and check whether you have done properly it or not:
Calling Activex Control 's Functions from javascript
Once you do the above thing correctly and open your website in IE, the web-page will at least "load" the ActiveX control. Beyond that, you can display message-boxes or write logs in your Delphi code to track down the actual coding issues.

VB6 application won't run in some computers, in others it runs fine

I have a VB6 application, the installer is compiled using INNO Setup.
The installer runs fine. But in about 10% of computers when the user clicks the Icon to run the installed app, it doesn't start, no error message, only a Beep sound.
This is happening on XP and also Win 7.
I develop in XP and Win 7 and the application works OK, so I haven't been able to reproduce the issue.
The installer registers all ocx and dlls needed (afaik). (Well not completely all, it assumes MS run-time components should be there, but I guess an error message should show up if something is missing)
I was thinking some kind of user permissions, UAC, but even users in the admin group have had the issue.
Could you point me to what possible issues to look for and test in order to patch the app.
Thanks!
[FOLLOW UP]
Thanks to the tips, found out the manifest is causing the problem. I use it to make the controls look better:
http://www.vbaccelerator.com/home/vb/code/libraries/xp_visual_styles/using_xp_visual_styles_in_vb/article.asp
Now I'm trying to discover why. I have another application with the same manifest and that one works ok.
Haven't been able to get feedback on the event viewer yet.
The "beep crash" often points to an error in an application manifest such as an XML syntax error or namspace conflict. Event Logs will often provide a hint about this.
But I've found that people often try to use the Common Controls 6.0 Library without ensuring proper library loading sequence.
Before any Forms are openend you should load shell32 and then comctl32. The easiest way is a couple of no-op calls in Sub Main:
Option Explicit
Private Declare Sub InitCommonControls Lib "comctl32" ()
Private Declare Function IsUserAnAdmin Lib "shell32" () As Long
Private Sub InitCommonControlsVB()
IsUserAnAdmin
InitCommonControls
End Sub
Private Sub Main()
InitCommonControlsVB
Form1.Show
End Sub
Without this your program will usually work fine in Vista or Win7, but will fail on some XP service pack and patch levels. Part of this is due to changes over time in the Fusion subsystem that handles SxS activation and comctl32.dll patches.
Ignore those saying you need to call InitCommonControlsEx(), it isn't necessary unless you are constructing and using Win32 controls directly instead of VB6 and COM controls.
A few things to try to narrow it down:
Check the Windows Event Log for crash events
Check the Windows Event Log (in the Application section) for crash reports from your application. You can quickly get to the log viewer on Windows XP by clicking Start > Run, typing eventvwr and pressing Enter. On Windows 7, you can type "event viewer" in the search box that is in the Start menu. You can filter the events to only show error events from your program.
You might find a few error events on one of the computers where this problem has already occured, because it sounds like the error reporting feature is turned off on these computers (in which case "hard crashes" like access violations are logged in the Event Log instead of displaying an error dialog to the end-user, as long as a debugger isn't installed on the computer).
Make sure "Error Reporting" is turned at the OS level
As mentioned in the previous section, it sounds like the error reporting feature is turned off on these computers. In that case, a crash won't display any kind of message to the end-user at all and the application will just vanish suddenly. In Windows XP, you can check this setting (and turn it on) as follows:
Right-click "My Computer" and select Properties.
Open the Advanced tab and click the Error Reporting button.
Select the Enable Error Reporting option.
Click OK to all the open windows.
Add trace code to your application
You could also add some trace code to your application's start-up code, such as code to display a message box or write a message to the Windows Event Log or to a log file as soon as your application starts (for example, in the Form_Initialize event of your main form, or in a Sub Main routine).
This way you will be able to tell whether your application is crashing before or after the VB6 runtime is loaded: if you try to start the application and it disappears/crashes, and your startup message isn't logged, then you know it's crashing before it even has a chance to get to your application's startup code, which could indicate that a dependency of the VB6 runtime or the VB6 runtime itself is not installed properly.
Note that Windows XP and Windows 7 both ship with the VB6 runtime pre-installed, but it's possible for misbehaving installers to overwrite or remove files that are part of the VB6 runtime.

Debugging application when launched via ShellExecute

I am trying to launch an application via the ShellExecute() API call. This application contains only a main function which does some processing and exits.
Now I have put DebugBreak() in starting of main. When ShellExecute() is called the application is launched successfully but it does not ask for breaking.
How can I debug my application when launched from other application using ShellExecute()?
I am using VC++ .
If DebugBreak() isn't workign for you, try _CrtDbgBreak(). Note that _CrtDbgBreak only works in a debug build.
_CrtDebugBreak definitely works for me to make a launched process break on startup, although I'm pretty sure DebugBreak does also.
Note that both functions will make it look like the process has crashed, since they raise an exception. That is normal and gives you the opportunity to attach a debugger via the crash dialog. (The crash dialog also lets you terminate the process; don't use that, obviously.)
Also note that if you have a catch-all SEH exception handler around your main then the exception raise by DebugBreak & friends will be swallowed up and the app will simply exit without showing the crash dialog or letting you attach to it.
You can't do this with VC++; with WinDbg this is just .childdbg 1 to debug all child processes. With VC++, you can use Image File Execution Options in a pinch - check out http://codereflect.com/2009/09/20/how-to-debug-child-process-using-windbgvisual-studio/ for more info. Really though, if you've got the time to learn WinDbg, it's much better at this.
you can try this, it's ok in xp system.
app.exe is your application name,
-s1...-s3 is command line arguments.
HINSTANCE hRet = ShellExecute(NULL, L"open", L"vsjitdebugger.exe", L" app.exe -s1 a1 -s2 a2 a3 -s3", szExePath, SW_SHOW);
There is now a Microsoft Child Process Debugging Power Tool.
The method I use for things like this is to embed some interactive code, which you can either delete afterwards, comment out or conditionally enable. In a few cases we have this code enabled by querying an environment variable which is set by the tool that launches the main application. This allows me to click a check box, hit launch and have the breakpoint dialog in seconds.
if (MessageBox(NULL,
_T("Attach the debugger now, then choose Yes to hit a breakpoint"),
_T("Attach Debugger"),
MB_YESNO) == IDYES)
__debugbreak();
This gives you the ability to attach the debugger when the dialog box appears and the option to hit a breakpoint or not. My earlier versions didn't give me the option and after a while I realised some of the time I wanted the breakpoint, and some of the time I didn't.

How do I disable the 'Debug / Close Application' dialog on Windows Vista?

When an application crashes on Windows and a debugger such as Visual Studio is installed the following modal dialog appears:
[Title: Microsoft Windows]
X has stopped working
A problem caused the program to stop
working correctly. Windows will close
the program and notify you if a
solution is available.
[Debug][Close Application]
Is there a way to disable this dialog? That is, have the program just crash and burn silently?
My scenario is that I would like to run several automated tests, some of which will crash due to bugs in the application under test. I don't want these dialogs stalling the automation run.
Searching around I think I've located the solution for disabling this on Windows XP, which is nuking this reg key:
HKLM\Software\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
However, that did not work on Windows Vista.
To force Windows Error Reporting (WER) to take a crash dump and close the app, instead of prompting you to debug the program, you can set these registry entries:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting]
"ForceQueue"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Windows Error Reporting\Consent]
"DefaultConsent"=dword:00000001
After this is set, when your apps crash, you should see *.hdmp and *.mdmp files in:
%ALLUSERSPROFILE%\Microsoft\Windows\WER\
See here:
http://msdn.microsoft.com/en-us/library/bb513638.aspx
regedit
DWORD HKLM or HKCU\Software\Microsoft\Windows\Windows Error Reporting\DontShowUI = "1"
will make WER silently report. Then you can set
DWORD HKLM or HKCU\Software\Microsoft\Windows\Windows Error Reporting\Disabled = "1"
to stop it from talking to MS.
I'm not sure if this refers to exactly the same dialog but here is an alternative approach from Raymond Chen:
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
I had to disable this for release automation work on Windows 64-bits for Firefox and I did the following:
gpedit.msc
Computer configuration -> Administrative Templates
Windows Components -> Windows Error Reporting
Set "Prevent display of the user interface for critical errors" to Enabled
It is similar what was accomplished for Customer Experience reporting in:
http://www.blogsdna.com/2137/fix-windows-installer-explorer-update-has-stopped-working-in-windows-7.htm
In my context, I only want to suppress the popup for my unit tests and not for the entire system. I've found that a combination of functions are needed in order to suppress these errors, such as catching unhandled exceptions, suppressing run time checks (such as the validity of the stack pointer) and the error mode flags. This is what I've used with some success:
#include <windows.h>
#include <rtcapi.h>
int exception_handler(LPEXCEPTION_POINTERS p)
{
printf("Exception detected during the unit tests!\n");
exit(1);
}
int runtime_check_handler(int errorType, const char *filename, int linenumber, const char *moduleName, const char *format, ...)
{
printf("Error type %d at %s line %d in %s", errorType, filename, linenumber, moduleName);
exit(1);
}
int main()
{
DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX);
SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)&exception_handler);
_RTC_SetErrorFunc(&runtime_check_handler);
// Run your tests here
return 0;
}
In WPF application
[DllImport("kernel32.dll", SetLastError = true)]
static extern int SetErrorMode(int wMode);
[DllImport("kernel32.dll")]
static extern FilterDelegate SetUnhandledExceptionFilter(FilterDelegate lpTopLevelExceptionFilter);
public delegate bool FilterDelegate(Exception ex);
public static void DisableChashReport()
{
FilterDelegate fd = delegate(Exception ex)
{
return true;
};
SetUnhandledExceptionFilter(fd);
SetErrorMode(SetErrorMode(0) | 0x0002 );
}
You have to implement an unhandled exception filter which simply quits your application, then set that filter function with SetUnhandledExceptionFilter().
If you're using the secure CRT, you also have to provide your own invalid parameter handler and set this with _set_invalid_parameter_handler().
This blog post has some information too:
http://blog.kalmbachnet.de/?postid=75
During test you can run with a 'debugger' like ADPlus attached which can be configured in many useful ways to collect data (minidumps) on errors and yet prevent the modal dialog problems you state above.
If you want to get some useful information when your app crashes in production you can configure Microsoft Error reporting to get something similar to ADPlus data.
This isn't a direct answer to the question since this is a workaround and the question is about how to disable that feature, but in my case, I'm a user on a server with limited permissions and cannot disable the feature using one of the other answers. So, I needed a workaround. This will likely work for at least some others who end up on this question.
I used autohotkey portable and created a macro that once a minute checks to see if the popup box exists, and if it does, clicks the button to close the program. In my case, that's sufficient, and leaves the feature on for other users. It requires that I start the script when I run the at-risk program, but it works for my needs.
The script is as follows:
sleep_duration = 60000 ; how often to check, in milliseconds.
; 60000 is a full minute
Loop
{
IfWinExist, ahk_class #32770 ; use autohotkey's window spy to confirm that
; ahk_class #32770 is it for you. This seemed to be consistent
; across all errors like this on Windows Server 2008
{
ControlClick, Button2, ahk_class #32770 ; sends the click.
; Button2 is the control name and then the following
; is that window name again
}
Sleep, sleep_duration ; wait for the time set above
}
edit: A quick flag. When other things are up, this seems to attempt to activate controls in the foreground window - it's supposed to send it to the program in the background. If I find a fix, I'll edit this answer to reflect it, but for now, be cautious about using this and trying to do other work on a machine at the same time.
After trying everything else on the internet to get rid of just in time debugger, I found a simple way that actually worked and I hope will help someone else.
Go to Control Panel
Go to Administrative Tools
Go to Services
Look down the list for Machine Debug Manager
Right Click on it and click on Properties
Under the General Tab, look for Start Up Type
Click on Disable.
Click on Apply and OK.
I haven't seen the debugger message since, and my computer is running perfectly.
Instead of changing values in the registry you can completly disable the error reporting on Windows Server 2008 R2, Windows Server 2012 and Windows 8 with: serverWerOptin /disable
https://technet.microsoft.com/en-us/library/hh875648(v=ws.11).aspx

Resources