elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Como proteger una cartera - billetera de Bitcoin


  Mostrar Temas
Páginas: [1]
1  Seguridad Informática / Análisis y Diseño de Malware / reemplazar funcion en la IAT en: 13 Septiembre 2011, 17:58 pm
buenas, estoy teniendo un problemilla interceptando la llamada a una funcion de una dll cuando la cargo de forma dinamica mediante loadlibrary, getprocaddress y todo eso. este es el proceso en el que inyecto mi dll.

 
Código:
#include <windows.h>
#include <iostream>

using namespace std;

typedef int (WINAPI *MSGBX) (HWND,LPCSTR, LPCSTR,UINT);


int main(){

HMODULE hMod = LoadLibrary("User32.dll");
if (!hMod) return 1;

MSGBX mymsgbox = (MSGBX)GetProcAddress(hMod, "MessageBoxA");

if (!mymsgbox) return 1;

cout << "libreria cargada y funcion localizada, esperando el hook..." << endl;

cin.get();

mymsgbox(NULL, "no ok", "!!", 0);             // no interceptada
MessageBox(NULL, "no ok", "!!", 0);           // interceptada

return 0;

}

esto es lo que hace mi dll

Código:
case DLL_PROCESS_ATTACH:

CreateThread(0, 0, (LPTHREAD_START_ROUTINE)begin, 0, 0, 0);

Código:
LPTHREAD_START_ROUTINE begin()
{

HMODULE hMod = GetModuleHandle(0);
orig_box = (MSGBX) InterceptDllCall(hMod, "User32.dll", "MessageBoxA", (DWORD)&mymsgbox);
MessageBox(NULL, "Inyectado", "adasd", 0);

return 0;

}

y aqui la funcion (que no es mia) que sobreescribe la direccion de la funcion en la IAT

Código:
void *InterceptDllCall( HMODULE hModule, char *szDllName, char *szFunctionName, DWORD pNewFunction )
{
PIMAGE_DOS_HEADER pDosHeader;
PIMAGE_NT_HEADERS pNTHeader;
PIMAGE_IMPORT_DESCRIPTOR pImportDesc;
PIMAGE_THUNK_DATA pThunk;
DWORD dwOldProtect;
DWORD dwOldProtect2;
void *pOldFunction;

if( !( pOldFunction = (void*) GetProcAddress( GetModuleHandle( szDllName ), szFunctionName ) ) )
{
MessageBox(NULL, "GetProcAddress failed", "Error", 0);
return( NULL );
}

pDosHeader = ( PIMAGE_DOS_HEADER )hModule;
if( pDosHeader->e_magic != IMAGE_DOS_SIGNATURE )
{
MessageBox(NULL, "dos_header failed", "Error", 0);
return( NULL );
}

pNTHeader = MakePtr( PIMAGE_NT_HEADERS, pDosHeader, pDosHeader->e_lfanew );
if( pNTHeader->Signature != IMAGE_NT_SIGNATURE
|| ( pImportDesc = MakePtr( PIMAGE_IMPORT_DESCRIPTOR, pDosHeader, pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress ) ) == ( PIMAGE_IMPORT_DESCRIPTOR )pNTHeader )
{
MessageBox(NULL, "PIMAGE_NT_HEADERS failed", "Error", 0);
return( NULL );
}

while( pImportDesc->Name )
{
char *szModuleName = MakePtr( char *, pDosHeader, pImportDesc->Name );
if( !stricmp( szModuleName, szDllName ) )
break;
pImportDesc++;
}
if( pImportDesc->Name == NULL )
{
MessageBox(NULL, "pImportDesc failed", "Error", 0);
return( NULL );
}

pThunk = MakePtr( PIMAGE_THUNK_DATA, pDosHeader, pImportDesc->FirstThunk );
while( pThunk->u1.Function )
{
if( pThunk->u1.Function == ( DWORD )pOldFunction )
{
VirtualProtect( ( void * )&pThunk->u1.Function, sizeof( DWORD ), PAGE_EXECUTE_READWRITE, &dwOldProtect );
pThunk->u1.Function = (DWORD)pNewFunction;
VirtualProtect( ( void * )&pThunk->u1.Function, sizeof( DWORD ), dwOldProtect, &dwOldProtect2 );
return( pOldFunction );
}
pThunk++;
}
return( NULL );
}

que deberia hacer para solucionarlo? habia pensado en hookear LoadLibrary y modificar la EAT para que apunte a mi funcion pero eso solo funcionaria si inyecto mi dll justo cuando el programa se ejecuta o bien abriendolo externamente, asi que estoy un poco perdido.

