|
Mostrar Temas
|
Páginas: [1]
|
1
|
Programación / .NET (C#, VB.NET, ASP) / [Source] Inyeccion Dll Microsoft Visual C# (Sharp) 2008
|
en: 3 Octubre 2009, 02:26 am
|
Hola, guiandome de codigos de inyeccion dll en no se cuantos lenguajes pude lograr uno en C# .
Aqui se los dejo espero lo disfruten :
Codigo InyectDll: private void InjectDLL(IntPtr hProcess, String strDLLName) { IntPtr bytesout; Int32 LenWrite = strDLLName.Length + 1; IntPtr AllocMem = (IntPtr)APIS.VirtualAllocEx(hProcess, (IntPtr)null, (uint)LenWrite, 0x1000, 0x40); APIS.WriteProcessMemory(hProcess, AllocMem, strDLLName, (UIntPtr)LenWrite, out bytesout); UIntPtr Injector = (UIntPtr)APIS.GetProcAddress(APIS.GetModuleHandle("kernel32.dll"), "LoadLibraryA"); if (Injector == null) { // Agreguen aqui un messagebox o lo que deseen para mostrar el error :P. return; } IntPtr hThread = (IntPtr)APIS.CreateRemoteThread(hProcess, (IntPtr)null, 0, Injector, AllocMem, 0, out bytesout); if (hThread == null) { // Agreguen aqui un messagebox o lo que deseen para mostrar el error :P. return; } int Result = APIS.WaitForSingleObject(hThread, 10 * 1000); if (Result == 0x00000080L || Result == 0x00000102L || Result == 0xFFFFFFF) { // Agreguen aqui un messagebox o lo que deseen para mostrar el error :P. if (hThread != null) { APIS.CloseHandle(hThread); } return; } Thread.Sleep(1000); APIS.VirtualFreeEx(hProcess, AllocMem, (UIntPtr)0, 0x8000); if (hThread != null) { APIS.CloseHandle(hThread); } return; }
Codigo clase APIS: private struct APIS { [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] public static extern bool VirtualFreeEx(IntPtr hProcess, IntPtr lpAddress, UIntPtr dwSize, uint dwFreeType); [DllImport("kernel32.dll", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern UIntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32.dll")] public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, string lpBuffer, UIntPtr nSize, out IntPtr lpNumberOfBytesWritten); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32", SetLastError = true, ExactSpelling = true)] public static extern Int32 WaitForSingleObject(IntPtr handle, Int32 milliseconds); [DllImport("kernel32")] public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, UIntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out IntPtr lpThreadId); [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(UInt32 dwDesiredAccess, Int32 bInheritHandle, Int32 dwProcessId); [DllImport("kernel32.dll")] public static extern Int32 CloseHandle(IntPtr hObject); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern IntPtr GetModuleHandle(string lpModuleName); }
Bien, ahora en using:using System; using System.IO; using System.Data; using System.Linq; using System.Text; using System.Drawing; using System.Threading; using System.Diagnostics; using System.Windows.Forms; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.InteropServices;
Codigo para los procesos : private Int32 GetProcessID(String proc) { Process[] ProcList; ProcList = Process.GetProcessesByName(proc); return ProcList[0].Id; }
Ahora Inyectemos la dll : private void button1_Click(object sender, EventArgs e) { string DllStrng = "C:\\Ladll.Dll"; Int32 ProcID = GetProcessID("Explorer"); //Coloquen aqui el nombre del proceso :P sin la extensión ".exe". if (ProcID >= 0) { IntPtr hProcess = (IntPtr)APIS.OpenProcess(0x1F0FFF, 1, ProcID); if (hProcess == null) { // Agreguen aqui un messagebox o lo que deseen para mostrar el error :P. return; } else { InjectDLL(hProcess, DllStrng); } } }
Listo! xD. como ven este codigo no puede inyectar dlls en procesos como svchost.exe pues necesita permisos (algo que no se hacer), me imagino que se hace con AdjustTokenPrivileges o algo parecido en fin si quieren permisos agreguenselo uds y si pueden muestrenlo aqui para ayudar a los demas .
yo actualmente ando estudiando Kernel Module, para asi poder hacer fiesta con los procesos xD.
en fin disfrutenlo, hasta pronto!
Creditos: WhatsHappen?
!
|
|
|
2
|
Programación / .NET (C#, VB.NET, ASP) / Inyeccion dll: [ Delphi ] - [ C++ ] - [ VB ] - [ Masm32 ] - [ C# ??? ]
|
en: 18 Septiembre 2009, 01:23 am
|
En VB: Private Const PAGE_READWRITE As Long = &H4 Private Const MEM_RELEASE As Long = &H8000 Private Const MEM_COMMIT As Long = &H1000 Private Const STANDARD_RIGHTS_REQUIRED As Long = &HF0000 Private Const SYNCHRONIZE As Long = &H100000 Private Const PROCESS_ALL_ACCESS As Long = (STANDARD_RIGHTS_REQUIRED Or SYNCHRONIZE Or &HFFF) Private Const INFINITE As Long = &HFFFFFF Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long Private Declare Function GetProcAddress Lib "kernel32" (ByVal hModule As Long, ByVal lpProcName As String) As Long Private Declare Function GetModuleHandle Lib "kernel32" Alias "GetModuleHandleA" (ByVal lpModuleName As String) As Long Private Declare Function VirtualAllocEx Lib "kernel32" (ByVal hProcess As Long, ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As Long Private Declare Function WriteProcessMemory Lib "kernel32" (ByVal hProcess As Long, lpBaseAddress As Any, lpBuffer As Any, ByVal nSize As Long, lpNumberOfBytesWritten As Long) As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Declare Function CreateRemoteThread Lib "kernel32" (ByVal hProcess As Long, lpThreadAttributes As Long, ByVal dwStackSize As Long, lpStartAddress As Long, lpParameter As Any, ByVal dwCreationFlags As Long, lpThreadId As Long) As Long Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long Public Function Inyecta(RutaDll As String, Pid As Long) As Integer Dim proc As Long Dim nload As Long Dim rems As Long Dim longi As Long Dim RemThread As Long Dim Tid As Long On Error GoTo Error proc = OpenProcess(PROCESS_ALL_ACCESS, False, Pid) nload = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA") rems = VirtualAllocEx(proc, 0, Len(RutaDll), MEM_COMMIT, PAGE_READWRITE) WriteProcessMemory proc, ByVal rems, ByVal RutaDll, Len(RutaDll), longi CreateRemoteThread proc, ByVal 0, 0, ByVal nload, ByVal rems, 0, Tid WaitForSingleObject rems, INFINITE CloseHandle proc CloseHandle rems Inyecta = 0 Exit Function Error: Inyecta = 1 End Function '----------------------------------------------------------------------------------' Private Sub Form_Load() Dim ruta As Long Dim resultado As Integer ruta = Shell("notepad.exe") resultado = Inyecta("C:\ladll.dll", ruta) If resultado = 0 Then MsgBox "Dll Inyectada con éxito!!!", , "Información" Else MsgBox "A ocurrido un error", vbCritical, "Información" End If End End Sub
En Delphi: Procedure InjectDll(Dll:string); var Thread,HandleWindow: THandle; DMod,Lib: Pointer; ThreadID,Written: Cardinal; WindowName,ProcessId: DWORD; begin WindowName := FindWindow(nil, 'Tester'); ThreadId := GetWindowThreadProcessId(WindowName, @ProcessId); HandleWindow := OpenProcess(PROCESS_ALL_ACCESS, False, ProcessId); Lib := GetProcAddress(GetModuleHandle(PChar('kernel32.dll')), PChar('LoadLibraryA')); DMod := VirtualAllocEx(HandleWindow, nil, Length(Dll) + 1, MEM_COMMIT or MEM_RESERVE, PAGE_EXECUTE_READWRITE); if WriteProcessMemory(HandleWindow, DMod, @Dll[1>, Length(Dll), Written) then Thread := CreateRemoteThread(HandleWindow, nil, 0, Lib, DMod, 0, ThreadID); WaitForSingleObject(Thread, INFINITE); CloseHandle(HandleWindow); CloseHandle(Thread); end;
En Masm: .386 .model flat,stdcall option casemap:none include \masm32\include\windows.inc include \masm32\include\kernel32.inc includelib \masm32\lib\kernel32.lib .const ID_proceso EQU 2964 ;La ID del proceso q sea .data Kernel32 db "kernel32.dll", 0 LoadLibrary_nombre db "LoadLibraryA", 0 DLL db "C:\DLL.dll", 0 .data? Proceso_ID DWORD ? Proceso_handle DWORD ? Kernel32_offset DWORD ? LoadLibrary_offset DWORD ? String DWORD ? Proceso PROCESSENTRY32 <?> .code Start: invoke GetModuleHandle, addr Kernel32 mov Kernel32_offset, eax invoke GetProcAddress, Kernel32_offset, addr LoadLibrary_nombre mov LoadLibrary_offset, eax mov Proceso.dwSize, 296 invoke OpenProcess, PROCESS_ALL_ACCESS, FALSE, ID_proceso mov Proceso_handle, eax invoke VirtualAllocEx, Proceso_handle, NULL, 64, MEM_COMMIT + MEM_RESERVE, PAGE_READWRITE mov String, eax invoke WriteProcessMemory, Proceso_handle, String, addr DLL, 64, NULL invoke CreateRemoteThread, Proceso_handle, NULL, NULL, LoadLibrary_offset, String, NULL, NULL invoke CloseHandle, Proceso_handle invoke ExitProcess, 0 End Start
En C++ [Sin Dll ]: #include <windows.h> #include <tlhelp32.h> #include <stdio.h> typedef int (WINAPI *datMessageBoxA) (HWND, LPCTSTR, LPCTSTR, UINT); struct datos { datMessageBoxA apiMessageBoxA; char titulo [20]; char mensaje [20]; }; DWORD GetAdres(char *module, char *function); DWORD inyectada (datos *data) { data -> apiMessageBoxA (0, data->mensaje, data->titulo, 0); return 0; } void inyectora() { int pid; HANDLE proc; datos dat; DWORD TamFun; void* esp; HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); PROCESSENTRY32 procinfo = { sizeof(PROCESSENTRY32) }; while(Process32Next(handle, &procinfo)) { if(!strcmp(procinfo. szExeFile, "notepad.exe")) { CloseHandle(handle); pid = procinfo.th32ProcessID; } } CloseHandle(handle); proc = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid); dat.apiMessageBoxA = (datMessageBoxA) GetAdres ("USER32.DLL", "MessageBoxA"); sprintf(dat. mensaje,"holaaaaaa!!!"); datos *dat_ = (datos*) VirtualAllocEx(proc, 0, sizeof(datos), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(proc, dat_, &dat, sizeof(datos), NULL); TamFun = (long unsigned int) inyectora - (long unsigned int)inyectada; esp = VirtualAllocEx(proc, 0, TamFun, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(proc, esp, (void*)inyectada, TamFun, NULL); CreateRemoteThread(proc, NULL, 0, (LPTHREAD_START_ROUTINE) esp, dat_, 0, NULL); } void main() { inyectora(); } DWORD GetAdres(char *module, char *function) { HMODULE dh = LoadLibrary(module); DWORD pf = (DWORD)GetProcAddress(dh,function); FreeLibrary(dh); return pf; }
Wowww! en todos los lenguajes que se pueden no ? Pero y en C# ? Alguien tiene alguno ? Hasta luego .
|
|
|
3
|
Programación / .NET (C#, VB.NET, ASP) / Inyeccion dll sin dll, by E0N. Problema: Edicion de Memoria. [Convertir a C#]
|
en: 13 Septiembre 2009, 18:43 pm
|
Bien, ya muchos han de haber visto el código de E0N, el de inyección DLL sin DLL que bueno es no? . Aquí un ejemplo del mismo . #pragma hdrstop #include <windows.h> #include <tlhelp32.h> #include <stdio.h>
//Creamos un puntero a la api que queremos inyectar typedef int (WINAPI *datMessageBoxA) (HWND, LPCTSTR, LPCTSTR, UINT);
//La estructura que inyectaremos struct datos { datMessageBoxA apiMessageBoxA; char titulo [100]; char mensaje [100]; };
//Declaración de funciones DWORD GetAdres(char *module, char *function);
//La función que inyectaremos DWORD inyectada (datos *data) { data -> apiMessageBoxA (0, data->mensaje, data->titulo, 0); return 0; }
//La función iyectora void inyectora() { int pid; // Este es el pid del proceso en el que nos queremos inyectar HANDLE proc; // El handle del proceso en el que inyectaremos datos dat; // El tipo de dato de la estructura DWORD TamFun; // El tamaño de la función a inyectar void* esp; // Lugar de memoria donde copiaremos nuestra función
HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0); //Obtenemos el pid PROCESSENTRY32 procinfo = { sizeof(PROCESSENTRY32) }; while(Process32Next(handle, &procinfo)) { if(!strcmp(procinfo.szExeFile, "AVKTray.exe")) { CloseHandle(handle); pid = procinfo.th32ProcessID; } } CloseHandle(handle);
//Abrimos el proceso en el que nos inyectaremos
proc = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid);
//Metemos la dirección de la api en la estructura llamndo a la función GetAdres dat.apiMessageBoxA = (datMessageBoxA) GetAdres ("USER32.DLL", "MessageBoxA");
//Inicializamos las variables que contendrán el mensaje sprintf(dat.mensaje,"holaaaaaa!!!"); sprintf(dat.titulo,"titulo!!!");
//Reservamos espacio para nuestra estructura en el proceso a inyectar y la escribimos datos *dat_ = (datos*) VirtualAllocEx(proc, 0, sizeof(datos), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); WriteProcessMemory(proc, dat_, &dat, sizeof(datos), NULL);
//Calculamos el tamaño de la función a inyectar TamFun = (long unsigned int) inyectora - (long unsigned int)inyectada;
//Reservamos espacio para la función, escribimos en él y creamos un hilo esp = VirtualAllocEx(proc, 0, TamFun, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); WriteProcessMemory(proc, esp, (void*)inyectada, TamFun, NULL); CreateRemoteThread(proc, NULL, 0, (LPTHREAD_START_ROUTINE) esp, dat_, 0, NULL); }
//La función main void main() { inyectora(); }
//Función que nos devuelve un DWORD con la dirección de una api DWORD GetAdres(char *module, char *function) { HMODULE dh = LoadLibrary(module); DWORD pf = (DWORD)GetProcAddress(dh,function); FreeLibrary(dh); return pf; } Bien, ese código inyecta un msgbox hasta donde logre ver y probar, lo inyecta en procesos protegidos! como el hl.exe que tiene su protección "sXe Injected", bueno la pregunta mía es: ¿Ya que se puede inyectar un MsgBox, se podría inyectar un código que no solo muestre un mensaje sino que cambie un valor X en una dirección X en su memoria? Sera esto posible? Pues las palabras de E0N Fueron: De todas formas si te permite mostrar el MessageBox, quiere decir que has podido usar un montón de apis "peligrosas" como WriteProcessMemory, CreateRemoteThread o VirtualAllocEx, con lo que facilmente podrías inyectarle una dll (por facilitar la tarea) y retocar ciertos valores en memoria para hacer trampas. Según el debí haber ido a cheatengine.org los cuales son Cheaters profesionales, he ido pero como que les ha quedado grande el codigote de E0N, alguien aquí presente sabría cómo hacer ello?. He aquí una demostración de una DLL en Delphi, que cambiaba valores en la memoria del proceso donde se inyectó: library DllProyect;
uses SysUtils, Windows, Classes, DllForm in 'Dll.pas' {DllForm};
{$R *.res} var hProcess:THandle; hId:Cardinal;
procedure funcStartCheating; begin; MainForm:=TMainForm.Create(nil); MainForm.ShowModal; end; begin hProcess:=OpenProcess(PROCESS_ALL_ACCESS,false,GetCurrentProcessID); CreateRemoteThread(hProcess,nil,0,@funcStartCheating,@funcStartCheating,0,hID); end. Bien ese es el código de la DLL, la cual me permite mostrar un Formulario para hacerme más fácil el trabajo de edición de memoria, he aquí el código de edición de memoria: var MainForm: TMainForm; Memory: DWORD; j: integer; ZeroBytes: Array of Byte;
procedure TMainForm.Timer1Timer(Sender: TObject); var number: byte; character: char; j: integer; Addresspointer: Dword; begin
if Checkbox1.Checked=True then begin Addresspointer:= PDWORD($0087A35C)^+$93; PBYTE(Addresspointer)^:=0; end;
if Checkbox5.Checked=True then begin CopyMemory(ptr(PDWORD($004023c1)^+$1),@ZeroBytes,8); end;
if checkbox12.Checked = true then begin; PBYTE($00928D1E)^:=0; end;
if checkbox10.Checked = true then begin; CopyMemory(ptr($00010701),@ZeroBytes,10); end; end;
end. Bien eso cambia el valor de la direccion X con el Valor X para lograr hacer trampas , ahora mi duda es: ¿Cómo se hace ello con el codigo de Inyección DLL sin DLL? ¿Cómo integro tal codigo dentro de ese inyector? ¿Es posible?. Según E0N si. Espero alguien sepa de que estoy hablando y me pueda ayudar, sin mas que decir me despido con un tipico "Gracias de antemano" aunque no logren ayudarme un gracias nunca esta demas . pd: me falto una pregunta Y la más importante: ¿SE PUEDE CAMBIAR ESTE CODIGO A C# 2008? Hasta Luego!.
|
|
|
4
|
Programación / .NET (C#, VB.NET, ASP) / [C#] Buscar archivo ".exe" desde mi form y mostrarlo en un combobox?
|
en: 4 Septiembre 2009, 08:16 am
|
Hola, espero no molestar traigo una duda como el tema lo dice espero puedan ayudarme, a continuación se las hago presente. Estoy en el proceso de crear una aplicación que busque ciertos archivos con extensiones “.exe”, para luego que los encuentre los muestre en un “Combobox” y así poder realizar la función deseada. Lo que deseo saber es: ¿Cómo busco en el disco local C: los archivos con ese nombre?, y luego de encontrarlos los mostrara en un “combobox”, daremos un ejemplo “Photoshop.exe”, claro será otro nombre el cual no deseo decir por derechos de autor por decir así. Simple, sé que es de novatos pero no logro nada; estoy trabajando con C# 2008, y no encuentro nada para poder hacer tal búsqueda, alguien tiene idea de cómo hacerla?. Gracias por adelantado a quien esté dispuesto a ayudarme, espero no molestar y no hacerles perder tiempo. PD: Ya he buscado lo suficiente en la web “MDSN” y hasta donde logrè hacer algo, no me sirvió.
|
|
|
|
|
|
|