Menú

Mostrar Mensajes

Esta sección te permite ver todos los mensajes escritos por este usuario. Ten en cuenta que sólo puedes ver los mensajes escritos en zonas a las que tienes acceso en este momento.

Mostrar Mensajes Menú

Mensajes - Arkangel

#1
Underc0de / Re:Reto Official Pentest Underc0de
Agosto 29, 2013, 01:06:05 PM
Tendre que intentarlo
#2
pues yo considero que en java para tipos no primitivos hacer esto:
Código: java

Integer a1 = 600;

es lo mismo que hacer
Código: java

Integer a1 = new Integer(600);

Porque cuando usas dato no primitivo, se crea un objeto para este y por lo tanto es como hacer un new. y como esto los convierte en punteros a objetos. el == es exactamente lo mismo en los dos casos. una comparación para ver si es el mismo objeto

Saludos
#3
Pues vamos alla:

1) estas haciendo new y comparando las referencias de los objetos, por lo tanto da false porque son diferentes objetos
2) Aqui pasa igual, porque integer es un tipo objeto y se hace una conversion, y si no usas ecual comparas referencias
3) Aqui pasa como el anterior, pero segun el debunger. se le a asignado el mismo objeto (Ni idea de porque aqui pasa esto)
4) al usar equal estas comparando el contenido de los objetos y por lo tanto da el valor true deseado
5) Aqui da false porque stringBuilder no sobrescribe el metodo equal y por lo tanto se llama al que se ereda de object que devuelve siempre false

Saludos
#4
Mira las definiciones que hay en C

Segun Vc++ se definen  asi:
Código: c

/* Declare _iob[] array */

#ifndef _STDIO_DEFINED
_CRTIMP FILE * __cdecl __iob_func(void);
#endif  /* _STDIO_DEFINED */

#define stdin  (&__iob_func()[0])
#define stdout (&__iob_func()[1])
#define stderr (&__iob_func()[2])



Basicamente tienes que exportar ese array de msvcrt.dll y sacar de hay las estructuras FILE

Saludos
#5
yo lo decia por que si ves la descripcion de "lea", dice que hace como si accediera a memoria, pero te devuelve la direccion a la que accede. por lo tanto segun esa definicion cabe la duda de si hara tambien la traduccion de los segmentos.

Saludos
#6
Muy buena karcrack.

Se podria hacer tambien usando LEA?

Saludos
#7
Bueno, se me ocurrio hablando con Zero una manera de detectar desde 32bits si el SO es de 64 y se me ocurrio esto para solucionar su problema
Gracias Zero por preguntar

Código: cpp

bool __declspec(naked) is64BitOS(){
    __asm{
        mov eax,fs:[0xC0]
        test eax,eax
        je _32bits
        mov eax,1
      _32bits:
        ret
    }
}


Saludos
#8
Códigos Fuentes / Re:[SRC]I/O Asincrono windows
Junio 20, 2013, 02:10:26 PM
Aqui te oingo unos trozos de un codigo donde lo uso

Código: c


//En esta funcion se aceptarian clientes del socket
int Socket_listen(ushort port,AcceptClientsCallback onAcceptClients){
.....
.....
while ((clientSocket = accept(serverSocket,(SOCKADDR*)&clientAddr,&clientAddrSize)) != INVALID_SOCKET) {
                        //Aqui se crea el IODevice a partir del socket
                        IODevice* ioClient = createIODevice((HANDLE)clientSocket,m_rw);
                        if(ioClient){
                            //Luego si hace falta cambiar alguna funcion como la de close, para casos especificos
                            ioClient->closeHandle = &Net_closeSocket;

                            onAcceptClients((struct sockaddr*)&clientAddr,ioClient);
                        }else{
                            printf("createIODevice error\n");
                            closesocket(clientSocket);
                        }
                    }
...
...
}

void httpClientDispatcher(struct sockaddr* addr,struct IODevice* io){
    //stream_printf(out,"hello\n");
    Http* newHttp = (Http*)malloc(sizeof(*newHttp));
    ZeroMemory(newHttp,sizeof(*newHttp));
    newHttp->maxRead = 1024;
    newHttp->readBuff = malloc(newHttp->maxRead);

    //Aqui se pone la funcion que atendera las notificaciones de datos leidos, escritos, fin de fichero y close
    io->context = newHttp;
    io->ioCompletion = &http_ioCompletion;

    /*
     *Aqui se empieza una solicitud de lectura y otra se escritura, pueden estar pendientes las 2 a la vez
     * Para detectar el fin de fichero hay que intentar leer
     */
    io->read(io,newHttp->readBuff,newHttp->maxRead);

    io->write(io,(const byte*)"hola\n",sizeof("hola\n"));
}

void http_ioCompletion(struct IODevice* io,byte* buff,ulong BytesTransfered,ulong op,ulong status){
    Http* http = (Http*)io->context;

    //Aqui se manejan las diferentes notificaciones
    switch (op) {
        case OP_WRITE:
            printf("http BytesWrited: %u, data: %s\n",(uint)BytesTransfered,buff);
            break;
        case OP_READ:
            if(status != STATUS_CANCELLED && status != ERROR_PROCESS_ABORTED){
                bool continueRead = true;
               
                printf("http BytesReated: %s\n",buff);
                ZeroMemory(http->readBuff,http->maxRead);

                if(strcmp("bye",buff)==0){
                        closeIODevice(io);
                        continueRead = false;
                }


                if(continueRead)io->read(io,http->readBuff,http->maxRead);

            }
            break;
        case OP_EOF:
            closeIODevice(io);
            break;
        case OP_CLOSE:
            printf("Cliente desconectado\n");
            break;
        default:
            break;
    }
}

#9
Códigos Fuentes / [SRC] I/O Asincrono windows
Junio 20, 2013, 12:10:37 PM
Hola, les traigo un code para la lectura y escritura en windows asincrona.
Se puede usar para pipes,ficheros,socket, etc
En teoria soporta una gran carga de trabajo al usar IOCP y overlapped.
Los IO completion port permiten crear una cola de solicitudes de I/O a medida que se van completando se pueden ir recuperando con GetQueuedCompletionStatus.
Esto es mas eficiente que crear un hilo por cada solicitud, a partir de un cierto numero de hilos la sobrecarga del cambio de tareas empieza a ser significativa y la memoria requerida para crear esso hilos se dispara.
Con este metodo un pequeño numero de hilos puede atender a una gran cantidad de solicitudes.
Esto es ideal para crear servidores tcp que podran atender a un gran numero  de clientes

Aqui tienen el code:

iodevice.h
Código: c

#ifndef IODEVICE_H
#define IODEVICE_H

#include <windows.h>
#include "basicTypes.h"

struct IODevice;
typedef void(*ioCompletionCallback)(struct IODevice* io,byte* buff,ulong BytesTransfered,ulong op,ulong status);


//Op codes for IOCP
#define OP_READ     0
#define OP_WRITE    1
#define OP_EOF      2
#define OP_CLOSE    3

#define STATUS_CANCELLED 0xC0000120

typedef struct OVERLAPPEDex{
    OVERLAPPED Overlapped;
    int opCode;
    byte* buff;
}OVERLAPPEDex;

typedef int (*IODeviceDispatchIoCompletion)(struct IODevice* io,OVERLAPPEDex* Overlapped,ulong BytesTransfered,bool result);
typedef int (*IODeviceWrite)(struct IODevice* io,const byte* buff,ulong nBytes);
typedef int (*IODeviceRead)(struct IODevice* io,byte* buff,ulong maxBuff);
typedef void (*IODeviceCloseHandle)(struct IODevice* io);

typedef struct IODevice{
        enum mode{
            m_none = 0,
            m_read = 1,
            m_write = 2,
            m_rw = 3
        }mode;

        IODeviceRead read;
        IODeviceWrite write;
        IODeviceDispatchIoCompletion dispatchIoCompletion;
        ioCompletionCallback ioCompletion;
        IODeviceCloseHandle closeHandle;
        ulong error;
        void* context;
}IODevice;
struct IODevice* createIODevice(HANDLE h,ulong mode);
HANDLE IODevice_getHandle(struct IODevice* io);
void closeIODevice(struct IODevice* io);
void freeIODevice(struct IODevice *io);

#endif // IODEVICE_H


iodevice.c
Código: c

#include "iodevice.h"
#include <stdio.h>


HANDLE completionPort = null;
void CALLBACK ThreadIoCompletion(int);

void IODevice_closeHandle(struct IODevice *io);