no veo forma de hacerlo sin el trampolin, pero esque no quiero usarlo xD
2  Programación / Programación C/C++ / problema Inyeccion DLL en: 30 Julio 2011, 19:08 pm
Buenas, estuve leyendome el tutorial de mazard sobre inyeccion de DLL y estoy teniendo problemas.

El problema es que la inyeccion mediante CreateRemoteThread me esta tirando ERROR_ACCESS_DENIED y no se por que.

la redireccion de thread, usando GetLastError() cuando intento abrir el hilo con THREAD_ALL_ACCESS me tira error_invalid_parameter. He probado a usar solamente algunos permisos por si fuera que no me dejara abrirlo con acceso completo pero me sigue tirando el mismo error.

Leyendo no se donde alguien dijo de habilitar los privilegios de debug pero tampoco me sirve.

a ver si alguien me puede echar una mano que voy un poco perdido.

Código:
#include <windows.h>
#include <shlwapi.h>
#include <tlhelp32.h>

unsigned long GetProcessIdFromProcName ( char *procName );
BOOL EnableTokenPrivilege (LPTSTR privilege);

unsigned long GetLastThreadFromProc(char *procname)
{

    DWORD pID = GetProcessIdFromProcName(procname);
    HANDLE thSnapshot;
    THREADENTRY32 te;
    thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, pID);

    if (thSnapshot == INVALID_HANDLE_VALUE)
    {
        MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", 0);
        return false;
    }

    te.dwSize = sizeof(THREADENTRY32);

    BOOL retval = Thread32First(thSnapshot, &te);

    DWORD threadsnumber = 0;
    while (retval){

        retval = Thread32Next(thSnapshot, &te);
        te.dwSize = sizeof(THREADENTRY32);
    }

    retval = Thread32First(thSnapshot, &te);
    for (int i = 0; i < threadsnumber; i++)
    {

        if (threadsnumber)
        {
            retval = Thread32Next(thSnapshot, &te);
            te.dwSize = sizeof(THREADENTRY32);
        }

    }

    if (retval) return te.th32ThreadID;
    else return NULL;

}

unsigned long GetProcessIdFromProcName ( char *procName )
{
   PROCESSENTRY32 pe;
   HANDLE thSnapshot;
   BOOL retval, ProcFound = false;

   thSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

   if(thSnapshot == INVALID_HANDLE_VALUE)
   {
      MessageBox(NULL, "Error: unable to create toolhelp snapshot", "Loader", 0);
      return false;
   }

   pe.dwSize = sizeof(PROCESSENTRY32);

    retval = Process32First(thSnapshot, &pe);

   while(retval)
   {
      if(StrStrI(pe.szExeFile, procName) )
      {
         ProcFound = true;
         break;
      }

      retval    = Process32Next(thSnapshot,&pe);
      pe.dwSize = sizeof(PROCESSENTRY32);
   }

   return pe.th32ProcessID;
}



HMODULE GetRemoteModuleHandle ( unsigned long pId, char *module )
{
    MODULEENTRY32 modEntry;
    HANDLE tlh = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pId);

    modEntry.dwSize = sizeof(MODULEENTRY32);
    Module32First(tlh, &modEntry);

    do
    {
        if(!_stricmp(modEntry.szModule, module))
            return modEntry.hModule;
        modEntry.dwSize = sizeof(MODULEENTRY32);
    }
    while(Module32Next(tlh, &modEntry));

    return NULL;
}


BYTE* CrearCodigoRedirect(DWORD Eip,DWORD Ruta,DWORD dLoadLibrary)
{
BYTE *codeBuff;

codeBuff=(BYTE*)malloc(22);
//push eipvella
*codeBuff=0x68;
codeBuff++;
*((DWORD*)codeBuff)=Eip;
codeBuff+=4;

*codeBuff=0x9C; //pushfd
codeBuff++;
*codeBuff=0x60;  //pushad
codeBuff++;

//push path
*codeBuff=0x68;
codeBuff++;
*((DWORD*)codeBuff)=Ruta;
codeBuff+=4;

//mov eax,nLoadLib
*codeBuff=0xB8;
codeBuff++;
*((DWORD*)codeBuff)=dLoadLibrary;
codeBuff+=4;

*((WORD*)codeBuff)=0xD0FF; //call eax
codeBuff+=2;
*codeBuff=0x61; //popad
codeBuff++;
*codeBuff=0x9D;  //popfd
codeBuff++;
*codeBuff=0xC3;   //ret
codeBuff-=21;

return codeBuff;
}



