Jump to content
Tuts 4 You

[C++] How to use isdebuggerpresent?


unix

Recommended Posts

Hi,

I want to write a little program, which should only consists out of two or three specific functions as i want then to analyse it with ollydbg and see if i can figure it out, how the asm code actually works. Unfortunately i have some problems, maybe someone can help me.

I am using Microsoft Visual C++ 2008 Express Edition as my IDE, but the code seems already a little 'overwhelmed' when i wrote a program which only prints hello world.

The basic source looks like this:

using namespace std;int _tmain(int argc, _TCHAR* argv[])
{
cout << "Hello World\n";
system("pause");
return 0;
}

When i try to analyse this with ollydbg, i get the following message when opening:

Module 'HelloWorld' has entry point outside the code (as specified in the PE header). Maybe this file is self-extracting or self-modifying. Please keep it in mind when setting breakpoints!

My program only displays hello world and has no other functions implemented, so why do i get this 'error'. I attached the file at the end.

Also i am curious, why my helloworld program looks so 'baffingly' when i accepted the message from ollydbg. It looks then like this when first launched (using Analyse code doesnt change anything):

http://img440.imageshack.us/img440/7529/ollydbg01yu2.png

Why is this? And why is the program already 40kb in size, when there is no real functionality available? I made some programs with radasm and they are very small, even with real functionalities. I mean, i know that asm programs in general very small when compared with visual basic/ delphi/ c++ programs, but why is this with my hello world - console application?

Also i dont understand yet, why i dont find the string Hello World when using Step over or Search for all referenced Text Strings.

So, that are my first problems.

Other questions i have are about some things i want to code in order to analyse it afterwards:

I want to write a program, which consists of the following three functions:

1) Isdebuggerpresent (the very basic function if there are any improvements available i am fine with the most basic one).

I just want to have implemented this function, and if isdebuggerpresent==true, the program should print DebuggerPresent and exit itself.

2) The program should check always, if there is a specific program open, such as the task-manager. I would like to do this with the caption of the window (and not the process at this point), but the sources i found on the net didnt work at all. There is something called like hinstance or hwindow or similar, but i couldn't get it to work actually.

3) The third function i would like to add to the program is that it writes itself to the autoexecute, so it always gets executed when windows starts. If it is already in the autoexecute and wasnt removed, then it should not write it there again.

The program should simulate a basic malware, although i know that such a simple virus wouldnt really harm anything and that there are many 'evilier' methods, but as i am just learning and want then afterwards to analyse it with ollydbg and write a little about my experience i made with it, it should do its purpose fine.

Another and currently last question i have, is, if i am coding in visual c++ or 'just' c++? I bought a book for learning c++, but the IDE is visual c++, so i am a litte confused.

If this visual c++ is something different, which ide (and/or compiler) you could recommend me?

Thanks for any help in advance!

HelloWorld.zip

Edited by unix
Link to comment
And why is the program already 40kb in size, when there is no real functionality available?

Because MS IDEs tend to add a whole heap of crap that you mostly don't need. For instance, I can do a C based game trainer in 9.0KB including icon in MSVC6, without EXE compression (and a hello world app can be much smaller then that). Try modifying your compiler/link settings to tune your file size.

I'll see about responding to your other stuff, later, I'm quite busy atm.

Link to comment

Okay, heres a example on the IsDebuggerPresent function.

#include <windows.h>
#include <stdio.h>BOOL isDebuggerPresent();#pragma comment(linker,"/FILEALIGN:512 /MERGE:.rdata=.text /MERGE:.data=.text /SECTION:.text,EWR /IGNORE:4078")int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
if (isDebuggerPresent())
{
MessageBox(GetForegroundWindow(),"Debugger detected!\nStop debugging me now!","HELP!",MB_ICONSTOP);
}
else
{
MessageBox(GetForegroundWindow(),"Yay!! No debugger here!",":)",MB_OK);
}
return 0;
}
BOOL isDebuggerPresent()
{
BOOL result = FALSE;
HINSTANCE kern_lib = LoadLibraryEx( "kernel32.dll", NULL, 0 );
if( kern_lib ) {
FARPROC lIsDebuggerPresent = GetProcAddress( kern_lib, "IsDebuggerPresent" );
if( lIsDebuggerPresent && lIsDebuggerPresent() ) {
result = TRUE;
}
FreeLibrary( kern_lib );
}
return result;
}

Don't mind the other code, just pay attention to the if (isDebuggerPresent()).....

Link to comment
When i try to analyse this with ollydbg, i get the following message when opening:
Module 'HelloWorld' has entry point outside the code (as specified in the PE header). Maybe this file is self-extracting or self-modifying. Please keep it in mind when setting breakpoints!

My program only displays hello world and has no other functions implemented, so why do i get this 'error'. I attached the file at the end.

Also i am curious, why my helloworld program looks so 'baffingly' when i accepted the message from ollydbg. It looks then like this when first launched (using Analyse code doesnt change anything):

http://img440.imageshack.us/img440/7529/ollydbg01yu2.png

Why is this? And why is the program already 40kb in size, when there is no real functionality available? I made some programs with radasm and they are very small, even with real functionalities. I mean, i know that asm programs in general very small when compared with visual basic/ delphi/ c++ programs, but why is this with my hello world - console application?

That is because it is a debug build. Building as a release will fix that.

To reduce the size you can define a specific entrypoint. To do that, go to your projects properties and under Linker->Advanced first option is EntryPoint, put in the field "_main" (without quotes).