bool inicializeIOCP(){
    bool result = false;

    if(completionPort == null){
        completionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0 );
        if(completionPort != null){
            int i;
            for(i = 0;i<8;i++){
                CreateThread(null,0,(LPTHREAD_START_ROUTINE)&ThreadIoCompletion,(LPVOID)i,0,null);
            }
            result = true;
        }else{
            printf("Error creating IOCP %d\n", (int)GetLastError());
        }
    }else {
        result = true;
    }
    return result;
}
typedef struct IODevicePrivate{
    struct IODevice device;
    HANDLE hFile;
    int mode;
    OVERLAPPEDex rOverlapped;
    OVERLAPPEDex wOverlapped;
}IODevicePrivate;

int IODevice_read(struct IODevice* io,byte* buff,ulong maxBuff){
    ulong NumberOfBytesReated = -1;
    if(io && (((IODevicePrivate*)io)->mode & m_read)){
        ioCompletionCallback callback = null;
        OVERLAPPEDex* Overlapped = &((IODevicePrivate*)io)->rOverlapped;
        ZeroMemory(Overlapped,sizeof(*Overlapped));
        Overlapped->opCode = OP_READ;
        Overlapped->buff = buff;

        if(!ReadFile(((IODevicePrivate*)io)->hFile
                           ,buff,maxBuff,&NumberOfBytesReated,(OVERLAPPED*)Overlapped)){
            int error = GetLastError();
            switch (error) {
                case ERROR_IO_PENDING:
                    // si el modo asincrono no esta activado, esperamos a que complete
                    callback = ((IODevicePrivate*)io)->device.ioCompletion;
                    if(!callback){
                        GetOverlappedResult(((IODevicePrivate*)io)->hFile,
                                               (OVERLAPPED*)Overlapped,&NumberOfBytesReated,true)
                    }
                    break;
                default:
                    printf("ReadFile error: %d\n",error);
                    break;
            }
        }
    }
    return NumberOfBytesReated;
}

int IODevice_write(struct IODevice* io,const byte* buff,ulong nBytes){
    ulong NumberOfBytesWritten = -1;
    if(io && (((IODevicePrivate*)io)->mode & m_write)){
        ioCompletionCallback callback = null;
        OVERLAPPEDex* Overlapped = &((IODevicePrivate*)io)->wOverlapped;
        Overlapped->opCode = OP_WRITE;
        Overlapped->buff = (byte*)buff;

        if(!WriteFile(((IODevicePrivate*)io)->hFile
                            ,buff,nBytes,&NumberOfBytesWritten,(OVERLAPPED*)Overlapped)){
            int error = GetLastError();
            switch (error) {
                case ERROR_IO_PENDING:
                    // si el modo asincrono no esta activado, esperamos a que complete
                    callback = io->ioCompletion;
                    if(!callback){
                        GetOverlappedResult(((IODevicePrivate*)io)->hFile,
                                               (OVERLAPPED*)Overlapped,&NumberOfBytesWritten,true)
                    }
                    break;
                default:
                    printf("WriteFile error: %d\n",error);
                    break;
            }
        }
    }
    return NumberOfBytesWritten;
}
int IODevice_dispatchIoCompletion(IODevicePrivate* io,OVERLAPPEDex* Overlapped,ulong BytesTransfered,bool result){
    if(io){
        byte* buff = null;
        int opCode,errorCode = 0;
        if(Overlapped){
            buff = Overlapped->buff;
            errorCode = Overlapped->Overlapped.Internal;
            opCode = Overlapped->opCode;

            if(result && !BytesTransfered && opCode == OP_READ){
                opCode = OP_EOF;
                printf("OP_EOF %u\n",errorCode);
            }
        }else{
            opCode = OP_CLOSE;
        }

        switch(opCode){
            case OP_EOF:
            case OP_READ:
            case OP_WRITE:
                if(io->device.ioCompletion)io->device.ioCompletion((IODevice*)io,buff,
                                                                   BytesTransfered,opCode,
                                                                   errorCode);
                break;
            case OP_CLOSE:
                if(io->device.ioCompletion)io->device.ioCompletion((IODevice*)io,buff,
                                                                   BytesTransfered,opCode,
                                                                   errorCode);
                io->device.closeHandle((IODevice*)io);
                free(io);
            default:
                ;
        }
    }
    return 0;
}
struct IODevice* createIODevice(HANDLE h,ulong mode){
    IODevicePrivate* ioDevice = null;
    if(inicializeIOCP()){
        ioDevice = malloc(sizeof(IODevicePrivate));
        if(ioDevice){
            ZeroMemory(ioDevice,sizeof(*ioDevice));

            ioDevice->mode = mode;
            ioDevice->hFile = h;
            ioDevice->device.read = &IODevice_read;
            ioDevice->device.write = &IODevice_write;
            ioDevice->device.dispatchIoCompletion = (IODeviceDispatchIoCompletion)&IODevice_dispatchIoCompletion;
            ioDevice->device.closeHandle = &IODevice_closeHandle;

            CreateIoCompletionPort(h,completionPort,(DWORD)ioDevice,0);
        }
    }

    return (struct IODevice*)ioDevice;
}
void CALLBACK ThreadIoCompletion(int lpParam){
    int nThreadNo = lpParam;

    OVERLAPPEDex *pOverlapped = NULL;
    IODevicePrivate   *pContext = NULL;
    DWORD            dwBytesTransfered = 0;

    bool result = true;
    while (result) {
        result = GetQueuedCompletionStatus(
                    completionPort,
                    &dwBytesTransfered,
                    (LPDWORD)&pContext,
                    (LPOVERLAPPED*)&pOverlapped,
                    INFINITE);
        if (!pContext){
            //Estan pidiendo parar
            break;
        }
        printf("thread dispatching: %d\n",nThreadNo);
        pContext->device.dispatchIoCompletion((struct IODevice*)pContext,pOverlapped,dwBytesTransfered,result);
    }
}


void closeIODevice(struct IODevice *io){
    //Cancelamos las operaciones pendientes y enviamos un mensaje a la cosa sin

    if(!CancelIo(((IODevicePrivate*)io)->hFile))
        printf("CancelIo error: %u\n",(uint)GetLastError());
    //Cambiamos el modo a none para que no se pueda llamar mas a read y a write
    ((IODevicePrivate*)io)->mode = m_none;
    PostQueuedCompletionStatus(completionPort,0,(uint)io,null);
}
void IODevice_closeHandle(struct IODevice *io){
    CloseHandle(((IODevicePrivate*)io)->hFile);
}

HANDLE IODevice_getHandle(struct IODevice *io){
    return ((IODevicePrivate*)io)->hFile;
}



Saludos
#10
lo de los ordinales no hay solucion, pero lo de los forward se podria solucionar, solo que complicaria la funcion un poco

Saludos
#11
Códigos Fuentes / [Code] GetThreadTEB
Junio 17, 2013, 08:58:55 AM
Otro codigo  mas de hace un tiempo
Esta función que te da la localización del TEB de cualquier hilo:

Código: cpp

#include <Windows.h>
#include <Winternl.h>

TEB* GetThreadTEB(ushort TID){
LDT_ENTRY ldt;//La LDT es un tipo de GDT que es diferente para cada hilo. http://wiki.osdev.org/GDT
CONTEXT context;
void* BaseTIB;
HANDLE hThread;

//Inicializamos a zero
ZeroMemory(&context,sizeof(context));
ZeroMemory(&ldt,sizeof(ldt));
//Le decimos que queremos los registros de segmento del hilo
context.ContextFlags = CONTEXT_SEGMENTS;
//Abrimos el hilo con los flag de THREAD_GET_CONTEXT y THREAD_QUERY_INFORMATION
hThread = OpenThread(THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION,0,TID);
//Conseguimos el contexto del hilo
GetThreadContext(hThread,&context);
//Conseguimos la LDT asignada a el selector del segmento fs
GetThreadSelectorEntry(hThread,context.SegFs,&ldt);
//Cerramos el handle
CloseHandle(hThread);

//La direccion base esta repartida en tres campos de la ldt BaseLow 0-15,BaseMid 16-23 y BaseHi 24-31
BaseTIB = (void*)(ldt.BaseLow | (ldt.HighWord.Bits.BaseMid<<16)| (ldt.HighWord.Bits.BaseHi<<24));
printf("base TIB: %p\n",BaseTIB);

return (TEB*)BaseTIB;
}

en el TIB es donde se guarda la informacion de u hilo concreto como los valores de el almacenamiento local, la direccion de la pila, manejo de excepciones, etc

Espero que a alguien le sea util. Yo lo uso para modificar el Thread local storage de cualquier hilo.

Saludos Arkangel
#12
ASM / [MASM] AmpliarSeccion
Junio 17, 2013, 08:54:30 AM
Enconte este code posteado en GedZac, pero como ya no hay actividad. Lo reposteo aqui. No funciona con exes de 64bits
Código: asm

AmpliarSeccion proc PFilePE:dword,PSizeFile,minSize:dword
LOCAL NumSections
LOCAL NumSectionsRestante
LOCAL PArrySections
LOCAL FileAlignment
LOCAL PFileCopia
LOCAL SeccionEjecu
LOCAL NewSize


mov ebx,PFilePE
cmp word ptr[ebx],5A4DH
jne NoExe
mov edx,[ebx+3Ch]
lea edx,[edx+ebx]
cmp dword ptr[edx],00004550H;Compruevo El PE signature
jne NoExe
mov ecx,[edx+3Ch]
mov FileAlignment,ecx

Sizing: ;Calculando el tamaño que se ampliara
push edx

xor edx,edx
mov eax,minSize
div ecx
test edx,edx
jz resto
inc eax
resto:

mul ecx
mov minSize,eax

pop edx
movzx eax,word ptr[edx+6]
mov NumSections,eax
mov ecx,eax

;Pido memoria para almacenar los datos de cada seccion
shl eax,4;Murtiplico por 16
push eax
push 0
call new
mov PArrySections,eax

lea edx,[edx+0f8h];Tabla de Secciones
mov ebx,eax;PArrySections

bucle:
dec ecx

mov [ebx],edx;PName
mov eax,[edx+14h];PointerToRawData
mov [ebx+4],eax
mov eax,[edx+10h];SizeOfRawData
mov [ebx+8],eax
mov eax,[edx+24h];Characteristics
mov [ebx+0Ch],eax

lea edx,[edx+28h]
add ebx,10h
test ecx,ecx
jnz bucle


push 10h;SizeEstruc
push 4;CampoOrdenar
push NumSections;Size
push PArrySections;PArrySections
Call ordenar_struc


mov ecx,NumSections
shl ecx,4
mov ebx,PArrySections

NoEjecutable:
test ecx,ecx
jz NoExe
sub ecx,10h
test dword ptr[ecx+ebx+0Ch],20000000h;Busca la seccion que tiene la marca de ejecutable
jne NoEjecutable
mov SeccionEjecu,ebx

mov eax,[NumSections]
shl eax,4
sub eax,ecx
mov NumSectionsRestante,ecx


mov eax, PSizeFile
mov eax,dword ptr[eax]
add eax,minSize

mov NewSize,eax
push eax
push 0
call new
mov PFileCopia,eax

mov ebx,SeccionEjecu
mov edx,[ebx+4];Base de la seccion
add edx,[ebx+8];Tamaño de la seccion en el archivo

push edx
push PFilePE
push eax
call CopyMem ;Copio la parte del archivo que no cambiara su posicion


mov eax,edx
mov ecx,PSizeFile
mov ecx,[ecx]
sub ecx,edx;calculo lo que queda por copiar


add eax,minSize
add eax,PFileCopia
add edx,PFilePE

push ecx
push edx
push eax
call CopyMem


mov ecx,NumSectionsRestante
mov eax,PFilePE
mov edx,SeccionEjecu
;//Puntero a una entrada de la tabla de secciones
mov ebx,[edx]
sub ebx, eax
add ebx,PFileCopia

mov esi,minSize
add [ebx+10h],esi
add edx,10h

Reubicando:
;Ajusto los punteros de PointerToRawData a la nueva posicion de las secciones
sub ecx,10h
mov ebx,[edx+ecx]
sub ebx, eax
add ebx,PFileCopia
mov esi,minSize
add [ebx+14h],esi

test ecx,ecx
jnz Reubicando



mov ebx,PSizeFile
mov eax,NewSize
mov [ebx],eax
mov eax,PFileCopia


ret
NoExe:
xor eax,eax
ret

AmpliarSeccion endp
#13
Presentaciones y cumpleaños / Saludos
Junio 17, 2013, 08:51:46 AM
Hola, soy Arkangel.
Lo mio no son las presentaciones. Pero intentare aportar y ayudar a quien pueda
Gracias a antrax por acojernos

Saludos
#14
ASM / [Modo Kernel] UnAttachDriver
Junio 17, 2013, 08:45:37 AM
Con esto se quita de la pila de objetos a un driver. Solo quedaría cerrar cualquier hilo  y handel relacionado con el para poder descargarlo con casi total seguridad. 8) 8) 8)
Código: asm

    UnAttachDriver proc pDriverObject:PDRIVER_OBJECT
    LOCAL CurrentIrql
     
    push esi
    push ecx
    push edx
    push ebx
     
    cli
    call KeRaiseIrqlToDpcLevel;Canbio la prioridad para que nada me detenga a medio y se produzca una BSOD
    mov CurrentIrql,eax
     
    xor eax,eax
    mov ebx,pDriverObject
    mov ebx,[ebx+4]
     
     
     
    NextDevice:
    cmp ebx,eax;Compruebo que tengo una direccion valida de un DeviceObject
    je EndDevice
    ;Posicion actual
    ;Uno de los DeviceObject a desconectar
    mov edx,[ebx+10h]
    mov [ebx+10h],eax
    mov ecx,[ebx+0B0h]
    cmp ecx,eax
    je Next
    ;Posicion actual
    ;DEVOBJ_EXTENSION del DeviceObject a desconectar
    mov esi,[ecx+18h];Consigo la direccion del DeviceObject Inferior de la pila de dispositivos
    mov [ecx+18h],eax;EAX = NULL
    cmp eax,esi
    je Next
    ;Posicion actual
    ;DeviceObject inferior
    mov [esi+10h],edx;Coloco la direccion del DeviceObject Superior de la pila de dispositivos
    cmp eax,edx
    je Next
    ;Posicion actual
    ;DeviceObject superior
    mov ecx,[edx+0B0h];Consigo la direccion de DEVOBJ_EXTENSION del DeviceObject Superior
    mov [ecx+18h],esi;Coloco la direccion del DeviceObject Inferior de la pila de dispositivos
     
    DecStackSize:
    dec byte ptr[edx+30];Disminullo el contador de la StackSize
    mov edx,[edx+10h]
    cmp edx,eax
    jne DecStackSize
     
    Next:
    mov ebx,[ebx+0Ch];Paso al siguiente de la lista
    jmp NextDevice
    EndDevice:
    push CurrentIrql
    call KeLowerIrql ;Vuelvo al nivel normal de prioridad
    sti
    xor eax,eax
     
    pop ebx
    pop edx
    pop ecx
    pop esi
     
     
    ret
     
    UnAttachDriver endp
     
#15
ASM / [Modo Kernel] GetPointerObjet
Junio 17, 2013, 08:43:06 AM
les dejo una función que les puede servir tanto para hacer hook en las IRP_MJ_XXX u ocultar Objetos en modo kernel
y si quieren también se los listara. Con mínimas modificaciones

Código: asm

GetPointerObjet proc PNDirObjet:PUNICODE_STRING,PNObjet:dword
LOCAL buff[260]:byte
LOCAL handel
LOCAL pDrectoriObject
LOCAL DirectoryEntry
LOCAL DirObjet:OBJECT_ATTRIBUTES
LOCAL count:dword
LOCAL resul

push edx
push ebx
push ecx


lea ebx,DirObjet
InitializeObjectAttributes ebx,PNDirObjet ,OBJ_CASE_INSENSITIVE,NULL,NULL

lea edx,[handel]

push edx
push null
push 80000000h
push null
push KernelMode
push null
push ebx
call ObOpenObjectByName ;Abro el directorio de objetos

lea edx,[pDrectoriObject]
push NULL
push edx
push KernelMode
push null
push FILE_ANY_ACCESS
push [handel]
call ObReferenceObjectByHandle ;Consigo un puntero a partir del Handle
xor ecx,ecx

mov [count],ecx

mov eax,[pDrectoriObject]
HASH_BUCKETS:
movzx ecx,word ptr[count]
cmp dword ptr[eax+ecx*4],0
je fin
mov eax,[pDrectoriObject]
mov ebx,[eax+ecx*4] ;ebx = pDrectoriObject->HashBuckets[Bucket]
ChainLink:
mov DirectoryEntry,ebx
mov ebx,[ebx+4] ;ebx = ebx->Object ;HashBuckets _OBJECT_DIRECTORY_ENTRY
lea ebx,[ebx- 18h] ;OBJECT_TO_OBJECT_HEADER
assume ebx:ptr _OBJECT_HEADER
movzx edx,byte ptr[ebx].NameInfoOffset
sub ebx,edx ;OBJECT_HEADER_TO_NAME_INFO
lea edx,[ebx+4] ;NAME_INFO->name
assume ebx:nothing

lea edi,buff
push edi
push edx
call UnicodeStrToAsciiStr ;Combierte de UNICODE_STRING a cadena ASCII

push edi
push PNObjet
call cmpsrt
cmp eax,0
je encontrado


mov ebx,DirectoryEntry
mov ebx,[ebx]
cmp ebx,0 ;comprueva si es un puntero NULL
jne ChainLink
fin:
inc count
mov eax,[pDrectoriObject]
cmp count,37 ;Comprueva si ha llegado al limite
jne HASH_BUCKETS
xor eax,eax ;Si no encuentra coincidencias devuelve NULL
jmp error
encontrado:
mov ebx,DirectoryEntry
mov eax,[ebx+4]
lea ebx,[eax-18h]
inc dword ptr[ebx] ;Aumento la cuenta del puntero al Objeto para que no sea borrado
error:
mov resul,eax


push pDrectoriObject
call ObDereferenceObject


push [handel]
call ZwClose

mov eax,resul

pop ecx
pop ebx
pop edx

ret

GetPointerObjet endp
#16
Códigos Fuentes / [SCR] GetProcAddres con hash FNV
Junio 17, 2013, 08:25:40 AM
Aqui les traigo esta funcion que ahorra  espacio cuando usas muchas importaciones y a parte, sirve para ocultar lo que importas al no quedar rastro visible de las cadenas de las apis

GetProcAddressByHash.c
Código: cpp

FARPROC WINAPI GetProcAddressByHash(HINSTANCE hModule,ulong hash){
    register PIMAGE_NT_HEADERS PE;
    register FARPROC proc = null;
    register PIMAGE_EXPORT_DIRECTORY ExpDir = null;
    register char** ExportNames = null;

    //Comprovamos la marca de DOS
    if(*((ushort*)hModule)==IMAGE_DOS_SIGNATURE){
        //localizamos la cabecera PE
        PE = (PIMAGE_NT_HEADERS)(((IMAGE_DOS_HEADER*)hModule)->e_lfanew+(ulong)hModule);
        //Compruebo la firma de PE y que halla tabla de importaciones
        if(PE->Signature == IMAGE_NT_SIGNATURE
                && PE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size){
            //Localizo el directorio de exportaciones
            ExpDir = (PIMAGE_EXPORT_DIRECTORY)(PE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
                    .VirtualAddress+(ulong)hModule);
#ifdef DEBUG
            DebugPrintf("GPA","ExpDir = %p,EXPORT_DIRECTORY = %x",ExpDir,PE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]
                        .VirtualAddress);
#endif
            //Localizo los nombres de simbolos exportados y busco la funcion
            ExportNames = (char**)(ExpDir->AddressOfNames+(ulong)hModule);
            register int i;
            for(i = 0;ExportNames[i];i++){
                //Comparo los hash para buscar la funcion
                if(fnv32(ExportNames[i]+(ulong)hModule) == hash){
                    ulong* funtionRVAs = (ulong*)(ExpDir->AddressOfFunctions+(ulong)hModule);
                    ushort* ordinalRVAs = (ushort*)(ExpDir->AddressOfNameOrdinals+(ulong)hModule);
                    //Calculamos la direccion de la funcion
                    proc = (FARPROC)(funtionRVAs[ordinalRVAs[i]] +(ulong)hModule);
                    break;
                }
            }

        }
    }
    return proc;
}

fnv.c
Código: cpp

#define FNV_PRIME_32 16777619
#define FNV_OFFSET_32 2166136261U

ulong fnv32(register const char *s){
    register ulong hash = FNV_OFFSET_32;

    while(*s)
        hash = (hash ^ (*(s++)))*FNV_PRIME_32;

    return hash;
}
#17
Veo que ya te llevas la casa a otro lugar. Seguro que les gusta este aporte aunque tenga ya tiempo

Saludos