INT InyectarRedirect(char* procname, char* dll)
{

    typedef HANDLE (__stdcall *openthread) (DWORD,BOOL,DWORD);
openthread AbrirHilo;

    HANDLE hThread = 0, hProcess = 0;
    DWORD tID = GetLastThreadFromProc(procname);
    CONTEXT context;
    DWORD EIPantigua = 0;
    DWORD nLoadLib;
    BYTE* codigo;

    if (!EnableTokenPrivilege("SeTcbPrivilege")) {
        char buff[256];
        wsprintf(buff, "error : %d", GetLastError());
        MessageBox(NULL, buff, "advertencia", 0);
        return -10;
    }

    DWORD pID = GetProcessIdFromProcName(procname);

    hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pID);
    if (!hProcess) return -1;

    AbrirHilo=(openthread)GetProcAddress(GetModuleHandle("kernel32.dll"),"OpenThread");

    hThread = AbrirHilo(0x0008 | 0x0040 | 0x0010 | 0x0002 | 0x0001
                        /*THREAD_GET_CONTEXT |
                        THREAD_QUERY_INFORMATION
                        THREAD_SET_CONTEXT |
                        THREAD_SUSPEND_RESUME
                        THREAD_TERMINATE*/
                        , false, tID);
    if (!hThread) {
        char buff[256];
        wsprintf(buff, "error : %d", GetLastError());
        MessageBox(NULL, buff, "advertencia", 0);
        return -2;
    }

    void* ruta = VirtualAllocEx(hProcess, NULL, strlen(dll)+1, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE );
    if (!ruta) return -3;

    if (WriteProcessMemory(hProcess, ruta, dll, strlen(dll), NULL) == 0) return -4;

    nLoadLib = (DWORD) GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
    if (!nLoadLib) return -5;

    SuspendThread(hThread);
    context.ContextFlags = CONTEXT_CONTROL;
    GetThreadContext(hThread, &context);
    EIPantigua = context.Eip;

    codigo = CrearCodigoRedirect((DWORD)EIPantigua, (DWORD) ruta, nLoadLib );
    void* zonainyectada = VirtualAllocEx(hProcess, NULL, 22, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
    if (!zonainyectada) return -6;

    context.Eip = (DWORD) zonainyectada;
    context.ContextFlags = CONTEXT_CONTROL;
    SetThreadContext(hThread, &context);

    ResumeThread(hThread);
    CloseHandle(hThread);
    CloseHandle(hProcess);

    return 0;

}


BOOL EnableTokenPrivilege (LPTSTR privilege)
{
HANDLE hToken;
TOKEN_PRIVILEGES token_privileges;
DWORD dwSize;
ZeroMemory (&token_privileges, sizeof (token_privileges));
token_privileges.PrivilegeCount = 1;
if ( !OpenProcessToken (GetCurrentProcess(), TOKEN_ALL_ACCESS, &hToken))
return FALSE;
if (!LookupPrivilegeValue ( NULL, privilege, &token_privileges.Privileges[0].Luid))
{
CloseHandle (hToken);
return FALSE;
}

token_privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
if (!AdjustTokenPrivileges ( hToken, FALSE, &token_privileges, 0, NULL, &dwSize))
{
CloseHandle (hToken);
return FALSE;
}
CloseHandle (hToken);
return TRUE;
}


INT ThreadRemoto(char *procname, char* dll)
{

    EnableTokenPrivilege("SeTcbPrivilege");
    DWORD pid = GetProcessIdFromProcName(procname);
HANDLE hProcess = NULL;
    LPVOID RemoteString = NULL;
LPVOID nLoadLibrary = NULL;

hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid );
if (!hProcess) return -1;

    nLoadLibrary = (LPVOID)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
    if (!nLoadLibrary) return -2;

    RemoteString = (LPVOID)VirtualAllocEx(hProcess,NULL,strlen(dll),MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
    if (!RemoteString) return -3;

    if (WriteProcessMemory(hProcess,(LPVOID)RemoteString,dll,strlen(dll),NULL) == 0) return -4;
    CreateRemoteThread(hProcess,NULL,NULL,(LPTHREAD_START_ROUTINE)nLoadLibrary,(LPVOID)RemoteString,NULL,NULL);
    CloseHandle(hProcess);
    return GetLastError();
    return 0;


}
3  Programación / Programación C/C++ / alguien que me sugiera un buen libro en: 21 Abril 2011, 13:57 pm
buenas, estoy leyendome actualmente los libros de herb sutter y scott meyers, effective y more effective c++, effective stl, exceptional c++ y more exceptional c++.

esos 2 ultimos me estan costando digerirlos pero me estoy fijando que en ninguno de los libros que me he estado leyendo tocan algunas cosas que me parecen bastante importantes como el preprocesador, las calling convention etc.

Tengo varias dudas y la documentacion que ofrece msdn me parece bastante 'pobre' sobre las calling convention (_cdecl, _stdcall, etc) y el preprocesador.

sabeis de algun libro donde se trate con profundidad eso?
Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines