Update: Killing threads based on start address and the EIP

16Jul09

Just another idea I had for killing foreign threads 😉

#include <windows.h>
#include <tlhelp32.h>

#define CODEBEGIN	0x00401000
#define CODEEND		0x004019FE

DWORD WINAPI GetThreadStartAddress( HANDLE hThread )
{
    NTSTATUS ntStatus;
    HANDLE hDupHandle;
    DWORD dwStartAddress;
    typedef NTSTATUS ( WINAPI *NQIT )( HANDLE, LONG, PVOID, ULONG, PULONG );
    NQIT NtQueryInformationThread = ( NQIT )GetProcAddress( GetModuleHandle( "ntdll.dll" ), "NtQueryInformationThread" );

    HANDLE hCurrentProcess = GetCurrentProcess( );

    if( !DuplicateHandle( hCurrentProcess, hThread, hCurrentProcess, &hDupHandle, THREAD_QUERY_INFORMATION, FALSE, 0 ) ) {
        return( ERROR_ACCESS_DENIED );
    }

    ntStatus = NtQueryInformationThread( hDupHandle, 9, &dwStartAddress, sizeof( DWORD ), NULL );

    CloseHandle( hDupHandle ); 

    return( dwStartAddress );
}

int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd )
{
  HANDLE h = CreateToolhelp32Snapshot( TH32CS_SNAPTHREAD, 0 );
  if( h != INVALID_HANDLE_VALUE ) {
    THREADENTRY32 te;
    te.dwSize = sizeof( te );
    if( Thread32First( h, &te ) ) {
      do {
       if ( te.dwSize >= FIELD_OFFSET( THREADENTRY32, th32OwnerProcessID ) +
                      sizeof( te.th32OwnerProcessID ) &&
					  GetCurrentProcessId( ) == te.th32OwnerProcessID ) {
			DWORD dwStartAddress;
			HANDLE lclThread = OpenThread( THREAD_GET_CONTEXT, FALSE, te.th32ThreadID );
			dwStartAddress = GetThreadStartAddress( lclThread );
			if( dwStartAddress < CODEBEGIN || dwStartAddress > CODEEND )
			{
				TerminateThread( lclThread, EXIT_SUCCESS );
			} else {
				CONTEXT ctx;
				SuspendThread( lclThread );
				GetThreadContext( lclThread, &ctx );
				if( ( int ) &ctx.Eip < CODEBEGIN || ( int ) &ctx.Eip > CODEEND )
					TerminateThread( lclThread, EXIT_SUCCESS );
				ResumeThread( lclThread );
			}


			CloseHandle( lclThread );
	  }
      te.dwSize = sizeof( te );
    } while( Thread32Next( h, &te ) );
   }
  }
  CloseHandle( h );
 

  MessageBox( 0, "Debugger not found.", "Success?", MB_OK );

  return( EXIT_SUCCESS );
}
Advertisements


No Responses Yet to “Update: Killing threads based on start address and the EIP”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: