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

 

 


Tema destacado:


  Mostrar Mensajes
Páginas: [1]
1  Programación / Programación C/C++ / Re: Acerca de rendimiento de Aplicaciones en: 3 Enero 2012, 20:29 pm
hay muchos factores que afectan al rendimiento siendo el algoritmo (en mi opinion) de los que mas influye directamente. una buena gestion de memoria y el uso de SIMD (cuando es necesario) en tareas criticas podria decirse que son, tambien, fundamentales.

si la memoria no esta alineada pues a la cpu le costara mas, si el algoritmo es una basura tendra que hacer un proceso 1000000 de veces cuando podrian usarse algoritmos de complejidad logaritmica. si usas vectores de la STL y no te preocupas por reservarle espacio suficiente va a estar liberando + reservando memoria constantemente a medidas que lo llenes y eso se come los tiempos de ejecucion.

en fin, son muchas cosas que al final pasan factura.
2  Programación / Programación C/C++ / Re: Código más eficiente en: 3 Enero 2012, 20:03 pm
ahi va el mio para sacar el maximo de 8 numeros de 16 bits
Código
  1. #include <iostream>
  2. #include <ctime>
  3.  
  4. typedef __declspec(align(8)) struct
  5. {
  6. short _t[4];
  7. }sal;
  8.  
  9. int main()
  10. {
  11.  
  12. sal k, j, e;
  13. k._t[0] = 2;
  14. k._t[1] = 2342;
  15. k._t[2] = 5712;
  16. k._t[3] = 32234;
  17. j._t[0] = 30353;
  18. j._t[1] = 2762;
  19. j._t[2] = 23484;
  20. j._t[3] = 9853;
  21. clock_t start = clock();
  22.  
  23. __asm {
  24. movq mm0, k
  25. movq mm1, j
  26. pmaxsw mm1, mm0
  27. pshufw mm0, mm1, 0x4e
  28. pmaxsw mm1, mm0
  29. pshufw mm0, mm1, 0x11
  30. pmaxsw mm1, mm0
  31. pshufw mm0, mm1, 0x11
  32. pmaxsw mm1, mm0
  33. movq e, mm0
  34. }
  35. clock_t end = clock();
  36. short x = 0;
  37.  
  38. std::cout<< e._t[0] << std::endl << end - start << std::endl;
  39. std::cin.get();
  40. return 0;
  41. }

output
Citar
32234
0
3  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
4  Programación / Programación C/C++ / Re: problema Inyeccion DLL en: 31 Julio 2011, 12:44 pm
pues ahora no se que pasa pero algun proceso debe haber cargado la dll pero de forma extraña, no me aparece con el tasklist en ninguno de los procesos con los que probe. 

la dll lo unico que hace es llamar a messagebox para mostrar una caja de texto pero sin embargo no me aparece nada.

debe estar ejecutandose porque intento eliminar la dll y me dice que se esta ejecutando por algun proceso xD
5  Programación / Programación C/C++ / Re: problema Inyeccion DLL en: 30 Julio 2011, 22:44 pm
recuerda que un proceso de 32bit no puede inyectarse en uno de 64 y nunca podras abrir un proceso con mas privilegios que el proceso actual

pero entonces deberia darme error directamente despues de llamar a OpenProcess no?

de todas formas estoy abriendo el loader en modo administrador. no deberia haber problemas no?

he probado en la calculadora, en el notepad y en el firefox (el firefox lo tengo en 32 bits).
6  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;


}
7  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