Friday, September 9, 2011

Hook Specials 29 : A SEH'S HOOK [expansibility]

Peoples know SEH mechanism well. But may be do not understand code of try-except combined with SEH, That is undocumented.

Code:
#include <windows.h>
#include <stdio.h>

//The structure is vector table of try except (array),Undocumented
typedef struct __vect_handler
{
  DWORD vFlag;
  PVOID TryHandler;/*try-except{code}*/
  PVOID NextContiueCode;/*Exception handling behind next address of command */

}vect_handler;

typedef struct __EXCEPTION_LIST
{
  __EXCEPTION_LIST* next;//next SEH chain
  PVOID             handler;//exception handling program
  vect_handler*     vecthandler;
  DWORD             IndexVechandler;/*Cunrrent handling number of try-except , cast exception(on try-except) both modified it*/
 
}EXCEPTION_LIST;

char* ff = "try";

DWORD WINAPI handler()
{
  /*突破except{}里不能定义局部变量,增加局部变量*/
  /*debugger monitoring*/
  /*encryption TRY code*/
      __asm pushad
   
    __asm push 0
    __asm push 0
    __asm push ff
    __asm push 0
    __asm mov eax,MessageBoxA
    __asm call eax
    __asm popad
  //  __asm jmp OldExceptCode realize the line like perfect hook
    return EXCEPTION_EXECUTE_HANDLER/*jmp Contiue function*/;
};

void   Contiue()
{
        MessageBoxA( 0,"contiue",0,0);
    ExitProcess( 0 );
};

int main( int argn, char** argv )
{
  char k;
  char* v = 0;//&k;
  DWORD prepageprotect;

  DWORD ntry = 0;
  EXCEPTION_LIST* pe;
  EXCEPTION_LIST* currentpe;


  __asm mov eax, fs:[0]
    __asm mov pe, eax
   
  currentpe = pe;

  BOOL ok = VirtualProtect( &currentpe->vecthandler[0].TryHandler, 8, PAGE_EXECUTE_READWRITE, &prepageprotect );
  currentpe->vecthandler[0].TryHandler = handler;//hook try-except 【0 】block
  currentpe->vecthandler[0].NextContiueCode = Contiue;/*hook try-except 【0】 block 可以调到任何IP,可自己扩展功能*/
//以下do-while为显示SEH-try链没啥作用
    do
  {
    printf( "Next:%08x,handler:%08x\n", pe->next, pe->handler );
    if( pe->vecthandler )
    {
      vect_handler* v = pe->vecthandler;

      while( v->vFlag == 0xffffffff )
      {
        printf( "------try:%d,handler:%08x,NextCode:%08x\n", ntry, v->TryHandler, v->NextContiueCode );
        v++;
        ntry++;
      };
    };
    pe = pe->next;

  }while( pe!=(EXCEPTION_LIST*)0xffffffff );
 
  __try{
    /*ASM 这里会有mov [ebp-4],0*///try-except 【0】对应vecthandler[0]
    *v = 0;//将抛出异常,它已hooked
   
  }__except(EXCEPTION_EXECUTE_HANDLER)
  {
                          // 该异常处理将变化为调用handler函数
           //异常处理完好后将调用Contiue函数;
   
  };
 
  __try{
    /*ASM 这里会有mov [ebp-4],1*///try-except 【1】对应vecthandler[1]
    *v = 0;
   
  }__except(EXCEPTION_CONTINUE_EXECUTION)
  {
   
  };
  getchar();
  return 0;
}

No comments:

Post a Comment