Esempio n. 1
0
DWORD WINAPI readPipeAndSendToSocketThreadLoop(LPVOID lpParam)
{
	SOCKET* ClientSocket = (SOCKET*)lpParam;

	char recvbuf[DEFAULT_BUFLEN];
	int recvbuflen = DEFAULT_BUFLEN;
	int bufSize = 0;
	int iSendResult;
	for (;;) {
		ZeroMemory(&recvbuf, recvbuflen);
		bufSize = readFromPipe(recvbuf);
		iSendResult = send(*ClientSocket, recvbuf, bufSize, 0);
		if (iSendResult == SOCKET_ERROR) {
			printf("send failed with error: %d\n", WSAGetLastError());
			if (isForceQuit) {
				return 0;
			}
			else {
				closeClientSocket();
				WSACleanup();
				return 1;
			}
		}
	}
	return 0;
}
serverState handshake(){

	fprintf(stderr , "-----------------------------------------------------------\n **** Waiting for handshake ****\n\n");	
	
	char buffer[MSG_MAX_SIZE];
	
	int length = readFromPipe(inputChannel ,(byte *) buffer);
				
	printMsg("Client to server ---> " , buffer , length);	
	
	if(strncmp(buffer , ClientOpenConnection , length) != 0 || length != strlen(ClientOpenConnection))
	{
		fprintf(stderr, "Handshake read error\n");
		return ERROR;
	}
		
	if(writeInPipe(outputChannel,(byte *) ServerOpenConnection , strlen(ServerOpenConnection)) < 0)
	{
		fprintf(stderr, "Handshake write error\n");
		return ERROR;
	}
	
	printMsg("Server to client ---> " , ServerOpenConnection , strlen(ServerOpenConnection));
	
	return HANDSHAKE;
}
void closeConnection(int inputChannel , int outputChannel){
	
	char msg[2048];
	
	fprintf(stderr,"Sending closing connection message : %s\n" , ClientCloseConnection);
	
	if(writeInPipe(outputChannel, (byte *) ClientCloseConnection , strlen(ClientCloseConnection)) < 0)
	{
		perror("Closing client error");
		return;	
	}
	
	fprintf(stderr , "message written , waiting for response\n");
	
	readFromPipe(inputChannel ,(byte *) msg);
	
	if(strncmp(msg , ServerCloseConnection , strlen(ServerCloseConnection)) != 0)
	{
		perror("Closing client error");
		return;
	}
	
	fprintf(stderr , "Connection closed\n\n");
	
	closeChannel(inputChannel);
	closeChannel(outputChannel);

}
int getJavaStartCommand(char *scriptFile) { 
	HANDLE hChildStdoutRd, hChildStdoutWr, hChildStdoutRdDup;
    SECURITY_ATTRIBUTES saAttr; 
    BOOL fSuccess; 
	
	//DebugBreak();
    // Set the bInheritHandle flag so pipe handles are inherited. 
    saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); 
    saAttr.bInheritHandle = TRUE; 
    saAttr.lpSecurityDescriptor = NULL; 
 
    // The steps for redirecting child process's STDOUT: 
    //     1. Create anonymous pipe to be STDOUT for child process. 
    //     2. Create a noninheritable duplicate of the read handle and
    //        close the inheritable read handle. 
    //     3. Set STDOUT for child process
 
    // Create a pipe to be used for the child process's STDOUT. 
     if (! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &saAttr, 0)) 
        errorExit("Stdout pipe creation failed"); 
 
    // Create noninheritable read handle and close the inheritable read 
    // handle. 
    fSuccess = DuplicateHandle(GetCurrentProcess(), hChildStdoutRd,
        GetCurrentProcess(), &hChildStdoutRdDup , 0, FALSE,
        DUPLICATE_SAME_ACCESS);
	if(!fSuccess) {
		PrintEvent(_T("DuplicateHandle failed"));
		errorExit("DuplicateHandle failed");
	}
    CloseHandle(hChildStdoutRd);

	//
	// Now create the child process. 
    fSuccess = createChildProcess(scriptFile, hChildStdoutWr);

	if (!fSuccess) {
		PrintEvent(_T("Could not create process!!"));
		errorExit("Create process failed"); 
	}

	//PrintEvent(_T("Created Child Process Successfully"));

	// Close the write end of the pipe before reading from the 
    // read end of the pipe. 
    if (!CloseHandle(hChildStdoutWr)) 
        errorExit("Closing handle failed"); 

    // Read from pipe that is the standard output for child process. 
    readFromPipe(hChildStdoutRdDup); 

    return 0;
} 
int askConnection(int inputChannel, int outputChannel){
	
	char msg[2048];
	
	fprintf(stderr,"Asking for connection\n");
	
	if(writeInPipe(outputChannel, (byte *) ClientOpenConnection , strlen(ClientOpenConnection)) < 0)
	{
		perror("handshake client error");
		return -1;	
	}

	readFromPipe(inputChannel ,(byte *) msg);
	
	if(strncmp(msg , ServerOpenConnection , strlen(ServerOpenConnection)) != 0)
	{
		perror("handshake client error");
		return -1;
	}
		
	return 1;
}
Esempio n. 6
0
void Interface::test() {
	std::cout << "Testing Interface Class START!..." << std::endl;
	std::cout << "TData Path: " << dataPath << std::endl;
	std::cout << "Fifo IN Path: " << pathFifoIn << std::endl;
	std::cout << "Fifo OUT Path: " << pathFifoOut << std::endl;

	std::cout << "Max Number of Frames: " << maxNumFrame << " Max Number of Actions: " << numAction << std::endl;
	for(int i = 0; i < numAction; ++i) {
		std::cout << "Index: " << i << " Action: " << ind2Act[i] << std::endl;
		std::cout << "Action: " << ind2Act[i] << " Index: " << act2Ind[ind2Act[i]] << std::endl;
	}

	std::cout << "Reset Button:Interface:: " << resetButton << std::endl;
	std::cout << "Num frame stack: " << numFrmStack << std::endl;
	std::cout << "crop Height: " << cropH << std::endl;
	std::cout << "crop Width: " << cropW << std::endl;
	std::cout << "crop Left: " << cropL << std::endl;
	std::cout << "crop Top: " << cropT << std::endl;

	std::cout << "GEN frame info Path: " << frmInfo << std::endl;
	std::cout << "GEN Episode info Path: " << EpInfo << std::endl;
	std::cout << "Opening and Initializing pipe: " << std::endl;
	openPipe();
	initInPipe();
	initOutPipe();
	std::cout << "Writing Random actions to InPipe and reading from OutPipe with data storage..." << std::endl;
	while(!isToEnd()) {
		resetVals(0);
		int x = rand()%numAction;
		writeInPipe(toString(ind2Act[x]));
		readFromPipe();
		saveFrameInfo();
		saveEpisodeInfo();
	}
	finalizePipe();
	std::cout << "Testing Interface Class END!..." << std::endl;
}
int receive_and_decrypt(byte * msg){

	int length = readFromPipe(inputChannel , msg); 

	if(length < 0)
	{
		fprintf(stderr , " **** error reading message **** \n\n");
		return -1;
	}	

	if(strncmp(msg , ClientCloseConnection , length) == 0 && length == strlen(ClientCloseConnection))
		return length;
	
	if(encType == PLAIN)
		return length;

	if(encType == RSA64){
		BIGNUM *message = BN_new();	
		message = BN_bin2bn((const unsigned char *) msg, RSA64_BYTE_LENGTH , NULL);
		
		printf("%s\n", BN_bn2hex(message));
		
		rsaEXP(message , &server64Rsa);	//Decrypt with private keyExchange
		
		BN_bn2bin(message , msg);

		BN_free(message);		
		return length;		
	}
	
	if(encType == RSA512){
		BIGNUM *message = BN_new();	
		message = BN_bin2bn((const unsigned char *) msg, RSA512_BYTE_LENGTH , NULL);
		
		printf("%s\n", BN_bn2hex(message));
		
		rsaEXP(message , &server512Rsa);	//Decrypt with private keyExchange

		BN_bn2bin(message , msg);

		BN_free(message);		
		return length;		
	}
	
	if(encType == Cipher_ALL5){
		BIGNUM *tm = BN_new();	
		tm = BN_bin2bn((const unsigned char *) msg, length , NULL);
		printf("ALL5 : %s\n", BN_bn2hex(tm));

		byte message[length - HASH_BYTE_LENGTH];	
		byte hash[HASH_BYTE_LENGTH];

		int recv_length = length;
		
		if(cipherSpec.hash_function == hash_spongeBunny)
		{
		recv_length -= HASH_BYTE_LENGTH;	
		memmove(hash , msg + (sizeof(byte) * recv_length) , sizeof(byte) * HASH_BYTE_LENGTH);	//copy the hash
		memcpy(message , msg , sizeof(byte) * recv_length);	//copy the cihpertext				
		
		ALL5_decrypt(&cipherStruct.all5, message, message, recv_length);	//decrypt
		
		byte rec_hash[HASH_BYTE_LENGTH];
		spongeBunnyComputeHash(message , rec_hash , recv_length);	//compute the hash of the plaintext
		
		if(memcmp(rec_hash, hash, sizeof(byte) * HASH_BYTE_LENGTH) != 0)
		{
			recv_length = 0;
			fprintf(stderr , "Wrong HASH !!!!!!! \n");
		}
		
		tm = BN_bin2bn((const unsigned char *) hash, HASH_BYTE_LENGTH , NULL);
		printf("HASH : %s\n", BN_bn2hex(tm));
		memcpy(msg , message , sizeof(byte) * recv_length);
		
			
		}	//no hash function
		else
			ALL5_decrypt(&cipherStruct.all5, msg, msg, recv_length);	//decrypt	
		
		BN_free(tm);		
		return recv_length;
	}
	
	if(encType == Cipher_MAJ5){
		BIGNUM *tm = BN_new();	
		tm = BN_bin2bn((const unsigned char *) msg, length , NULL);
		printf("MAJ5 : %s\n", BN_bn2hex(tm));
		
		int recv_length = length;
		
		if(cipherSpec.hash_function == hash_spongeBunny)		
		{
		byte message[length - HASH_BYTE_LENGTH];	
		byte hash[HASH_BYTE_LENGTH];
		
		recv_length -= HASH_BYTE_LENGTH;	
		memmove(hash , msg + (sizeof(byte) * recv_length) , sizeof(byte) * HASH_BYTE_LENGTH);	//copy the hash
		memcpy(message , msg , sizeof(byte) * recv_length);	//copy the cihpertext				
		
		MAJ5_decrypt(&cipherStruct.maj5, message, message, recv_length);	//decrypt
		
		byte rec_hash[HASH_BYTE_LENGTH];
		spongeBunnyComputeHash(message , rec_hash , recv_length);	//compute the hash of the plaintext
		
		if(memcmp(rec_hash, hash, sizeof(byte) * HASH_BYTE_LENGTH) != 0)
		{
			recv_length = 0;
			fprintf(stderr , "Wrong HASH !!!!!!! \n");
		}
		
		tm = BN_bin2bn((const unsigned char *) hash, HASH_BYTE_LENGTH , NULL);
		printf("HASH : %s\n", BN_bn2hex(tm));
		memcpy(msg , message , sizeof(byte) * recv_length);
		
		}	//no hash function
		else
			MAJ5_decrypt(&cipherStruct.maj5, msg, msg, recv_length);	//decrypt	
		
		BN_free(tm);		
		return recv_length;
		
	}
	
	if(encType == Cipher_Bunny24){
		
		BIGNUM *tm = BN_new();	
		tm = BN_bin2bn((const unsigned char *) msg, length , NULL);
		printf("BUNNY24 : %s \n", BN_bn2hex(tm));
		
		int recv_length = length - HASH_BYTE_LENGTH;
		
		byte hash[HASH_BYTE_LENGTH];	
		byte mess[recv_length];
		
		memmove(hash , msg + (sizeof(byte) * recv_length) , sizeof(byte) * HASH_BYTE_LENGTH);	//copy the hash					
		memcpy(mess , msg , sizeof(byte) * recv_length);
		
		int message_bit_length = recv_length * 8;
		
		bit  plain_bit_text[message_bit_length];			//plaintext in  bits
		bit  crypt_bit_text[message_bit_length];			//ciphertext in bits
		bit  plain_byte_text[recv_length];
		
		memset(plain_byte_text , 0 , sizeof(byte) * recv_length);

		int i;

		for(i = 0; i < message_bit_length; i++)
			crypt_bit_text[i] = (msg[i / 8] & (1 << i % 8)) ? 1 : 0;		//to bit
			
		bunny24CBC_decrypt(plain_bit_text, crypt_bit_text , init_vector , cipherStruct.key , message_bit_length); // encrypt

		for(i = 0; i < message_bit_length; i++)
			plain_byte_text[i/8] |= (plain_bit_text[i] << (i % 8));		//to byte
			
		strcpy(msg ,plain_byte_text);
		msg[strlen(msg) + 1] = '\0';

		byte rec_hash[HASH_BYTE_LENGTH];
		memset(rec_hash , 0 , sizeof(byte) * HASH_BYTE_LENGTH);
		spongeBunnyComputeHash(msg , rec_hash , strlen(msg) + 1);	//compute the hash of the ciphertext
		
		if(memcmp(rec_hash, hash, sizeof(byte) * HASH_BYTE_LENGTH) != 0)
			fprintf(stderr , "Wrong HASH !!!!!!! \n");	
		
		tm = BN_bin2bn((const unsigned char *) rec_hash , HASH_BYTE_LENGTH , NULL);
		printf("\nHASH : %s\n", BN_bn2hex(tm));

		BN_free(tm);	
		
		return strlen(msg) + 1;
	}
	
}
Esempio n. 8
0
int pintoolInit()
{ 
    int returnValue = INIT_ERROR;

    // option du pintool('taint' ou 'checkscore')    
    g_option = KOption.Value();
    
    /**** OPTION TAINT ***/
    if ("taint" == g_option)
    {
        returnValue = OPTION_TAINT;

        // instanciation des classes globales : marquage mémoire et formule SMT2
        pTmgrGlobal   = new TaintManager_Global;
        g_pFormula    = new TranslateIR;
        if (!pTmgrGlobal || !g_pFormula)  return (INIT_ERROR);

        /*** RECUPERATION DES ARGUMENTS DE LA LIGNE DE COMMANDE ***/
        // 1) si pipe => ouverture, sinon récupération de l'option 'input'
        g_nopipe = KNoPipe.Value();
        if (!g_nopipe)
        {
            // erreur si pipe ne peut pas être ouvert
            if (EXIT_FAILURE == openPipe()) return (INIT_ERROR);
            // récupération de l'entrée étudiée via le pipe
            g_inputFile = readFromPipe();
            if (g_inputFile.empty()) return (INIT_ERROR);
        }
        else
        {
            // si pas de pipe, nom de l'entrée passée par ligne de commande
            g_inputFile = KInputFile.Value();    
            // l'écriture des resultats (formule SMT2) se fera dans un fichier
            // donc récupérer le handle du fichier qui sera utilisé
            std::string formulaFile(g_inputFile + "_formula.smt2");
            g_hPipe = WINDOWS::CreateFile(
                formulaFile.c_str(), // nom du fichier 
                GENERIC_WRITE, // acces en ecriture
                0,             // pas de partage 
                nullptr,       // attributs de sécurité par défaut
                CREATE_ALWAYS, // écrasement du précédent fichier, si existant
                0,             // attributs par défaut
                nullptr);	   // pas de modèle

            if ((HANDLE)(WINDOWS::LONG_PTR) (-1) == g_hPipe)  return (INIT_ERROR);
        }

        // 2) mode verbeux : création des fichiers de log
        g_verbose = KVerbose.Value();
        if (g_verbose)
        {
            // création et ouverture du fichier de log dessasemblage
            std::string logfile(g_inputFile + "_asm.log");
            g_debug.open(logfile); 

            // création et ouverture du fichier de log de marquage
            std::string taintfile(g_inputFile + "_taint.log");
            g_taint.open(taintfile);
            if (!g_taint.good() || !g_debug.good()) return (INIT_ERROR);

            // stockage de l'heure du top départ pour statistiques
            g_timeBegin = clock();
        }

        // 4) intervalles d'octets source à marquer, si option présente
        if (!KBytes.Value().empty())  pTmgrGlobal->setBytesToTaint(KBytes.Value());

        // 5) nombre maximal de contraintes ((0 si aucune)
        g_maxConstraints = KMaxConstr.Value();
        
        // 6) type d'OS hote (déterminé par le programme appelant)
        g_osType = static_cast<OSTYPE>(KOsType.Value());
        // détermination des numéros de syscalls à monitorer (dépend de l'OS)
        if (HOST_UNKNOWN == g_osType) return (INIT_ERROR);
        else SYSCALLS::defineSyscallsNumbers(g_osType);
            
        // initialisation de variable globale indiquant le départ de l'instrumentation
        // est mise à vrai par la partie syscalls lorsque les premières données
        // marquées sont créées (= lecture dans l'entrée)
        g_beginInstrumentationOfInstructions = false;

        // création des clefs pour les TLS, pas de fonction de destruction
        g_tlsKeyTaint       = PIN_CreateThreadDataKey(nullptr);
        g_tlsKeySyscallData = PIN_CreateThreadDataKey(nullptr);
    }
    else if ("checkscore" == g_option) // option....checkscore :)   
    {
        // erreur si pipe ne peut pas être ouvert
        if (EXIT_FAILURE == openPipe()) return (INIT_ERROR);
        returnValue = OPTION_CHECKSCORE;
    }
    else return (INIT_ERROR); // option inconnue : erreur

    /**** DERNIERES INITIALISATIONS COMMUNES AUX DEUX OPTIONS **/

    // Initialisation des verrous pour le multithreading
    PIN_InitLock(&g_lock);
  
    // temps maximal d'exécution (valable en 'taint' et en 'checkscore')
    g_maxTime = KMaxTime.Value();
    // si non nul, création d'un thread interne au pintool : 
    // sert à la surveillance du temps maximal d'execution 
    if (g_maxTime)
    {
        THREADID tid = PIN_SpawnInternalThread(maxTimeThread, nullptr, 0, nullptr);
        if (INVALID_THREADID == tid)   return (INIT_ERROR);  
    }

    return (returnValue); // option choisie (taint ou checkScore), ou erreur d'init
} // pintoolInit()
Esempio n. 9
0
int main() {
  int inputPipe;
  char buffer[BUFFER_LEN];
  char mktemp_filename[PATH_MAX];
  char mktemp_dir[PATH_MAX];
  int ret;
  int terminalPid;
  TerminalList * termlist = lst_new();
  pthread_t threadMonitor;
  char *args[N_ARGS];
  if (signal(SIGINT, handleSIGINT)) {
    fprintf(stderr, "Could not set sigint handler!\n");
    exit(EXIT_FAILURE);
  }
  if (pthread_mutex_init(&mutexRunningProcesses, NULL)) {
    fprintf(stderr, "Could not create runningProcesses mutex\n");
    exit(EXIT_FAILURE);
  }
  if (pthread_cond_init(&condRunningProcesses, NULL)) {
    fprintf(stderr, "Could not create runningProcesses cond\n");
    exit(EXIT_FAILURE);
  }
  if (pthread_cond_init(&condFreeSlots, NULL)) {
    fprintf(stderr, "Could not create FreeSlots cond\n");
    exit(EXIT_FAILURE);
  }

  strcpy(mktemp_dir, MKTEMP_TEMPLATE);
  TESTTRUE(mkdtemp(mktemp_dir)!=NULL, "Erro na criação do diretorio temporário (" _AT_ ")\n");
  strncpy(mktemp_filename, mktemp_dir, PATH_MAX);
  strncpy(mktemp_filename+strlen(mktemp_filename), "/" INPUT_FILE, PATH_MAX-strlen(mktemp_filename));
  fprintf(stdin, "Ficheiro de input: '%s'\n", mktemp_filename);
  if (mkfifo(mktemp_filename, 0660) <0) {
    fprintf(stderr, "Could not create fifo %s\n", mktemp_filename);
    exit(EXIT_FAILURE);
  }
  printf("A abrir o pipe %s para leitura...\n", mktemp_filename);
  if ((inputPipe = open(mktemp_filename, O_RDONLY)) < 0) {
    fprintf(stderr, "Could not create fifo " INPUT_FILE "\n");
    exit(EXIT_FAILURE);
  }
  printf("A abrir o pipe %s para escrita...\n", mktemp_filename);
  if ((outPipe = open(mktemp_filename, O_WRONLY|O_NONBLOCK)) < 0) {
    fprintf(stderr, "Erro ao abrir o ficheiro de output" INPUT_FILE "\n");
    exit(EXIT_FAILURE);
  }
  initProcessList();
  if(pthread_create(&threadMonitor, 0,processMonitor, NULL)!= 0) {
    printf("Erro na criação da tarefa\n");
    exit(EXIT_FAILURE);
  }

  while(1) {
    if (exitCalled) break;
    if (readFromPipe(inputPipe, buffer, &terminalPid, termlist)!=0) continue;
    printf("Comando: %s\n", buffer);
    ret = readLineArguments(args, N_ARGS, buffer, BUFFER_LEN);
    if (!ret) continue;
    processesWaitingToRun++;
    newProcess(args, terminalPid);
  }

  //Mata todos os processos de terminal
  lst_destroy(termlist);

  C_SIGNAL(&condRunningProcesses);

  pthread_join(threadMonitor, NULL);



  //The following function is called after all threads have joined, therefore there aren't used any mutexes
  exitParShell();
  endProcessList();

  pthread_mutex_destroy(&mutexRunningProcesses);
  pthread_cond_destroy(&condRunningProcesses);
  pthread_cond_destroy(&condFreeSlots);
  close(inputPipe); //aqui nao faz sentido testar o return destas funcoes
  close(outPipe); //aqui nao faz sentido testar o return destas funcoes
  unlink(INPUT_FILE); //aqui nao faz sentido testar o return destas funcoes

  return EXIT_SUCCESS;
}