|
252
|
Programación / Programación Visual Basic / Re: Uso de API's ReadProcessMemory y WriteProcessMemory
|
en: 5 Mayo 2008, 23:38 pm
|
y bueno ya que esta el hilo abierto estaria lindo quien tenga otros ejemplo lo ponga a continuacion para hacer una pequeña recopilacion sobre el uso de estas dos apis. que no entiendes? Yo tengo codes pero en C o asm, si te vale... A ver, el uso de estas dos apis es muy simple, me autocito de un tuto de rootkits q escribí, ya de paso pongo algunas apis relaccionadas q os serán utiles: OpenProcess:
HANDLE OpenProcess( DWORD dwDesiredAccess, // access flag BOOL bInheritHandle, // handle inheritance flag DWORD dwProcessId // process identifier );
Esta es la documentación que Microsoft nos proporciona sobre este api. Ahora os la detallo un poco: Valor de retorno: El valor devuelto es el manejador del proceso, explicado de una forma simple es la forma que tendremos en el código para referirnos al proceso. El valor que devuelve lo almacenaremos en una variable del tipo HANDLE. DWORD dwDesiredAccess: Es el modo de apertura del proceso, en nuestro caso nos daremos todos los privilegios con PROCESS_ALL_ACCESS. BOOL bInheritHandle: Toma valor true (hereda) o false (no hereda). Nosotros pondremos false. DWORD dwProcessId: Es el PID del proceso, luego veremos como obtenerlo con el nombre del proceso.
VirtualAllocEx:
Sirve para reservar espacio en la memoria de un proceso.
LPVOID VirtualAllocEx( HANDLE hProcess, // process within which to allocate memory LPVOID lpAddress, // desired starting address of allocation DWORD dwSize, // size, in bytes, of region to allocate DWORD flAllocationType, // type of allocation DWORD flProtect // type of access protection );
Valor de retorno: La dirección donde empezaremos a escribir con WriteProcessMemory.
HANDLE hProcess: El manejador del proceso en el cual vamos a escribir. Es el valor que nos devuelve OpenProcess. LPVOID lpAddress: La dirección donde empezamos a reservar espacio, lo dejaremos en NULL. DWORD dwSize: El tamaño en bytes de la región que queremos reservar, en nuestro caso será el tamaño de la cadena que contiene la ruta de la dll a inyectar. DWORD flAllocationType: El motivo por el cual queremos reservar la memoria, en nuestro caso MEM_COMMIT|MEM_RESERVE. DWORD flProtect: El tipo de protección, en nuestro caso PAGE_READWRITE.
WriteProcessMemory:
Sirve para escribir en la memoria anteriormente reservada. BOOL WriteProcessMemory( HANDLE hProcess, // handle to process whose memory is written to LPVOID lpBaseAddress, // address to start writing to LPVOID lpBuffer, // pointer to buffer to write data to DWORD nSize, // number of bytes to write LPDWORD lpNumberOfBytesWritten // actual number of bytes //written );
Valor de retorno: Ver LPDWORD lpNumberOfBytesWritten. HANDLE hProcess: El valor devuelto por OpenProcess. LPVOID lpBaseAddress: La dirección por donde empezaremos a escribir. Es el valor devuelto por VirtualAllocEx. LPVOID lpBuffer: Lo que queremos escribir, en nuestro caso la ruta de nuestra dll.
DWORD nSize: El tamaño en bytes de lo que queremos escribir, es decir el tamaño en bytes de la ruta de nuestra dll. LPDWORD lpNumberOfBytesWritten: Es el numero de bytes que se han escrito correctamente, así como el valor de retorno, nosotros lo dejaremos en NULL ya que no nos interesa.
Y ReadProcessMemory es lo mismo q WritePM pero para leer xD Poned dudas mas concretas 1S4ludo
|
|
|
253
|
Programación / Programación Visual Basic / Re: leer archivo con api's
|
en: 4 Mayo 2008, 13:37 pm
|
Creo q ya te lo contesté, pero weno. Con CreateFile abres el archivo, con GetFileSize obtienes su tamaño y con ReadFile lo lees. Si no tb puedes mapearlo en memoria y acceder a el trankilamente usando CreateFile para abrirlo, CreateFileMapping y MapViewOfFile.
Usa CloseHandle con los handles que te dan CreateFile y CreateFileMapping y UnmapViewOfFile con el de MapViewOfFile
|
|
|
256
|
Seguridad Informática / Abril negro / Re: Abril Negro 2008: Taller de ASM by E0N
|
en: 4 Mayo 2008, 01:12 am
|
Eso así obiamente no te va a funcionar nunca, tienes que usar el api wsprintf para concatenar texto con números. Ojito a esto: Note Unlike other Windows functions, wsprintf uses the C calling convention (_cdecl), rather than the Pascal calling convention. As a result, it is the responsibility of the calling process to pop arguments off the stack, and arguments are pushed on the stack from right to left. In C-language modules, the C compiler performs this task. Vamos, que tienes que cuadrar la pila tu, por que el api no lo hace por ti. El programa sería así: include 'H:\archivos de programa\fasm\include\win32ax.inc' .data veces db ' veces',0 texto dd 0 .code start: invoke MessageBoxA,0,'Quieres que te toque los huevos?','Quieres?',0 mov ebx, 1 ; No uses eax como contdor porque cambia tras llamar a un api :P putada: invoke LocalAlloc, LPTR, 100 mov [texto], eax push veces push ebx invoke wsprintf, [texto], '%d%s' add esp, 16 invoke MessageBox, 0, [texto], 'te he tocado los huevos', 0 invoke LocalFree, [texto] add ebx,1 jmp putada .end start
Hechale un ojo con el debugger para ver como el api no restaura la pila y por que hay que poner ese add esp,16 Salu2
|
|
|
257
|
Seguridad Informática / Abril negro / Re: Abril Negro 2008: Taller de ASM by E0N
|
en: 2 Mayo 2008, 13:03 pm
|
Pues usando el api como todo en asm Eso lo explicaré mas adelante, q no me das tiempo!! Puedes usar CreateFile para abrir el archivo deseado y a partir de aki tienes dos opciones: 1 - Usar ReadFile y WriteFile para escribir y leer el archivo 2 - Mapear el archivo con CreateFileMapping y MapViewOfFile Para obtener el tamaño del archivo usa GetFileSize y no se te olvide usar CloseHandle y UnmapViewOfFile. Salu3 E0N PD - Mirate el código de mi Small Joiner, que te será útil para lo que quieres hacer
|
|
|
258
|
Programación / Programación Visual Basic / Re: ms-dos vb
|
en: 2 Mayo 2008, 12:42 pm
|
También puedes usar pipes, q es mas elegante Ejemplo de la api guide: 'Redirects output from console program to textbox. 'Requires two textboxes and one command button. 'Set MultiLine property of Text2 to true. ' 'Original bcx version of this program was made by ' dl <dl@tks.cjb.net> 'VB port was made by Jernej Simoncic <jernej@isg.si> 'Visit Jernejs site at http://www2.arnes.si/~sopjsimo/ ' 'Note: don't run plain DOS programs with this example 'under Windows 95,98 and ME, as the program freezes when 'execution of program is finnished. Option Explicit Private Declare Function CreatePipe Lib "kernel32" (phReadPipe As Long, phWritePipe As Long, lpPipeAttributes As SECURITY_ATTRIBUTES, ByVal nSize As Long) As Long Private Declare Sub GetStartupInfo Lib "kernel32" Alias "GetStartupInfoA" (lpStartupInfo As STARTUPINFO) Private Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" (ByVal lpApplicationName As String, ByVal lpCommandLine As String, lpProcessAttributes As Any, lpThreadAttributes As Any, ByVal bInheritHandles As Long, ByVal dwCreationFlags As Long, lpEnvironment As Any, ByVal lpCurrentDriectory As String, lpStartupInfo As STARTUPINFO, lpProcessInformation As PROCESS_INFORMATION) As Long Private Declare Function SetWindowText Lib "user32" Alias "SetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String) As Long Private Declare Function ReadFile Lib "kernel32" (ByVal hFile As Long, lpBuffer As Any, ByVal nNumberOfBytesToRead As Long, lpNumberOfBytesRead As Long, lpOverlapped As Any) As Long Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long Private Type SECURITY_ATTRIBUTES nLength As Long lpSecurityDescriptor As Long bInheritHandle As Long End Type Private Type PROCESS_INFORMATION hProcess As Long hThread As Long dwProcessId As Long dwThreadId As Long End Type Private Type STARTUPINFO cb As Long lpReserved As Long lpDesktop As Long lpTitle As Long dwX As Long dwY As Long dwXSize As Long dwYSize As Long dwXCountChars As Long dwYCountChars As Long dwFillAttribute As Long dwFlags As Long wShowWindow As Integer cbReserved2 As Integer lpReserved2 As Byte hStdInput As Long hStdOutput As Long hStdError As Long End Type Private Type OVERLAPPED ternal As Long ternalHigh As Long offset As Long OffsetHigh As Long hEvent As Long End Type Private Const STARTF_USESHOWWINDOW = &H1 Private Const STARTF_USESTDHANDLES = &H100 Private Const SW_HIDE = 0 Private Const EM_SETSEL = &HB1 Private Const EM_REPLACESEL = &HC2 Private Sub Command1_Click() Command1.Enabled = False Redirect Text1.Text, Text2 Command1.Enabled = True End Sub Private Sub Form_Load() Text1.Text = "ping" End Sub Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) If Command1.Enabled = False Then Cancel = True End Sub Sub Redirect(cmdLine As String, objTarget As Object) Dim i%, t$ Dim pa As SECURITY_ATTRIBUTES Dim pra As SECURITY_ATTRIBUTES Dim tra As SECURITY_ATTRIBUTES Dim pi As PROCESS_INFORMATION Dim sui As STARTUPINFO Dim hRead As Long Dim hWrite As Long Dim bRead As Long Dim lpBuffer(1024) As Byte pa.nLength = Len(pa) pa.lpSecurityDescriptor = 0 pa.bInheritHandle = True pra.nLength = Len(pra) tra.nLength = Len(tra) If CreatePipe(hRead, hWrite, pa, 0) <> 0 Then sui.cb = Len(sui) GetStartupInfo sui sui.hStdOutput = hWrite sui.hStdError = hWrite sui.dwFlags = STARTF_USESHOWWINDOW Or STARTF_USESTDHANDLES sui.wShowWindow = SW_HIDE If CreateProcess(vbNullString, cmdLine, pra, tra, True, 0, Null, vbNullString, sui, pi) <> 0 Then SetWindowText objTarget.hwnd, "" Do Erase lpBuffer() If ReadFile(hRead, lpBuffer(0), 1023, bRead, ByVal 0&) Then SendMessage objTarget.hwnd, EM_SETSEL, -1, 0 SendMessage objTarget.hwnd, EM_REPLACESEL, False, lpBuffer(0) DoEvents Else CloseHandle pi.hThread CloseHandle pi.hProcess Exit Do End If CloseHandle hWrite Loop CloseHandle hRead End If End If End Sub
Miratelo, al principio pueden costar, pero son faciles de usar Salu2
|
|
|
259
|
Seguridad Informática / Abril negro / Re: Abril Negro 2008: Taller de ASM by E0N
|
en: 2 Mayo 2008, 00:54 am
|
Veo q has hecho progresos ^^ Si quieres dejar el código un poco más legible te recomiendo el uso de invoke para poder llamar a las apis como se haria en un lenguaje de alto nivel. Por ejemplo esto: push 0 push 0 push archivo push web push 0 call [Descargar]
Te quedaría así: invoke Descargar, 0, web, archivo, 0, 0
Mucho más legible Salu2
|
|
|
260
|
Seguridad Informática / Abril negro / Re: Abril Negro 2008: Taller de ASM by E0N
|
en: 1 Mayo 2008, 16:53 pm
|
No Puedes adaptarte un poco el codigo, pero copiando y pegando tal cual no te va a funcionar. Mejor aprende a programarte un crypter tu mismo
He actualizado el primer post. Se han añadido tres capitulos, uno con unas cuantas instrucciones que nos faltaban por aprender, otro con las distintas estructuras que puede tomar el código en FASM y otro en el que explico como declarar variables, asi que cuando los leais ya sabreis hacer algún programilla básico Salu2 E0N
|
|
|
|
|
|
|