{"id":64,"date":"2011-11-22T18:29:46","date_gmt":"2011-11-22T18:29:46","guid":{"rendered":"http:\/\/52.15.227.128\/?p=64"},"modified":"2018-01-03T23:34:52","modified_gmt":"2018-01-03T23:34:52","slug":"inyector-dll-winapi","status":"publish","type":"post","link":"https:\/\/0aps.me\/blog\/2011\/11\/22\/inyector-dll-winapi\/","title":{"rendered":"Inyector dll &#8211; WinApi"},"content":{"rendered":"<p>Este art\u00edculo pertenece a una serie de dudas antiguas que fueron publicadas en foros de internet antes de la creaci\u00f3n del blog, lo plasmo aqu\u00ed para no perderlas y que formen parte de la antolog\u00eda.<\/p>\n<p>Post:<\/p>\n<blockquote><p>\nPues como tenia muchisimo sin programar nada y ultimamente he estado leyendo sobre inyecciones dll y manejo de memoria, salio esto de practica:<\/p>\n<p>Es un inyector de dlls, el proceso es sencillo: escribes el proceso , buscas la ruta de la dll, verificas el proceso y lo inyectas. <\/p>\n<p>[code language=&#8221;cpp&#8221;]<br \/>\n#include &lt;windows.h&gt;<br \/>\n#include &lt;stdio.h&gt;<br \/>\n#include &lt;Tlhelp32.h&gt;<\/p>\n<p>\/*  Declare Windows procedure  *\/<br \/>\nLRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);<\/p>\n<p>void Buscar_Dll   (HWND);<br \/>\nvoid CrearVentana (HWND);<br \/>\nint Inyectar      ();<br \/>\nint Buscar_Proceso();<br \/>\nint Existe_A      (char *);<\/p>\n<p>\/*  Make the class name into a global variable  *\/<br \/>\nchar szClassName [   ]   = &quot;WindowsApp&quot;;<br \/>\nchar ruta_dll    [256];<br \/>\nchar n_Proceso   [100];<br \/>\nchar mensaje     [256];<\/p>\n<p>HANDLE CProc;              \/\/Para crear la captura de la lista de procesos<br \/>\nHANDLE hProceso;           \/\/Para guardar el manejador del proceso<br \/>\nPROCESSENTRY32 Proceso;    \/\/Necesario para realizar la captura de procesos<\/p>\n<p>HWND   Button1, Button2, Button3, Edit1, Edit2, ComboBox, Static1, Static2;<br \/>\nHINSTANCE instancia;      <\/p>\n<p>HBRUSH hbrBackground = CreateSolidBrush(RGB(258, 205, 255));<\/p>\n<p>HANDLE  hProc;<br \/>\nDWORD   pid;<br \/>\nLPVOID  dDll;<br \/>\nLPVOID  dLoadLibrary;<\/p>\n<p>int WINAPI WinMain (HINSTANCE hThisInstance,<br \/>\n                    HINSTANCE hPrevInstance,<br \/>\n                    LPSTR lpszArgument,<br \/>\n                    int nFunsterStil)<\/p>\n<p>{<br \/>\n    HWND hwnd;                   \/* This is the handle for our window          *\/<br \/>\n    MSG messages;               \/* Here messages to the application are saved *\/<br \/>\n    WNDCLASSEX wincl;          \/* Data structure for the windowclass         *\/<br \/>\n    instancia = hThisInstance;<\/p>\n<p>    \/* The Window structure *\/<br \/>\n    wincl.hInstance = hThisInstance;<br \/>\n    wincl.lpszClassName = szClassName;<br \/>\n    wincl.lpfnWndProc = WindowProcedure;      \/* This function is called by windows *\/<br \/>\n    wincl.style = CS_DBLCLKS;                \/* Catch double-clicks                 *\/<br \/>\n    wincl.cbSize = sizeof (WNDCLASSEX);<\/p>\n<p>    \/* Use default icon and mouse-pointer *\/<br \/>\n    wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);<br \/>\n    wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);<br \/>\n    wincl.hCursor = LoadCursor (NULL, IDC_ARROW);<br \/>\n    wincl.lpszMenuName = NULL;                 \/* No menu *\/<br \/>\n    wincl.cbClsExtra = 0;                      \/* No extra bytes after the window class *\/<br \/>\n    wincl.cbWndExtra = 0;                      \/* structure or the window instance *\/<\/p>\n<p>    \/* Use Windows&#8217;s default color as the background of the window *\/<br \/>\n    wincl.hbrBackground = (HBRUSH) CreateSolidBrush(RGB(258, 205, 255));<\/p>\n<p>    \/* Register the window class, and if it fails quit the program *\/<br \/>\n    if (!RegisterClassEx (&amp;wincl))<br \/>\n        return 0;<\/p>\n<p>    \/* The class is registered, let&#8217;s create the program*\/<br \/>\n    hwnd = CreateWindowEx (<br \/>\n           0,                   \/* Extended possibilites for variation *\/<br \/>\n           szClassName,         \/* Classname *\/<br \/>\n           &quot;Windows App&quot;,       \/* Title Text *\/<br \/>\n           WS_OVERLAPPEDWINDOW, \/* default window *\/<br \/>\n           CW_USEDEFAULT,       \/* Windows decides the position *\/<br \/>\n           CW_USEDEFAULT,       \/* where the window ends up on the screen *\/<br \/>\n           544,                 \/* The programs width *\/<br \/>\n           375,                 \/* and height in pixels *\/<br \/>\n           HWND_DESKTOP,        \/* The window is a child-window to desktop *\/<br \/>\n           NULL,                \/* No menu *\/<br \/>\n           hThisInstance,       \/* Program Instance handler *\/<br \/>\n           NULL                 \/* No Window Creation data *\/<br \/>\n           );<\/p>\n<p>    \/* Make the window visible on the screen *\/<br \/>\n    ShowWindow (hwnd, nFunsterStil);<\/p>\n<p>    \/* Run the message loop. It will run until GetMessage() returns 0 *\/<br \/>\n    while (GetMessage (&amp;messages, NULL, 0, 0))<br \/>\n    {<br \/>\n        \/* Translate virtual-key messages into character messages *\/<br \/>\n        TranslateMessage(&amp;messages);<br \/>\n        \/* Send message to WindowProcedure *\/<br \/>\n        DispatchMessage(&amp;messages);<\/p>\n<p>    }<\/p>\n<p>    \/* The program return-value is 0 &#8211; The value that PostQuitMessage() gave *\/<br \/>\n    return messages.wParam;<br \/>\n}<\/p>\n<p>\/*  This function is called by the Windows function DispatchMessage()  *\/<\/p>\n<p>LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)<br \/>\n{<br \/>\n    switch (message)                  \/* handle the messages *\/<br \/>\n    {<\/p>\n<p>          case WM_CREATE:<br \/>\n                          CrearVentana(hwnd);<br \/>\n                          break;<\/p>\n<p>          case WM_COMMAND:<\/p>\n<p>            \/\/buscar dll<br \/>\n            if( (HWND)lParam == Button1)<br \/>\n            {<br \/>\n                       Buscar_Dll(hwnd);<br \/>\n            }<\/p>\n<p>            \/\/edit d la ruta<br \/>\n            if( (HWND)lParam == Edit1  )<br \/>\n            {<br \/>\n                 GetWindowText(Edit1, ruta_dll, 255);<br \/>\n            }<\/p>\n<p>            \/\/edit del proceso<br \/>\n            if( (HWND)lParam  == Edit2)<br \/>\n            {<br \/>\n                 GetWindowText(Edit2, n_Proceso, 255);<br \/>\n            } <\/p>\n<p>            \/\/buscar proceso<br \/>\n            if( (HWND)lParam == Button2 )<br \/>\n            {<br \/>\n                 ( Buscar_Proceso() == 0 )  ?          <\/p>\n<p>                 MessageBox(0, &quot;El proceso esta corriendo&quot;, &quot;Proceso&quot;, 0)    :<br \/>\n                 MessageBox(0, &quot;El proceso no esta corriendo&quot;, &quot;Proceso&quot;, 0) ;<br \/>\n            }  <\/p>\n<p>            \/\/inyectar<br \/>\n            if( (HWND)lParam == Button3 )<br \/>\n            {<\/p>\n<p>                switch( Inyectar() )<br \/>\n                {<br \/>\n                                case  0:<br \/>\n                                case -1:<br \/>\n                                case -2:<br \/>\n                                case -3:<br \/>\n                                case -4:<br \/>\n                                case -5:<br \/>\n                                SendMessage(ComboBox, WM_SETTEXT, 0, (LPARAM)mensaje);<br \/>\n                                break;<\/p>\n<p>                }<\/p>\n<p>            }<\/p>\n<p>            break; <\/p>\n<p>        \/\/mensaje para cambiarle el fondo al static<br \/>\n        case WM_CTLCOLORSTATIC:<br \/>\n        {<br \/>\n           SetBkMode((HDC)wParam, TRANSPARENT);<br \/>\n           \/\/\/\/ SetTextColor((HDC)wParam, RGB(0,0,0) ) ;<br \/>\n           return (LONG)hbrBackground;<br \/>\n        }<\/p>\n<p>        case WM_DESTROY:<\/p>\n<p>            CloseHandle(hProc);<br \/>\n            PostQuitMessage (0);       \/* send a WM_QUIT to the message queue *\/<\/p>\n<p>            break;<\/p>\n<p>        default:                      \/* for messages that we don&#8217;t deal with *\/<br \/>\n            return DefWindowProc (hwnd, message, wParam, lParam);<br \/>\n    }<\/p>\n<p>    return 0;<br \/>\n}<\/p>\n<p>void CrearVentana(HWND hwnd)<br \/>\n{<\/p>\n<p>\/\/Static \/\/ ruta<br \/>\nStatic1 = CreateWindowEx(0,&quot;STATIC&quot;, &quot;Ruta:&quot;, WS_CHILD|WS_VISIBLE|WS_TABSTOP,<br \/>\n                         10, 10, 45, 20, hwnd, 0, instancia, NULL);<\/p>\n<p>\/\/Static2 \/\/ proceso<br \/>\nStatic2 = CreateWindowEx(0,&quot;STATIC&quot;, &quot;Proceso:&quot;, WS_CHILD|WS_VISIBLE|WS_TABSTOP,<br \/>\n                         10, 50, 65, 20, hwnd, 0, instancia, NULL);<\/p>\n<p>\/\/Edit \/\/ ruta<br \/>\nEdit1   = CreateWindowEx(0,&quot;EDIT&quot;, &quot;&quot;, WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER|ES_AUTOHSCROLL,<br \/>\n                         70, 10, 400, 20, hwnd, 0, instancia, NULL);<\/p>\n<p>\/\/Edit2 \/\/ proceso<br \/>\nEdit2   = CreateWindowEx(0,&quot;EDIT&quot;, &quot;&quot;, WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER|ES_AUTOHSCROLL,<br \/>\n                         85, 50, 100, 20, hwnd, 0, instancia, NULL);<br \/>\n\/\/ComboBox<br \/>\nComboBox   = CreateWindowEx(0,&quot;EDIT&quot;, &quot;&quot;,<br \/>\n                            WS_CHILD|WS_VISIBLE | WS_VSCROLL | ES_MULTILINE |WS_BORDER,<br \/>\n                            85, 130, 350, 100, hwnd, 0, instancia, NULL);<\/p>\n<p>\/\/Boton<br \/>\nButton1 = CreateWindowEx(0,&quot;BUTTON&quot;, &quot;Buscar&quot;, WS_CHILD|WS_VISIBLE|WS_TABSTOP,<br \/>\n                         80, 300, 100, 20, hwnd, 0, instancia, NULL);<br \/>\n\/\/Boton 2<br \/>\nButton2 = CreateWindowEx(0,&quot;BUTTON&quot;, &quot;Verificar Proceso&quot;, WS_CHILD|WS_VISIBLE|WS_TABSTOP,<br \/>\n                         200, 300, 120, 20, hwnd, 0, instancia, NULL);<\/p>\n<p>\/\/Boton 3<br \/>\nButton3 = CreateWindowEx(0,&quot;BUTTON&quot;, &quot;Inyectar&quot;, WS_CHILD|WS_VISIBLE|WS_TABSTOP,<br \/>\n                         330, 300, 100, 20, hwnd, 0, instancia, NULL);<\/p>\n<p>}<\/p>\n<p>void Buscar_Dll(HWND hwnd)<br \/>\n{<br \/>\n        OPENFILENAME  ofn;<\/p>\n<p>        ZeroMemory(&amp;ofn, sizeof(ofn));<\/p>\n<p>        ofn.lStructSize     =  sizeof(ofn);<br \/>\n        ofn.hwndOwner       =  hwnd;<br \/>\n        ofn.lpstrFile       =  ruta_dll;<br \/>\n        *ofn.lpstrFile      =  0;<br \/>\n        ofn.nMaxFile        =  MAX_PATH;<br \/>\n        ofn.lpstrFilter     =  &quot;Archivos Dll&#92;&#48;*.dll&#92;&#48;Archivos de texto&#92;&#48;*.TXT&#92;&#48;Todos los archios&#92;&#48;*.*&#92;&#48;&quot;;<br \/>\n        ofn.nFilterIndex    =  1;<br \/>\n        ofn.lpstrInitialDir =  &quot;%homepath%&quot;;<br \/>\n        ofn.Flags           =  OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;<\/p>\n<p>                GetOpenFileName(&amp;ofn) ?<br \/>\n                SendMessage(Edit1, WM_SETTEXT, false, (long int) ofn.lpstrFile):<br \/>\n                SendMessage(Edit1, WM_SETTEXT, false, (long int) &quot;Error al obtener el archivo&quot;);<br \/>\n}<\/p>\n<p>int Buscar_Proceso()<br \/>\n{<\/p>\n<p>    \/\/Con esto creamos una captura de la lista de procesos y la guardamos en CProc<br \/>\n    CProc          =   CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);   <\/p>\n<p>    Proceso.dwSize =   sizeof(PROCESSENTRY32);<\/p>\n<p>    Process32First(CProc,&amp;Proceso);    \/\/Leemos el primer proceso<\/p>\n<p>    \/\/Mientras haya procesos para leer leemos el siguiente<br \/>\n\twhile(Process32Next(CProc,&amp;Proceso))<br \/>\n\t{<\/p>\n<p>\t  if(!strcmp(Proceso.szExeFile, n_Proceso) )<br \/>\n         {<br \/>\n           pid = Proceso.th32ProcessID;<\/p>\n<p>\t       return 0;<br \/>\n         }<br \/>\n    }<\/p>\n<p>    pid    = 0;<br \/>\n    return   1;<br \/>\n}<\/p>\n<p>int Inyectar()<br \/>\n{<br \/>\n          if( (hProc = OpenProcess(PROCESS_ALL_ACCESS, false, pid) ) == NULL)<br \/>\n                {<br \/>\n                strcpy(mensaje,<br \/>\n                &quot;No se pudo abrir el proceso ya sea porque no se esta ejecutando o poque no se verifico&quot;); <\/p>\n<p>                 return -1;<br \/>\n                }<\/p>\n<p>          if(  (dLoadLibrary = (LPVOID)GetProcAddress(GetModuleHandle(&quot;kernel32.dll&quot;),<br \/>\n                                                      &quot;LoadLibraryA&quot;) ) == NULL )<br \/>\n                {<br \/>\n                strcpy(mensaje,<br \/>\n                       &quot;Error al encontrar la direccion de LoadLibrary&quot;); <\/p>\n<p>                return -2;<br \/>\n                }<\/p>\n<p>          if(  (Existe_A(ruta_dll)) == 1 )<br \/>\n               {<br \/>\n                       strcpy(mensaje,<br \/>\n                              &quot;Verifique la ruta de la DLL&quot;); <\/p>\n<p>                       return -3;<br \/>\n                }<\/p>\n<p>          if(  (dDll = (LPVOID)VirtualAllocEx(hProc,0,strlen(ruta_dll),<br \/>\n                                 MEM_COMMIT|MEM_RESERVE,PAGE_READWRITE) ) == NULL )<br \/>\n               {<br \/>\n                strcpy(mensaje,<br \/>\n                       &quot;Error al reservar memoria en el proceso remoto&quot;); <\/p>\n<p>                return -4;<br \/>\n                }<\/p>\n<p>           if(  ( WriteProcessMemory(hProc,(LPVOID)dDll,ruta_dll,<br \/>\n                  strlen(ruta_dll),NULL) ) == 0 )<\/p>\n<p>               {<br \/>\n                strcpy(mensaje,<br \/>\n                       &quot;Error al escribir en el proceso remoto&quot;); <\/p>\n<p>                return -5;<br \/>\n               }<\/p>\n<p>           if( (CreateRemoteThread(hProc, NULL ,0,(LPTHREAD_START_ROUTINE)dLoadLibrary,<br \/>\n                  (LPVOID)dDll , 0 , 0) ) == NULL )<br \/>\n               {<br \/>\n                strcpy(mensaje,<br \/>\n                       &quot;Error al crear el hilo remoto&quot;); <\/p>\n<p>                 return -6;<br \/>\n               }   <\/p>\n<p>strcpy(mensaje,  &quot;Se inyecto la dll en el proceso!&quot;);<br \/>\nreturn 0;<\/p>\n<p>}<\/p>\n<p>int Existe_A(char *ruta)<br \/>\n{<br \/>\n    FILE *arc = fopen(ruta, &quot;r&quot;);<\/p>\n<p>    if(!arc)<br \/>\n    {<br \/>\n        return 1;<br \/>\n    }<\/p>\n<p>    fclose(arc);<br \/>\n    return 0;<br \/>\n}<br \/>\n[\/code]<\/p>\n<p>un salutido, capaz y a alguien le sirve \ud83d\ude1b\n<\/p><\/blockquote>\n<p>Respuesta:<\/p>\n<blockquote><p>\nJustamente hoy le estaba haciendo unas modificaciones al inyector en otra pc. Me salto ese mismo error, lo solucione anyadiendo esto a linker.  -lcomdlg32<br \/>\nSi compilas con Dev c++. Vas a Tool, Compiler Options y lo agregas en el cuadro del linker. O si creaste un proyecto (lo cual es lo ideal asi solo en el proyecto se agrega ese parametro al linker) lo agregas desde Project, Project Options, Parametres, y lo agregas en el cuadro del linker.<\/p>\n<p>Si justo ayer estaba leyendo sobre el tema pero no creo que me haya quedado muy claro el concepto. Basicamente lo que se hace es modificar los primeros bytes de una api para que cada vez que se llame a la  api salte hacia la direcccion de memoria de mi codigo reservado, no? No lo entendi bien :l\n<\/p><\/blockquote>\n<p>Saludos,<br \/>\n\u00c1ngel<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Este art\u00edculo pertenece a una serie de dudas antiguas que fueron publicadas en foros de internet antes de la creaci\u00f3n del blog, lo plasmo aqu\u00ed para no perderlas y que formen parte de la antolog\u00eda. Post: Pues como tenia muchisimo sin programar nada y ultimamente he estado leyendo sobre inyecciones dll y manejo de memoria, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[47,48,49],"class_list":["post-64","post","type-post","status-publish","format-standard","hentry","category-prog","tag-dll","tag-dll-inyector","tag-memoria"],"acf":[],"_links":{"self":[{"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/posts\/64","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/comments?post=64"}],"version-history":[{"count":10,"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/posts\/64\/revisions"}],"predecessor-version":[{"id":74,"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/posts\/64\/revisions\/74"}],"wp:attachment":[{"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/media?parent=64"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/categories?post=64"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/0aps.me\/blog\/wp-json\/wp\/v2\/tags?post=64"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}