Then change your example code to

using namespace std; int _main(int argc, _char* argv[])
{
cout << "Hello World\n";
system("pause");
return 0;
}

That will remove microsofts entry which is quite big.

Removing the precompiled header might give something.

Then you can get some more by messing with the configuration. I got it down to 3.5kb which it is basically just padding now.

Link to comment
Okay, heres a example on the IsDebuggerPresent function.
#include <windows.h>
#include <stdio.h>BOOL isDebuggerPresent();#pragma comment(linker,"/FILEALIGN:512 /MERGE:.rdata=.text /MERGE:.data=.text /SECTION:.text,EWR /IGNORE:4078")int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow )
{
if (isDebuggerPresent())
{
MessageBox(GetForegroundWindow(),"Debugger detected!\nStop debugging me now!","HELP!",MB_ICONSTOP);
}
else
{
MessageBox(GetForegroundWindow(),"Yay!! No debugger here!",":)",MB_OK);
}
return 0;
}
BOOL isDebuggerPresent()
{
BOOL result = FALSE;
HINSTANCE kern_lib = LoadLibraryEx( "kernel32.dll", NULL, 0 );
if( kern_lib ) {
FARPROC lIsDebuggerPresent = GetProcAddress( kern_lib, "IsDebuggerPresent" );
if( lIsDebuggerPresent && lIsDebuggerPresent() ) {
result = TRUE;
}
FreeLibrary( kern_lib );
}
return result;
}

Don't mind the other code, just pay attention to the if (isDebuggerPresent()).....

why use LoadLibraryEx instead of LoadLibrary ? you're not using the other parameters anyways.

Also, to make the code more tidier, i would use switch/case and instead of the prototype, just bring the block of code above the defined entry-point lol.

Also2, i noticed you included the standard input-output library, so consider using printf() to output result to the console screen instead of using annoying MessageBox();

And to others, don't use system(), it's bad, if you want to avoid instant close use std::cin()

Edited by Rot1
Link to comment
why use LoadLibraryEx instead of LoadLibrary ? you're not using the other parameters anyways.

Because I felt like it :/

Also, to make the code more tidier, i would use switch/case and instead of the prototype, just bring the block of code above the defined entry-point lol.

I did it as a example of how to use IsDebuggerPresent(), not as a example in efficient program design. It was wrote in < 2 minutes.

Link to comment
And why is the program already 40kb in size, when there is no real functionality available?

Easy, that's because you're using iostream. This class object is huge, and contributes to virtually all of the size and confusiong code found in your executable.

Take the following two snippets:

main.cpp

#include <iostream>   using namespace std;   int main()
{
cout << "Hello world!" << endl;
system("pause");
return 0;
}

main.c

#include <stdio.h>
#include <stdlib.h> int main()
{
printf("Hello world!\n");
system("pause");
return 0;
}

Using gcc 3.4.5, the first one comes out at ~ 274kb in a release build with all symbols stripped and size optimizations enabled.

The C version on the other hand, (using printf instead of cout) weighs in at about 5.5kb.

Link to comment

Thanks for all your replies.

I tried several other sources i found on source-code sites and forums, however, i still havent successfully compiled such examples.

Could someone please give me some more help on how to actually get those three functions wanted from the first post implemented?

When its for another IDE or compiler, it doesnt matter, as long as i get such a program to work. If its a C code, it would also be okay.

Any help would be much appreciated.

Link to comment
Any chance someone would like to help me please out? :(

If you wanna see if the task manager is running, simply ask for the handle of it's HWND. If you get a valid handle, TaskMan is running. If you get back NULL, it's not.

BOOL isTaskManRunning()
{
HWND hwndTaskMan = FindWindowEx(NULL, NULL, NULL, "Windows Task Manager");
if (hwndTaskMan != NULL)
return true;
return false;
}

As for persistence, heres some code you may wanna take a look at. I'l leave it as an exercise to determine which key you need to check/write in order for your program to be executed at windows start-up.

// Returns: nothing
// creates HKLM\SOFTWARE\001\WindowPos key
// and fills it with the co-ords of the passed RECT
void SaveWindowPosToRegistry(RECT &myRect)
{
HKEY newKey;
long result;
DWORD disposition;
char posString[32]; result = RegCreateKeyEx(HKEY_LOCAL_MACHINE,
"SOFTWARE\\001\\WindowPos",
0,
"REG_SZ",
REG_OPTION_NON_VOLATILE,
KEY_ALL_ACCESS,
NULL,
&newKey,
&disposition); sprintf(posString,"%d, %d, %d, %d", myRect.top, myRect.left, myRect.bottom, myRect.right);
result = RegSetValueEx(newKey, "", 0, REG_SZ, (BYTE*)posString, strlen(posString)+1);
RegCloseKey(newKey);
} // Returns: true if key found, false otherwise
// reads the value of the HKLM\SOFTWARE\001\WindowPos key
// and fills the passed RECT with the coords read from the key
bool readWindowPosFromReg(RECT *windowPos)
{
LONG result, keyLength;
HKEY openedKey;
char buffer[32]; result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\001\\WindowPos", 0, KEY_ALL_ACCESS, &openedKey);
RegQueryValue(openedKey, "", buffer, &keyLength);
RegCloseKey(openedKey);
sscanf(buffer, "%ld, %ld, %ld, %ld", &windowPos->top, &windowPos->left, &windowPos->bottom, &windowPos->right); return (!(bool)result);
}
Edited by enhzflep
  • Like 1
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...