示例#1
2
文件: client-mqqtsn.c 项目: hyxer/osx
int main(int count, char *strings[])
{   
    FILE * fp;   
    clock_t begin, end;
    double time_spent;

    SSL_CTX *ctx;
    int server,i=0;
    SSL *ssl;
    char buf[1024];
    int bytes;
    char *hostname, *portnum;

while (i<86400) 
{
    begin = clock(); //start time measurement - harith
    
    if ( count != 3 )
    {
        printf("usage: %s <hostname> <portnum>\n", strings[0]);
        exit(0);
    }
    SSL_library_init();
    hostname=strings[1];
    portnum=strings[2];
 
    ctx = InitCTX();
    server = OpenConnection(hostname, atoi(portnum));
    ssl = SSL_new(ctx);      /* create new SSL connection state */
    SSL_set_fd(ssl, server);    /* attach the socket descriptor */
    if ( SSL_connect(ssl) == FAIL )   /* perform the connection */
        ERR_print_errors_fp(stderr);
    else
    {   char *msg = "Hello???";
 
        printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
        ShowCerts(ssl);        /* get any certs */
        SSL_write(ssl, msg, strlen(msg));   /* encrypt & send message */
        bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */
        buf[bytes] = 0;
        printf("Received: \"%s\"\n\n", buf);
        SSL_free(ssl);        /* release connection state */
    }
    close(server);         /* close socket */
    SSL_CTX_free(ctx);        /* release context */
    
    end = clock(); // stop time measurement -- harith
    time_spent = (double)(end - begin) / CLOCKS_PER_SEC * 1000;
      //printf("Total execution time is: %f \n", time_spent);
      //reset time
      	begin = 0;
	end   = 0; 
      
	fp = fopen( "logfile.txt", "a" ); // Open file for writing

    fprintf(fp, "Sequence %d, Time taken: %f ms \r\n",i,time_spent);

    fclose(fp);
    i++;
    sleep(1);
}
    return 0;
}
示例#2
0
int      kn_sock_sslconnect(//engine_t e,
		                  handle_t h,
		                  kn_sockaddr *remote,
		                  kn_sockaddr *local){
	if(h->type != KN_SOCKET && ((kn_socket*)h)->type != SOCK_STREAM)
		return 0;
	kn_socket *s = (kn_socket*)h;
	if(h->status != SOCKET_NONE) return -1;
	//if(s->e) return -1;
	SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method());
	if (ctx == NULL) {
	    ERR_print_errors_fp(stdout);
	    return -1;
	}
    	((kn_stream_socket*)s)->ctx = ctx;		
	s->addr_remote = *remote;
	int ret = stream_socket_connect((kn_stream_socket*)s,local,remote);
	if(ret == 1){
		((kn_stream_socket*)s)->ssl = SSL_new(ctx);
		SSL_set_fd(((kn_stream_socket*)s)->ssl,h->fd);
		if (SSL_connect(((kn_stream_socket*)s)->ssl) == -1){
		        ERR_print_errors_fp(stderr);
		        ret = -1;
		}
		else {
		        kn_set_noblock(h->fd,0);
		        h->status = SOCKET_ESTABLISH;
		        printf("Connected with %s encryption/n", SSL_get_cipher(((kn_stream_socket*)s)->ssl));
		        ShowCerts(((kn_stream_socket*)s)->ssl);
		}		
	}else{
		ret = -1;
	}	
	return ret;	
}
示例#3
0
int encrypt_connect_server()
{
    //return -1;
    /* SSL initialization*/
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    SSL_load_error_strings();
    ctx = SSL_CTX_new(TLSv1_client_method());
    if (ctx == NULL)
    {
        ERR_print_errors_fp(stdout);
        exit(1);
    }
    /* creat a new SSL based on ctx */
    ssl = SSL_new(ctx);
    // connect ssl to TCP SOCKET
    SSL_set_fd(ssl, sockfd);
    /* create ssl connection */
    if (SSL_connect(ssl) == -1 || strcmp("(NONE)",SSL_get_cipher(ssl)) == 0)
    {
        ERR_print_errors_fp(stderr);
        return -1;
    }
    DEBUG_printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
    ShowCerts(ssl);
    return 1;
}
示例#4
0
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{   char buf[1024];
    char reply[1024];
    int sd, bytes;
    const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";
 
    if ( SSL_accept(ssl) == FAIL )     /* do SSL-protocol accept */
        ERR_print_errors_fp(stderr);
    else
    {
        ShowCerts(ssl);        /* get any certificates */
        bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
        if ( bytes > 0 )
        {
            buf[bytes] = 0;
            printf("Client msg: \"%s\"\n", buf);
            sprintf(reply, HTMLecho, buf);   /* construct reply */
            SSL_write(ssl, reply, strlen(reply)); /* send reply */
        }
        else
            ERR_print_errors_fp(stderr);
    }
    sd = SSL_get_fd(ssl);       /* get socket connection */
    SSL_free(ssl);         /* release SSL state */
    close(sd);          /* close connection */
}
int initialize_secure_connection(int fd)
{
	ssds_log(logDEBUG, "Init SSL\n");
	sleep(5);
	ctx = InitCTX();
	if (ctx == NULL)
	{
		return -1;
	}

	//server loads certificate and key
	#ifdef __CASE_SERVER
	ssds_log(logDEBUG, "Server is loading certificates\n");
	if (LoadCertificates(ctx, MY_CERT, MY_KEY) == -1)
	{
		ssds_log(logERROR, "SSL fail (server load certs)\n");
		if (PRINT_SSL_ERRORS_TO_STDERR) ERR_print_errors_fp(stderr);
		return -1;
	}
	else
	{
		ssds_log(logMESSAGE, "SSL certificates successfully loaded\n");
	}
	#endif

	ssl = SSL_new(ctx);
	SSL_set_fd(ssl, fd);

	//client connects to server
	#ifdef __CASE_CLIENT
	if (SSL_connect(ssl) == -1)
	{
		ssds_log(logERROR, "SSL fail (client connect)\n");
		if (PRINT_SSL_ERRORS_TO_STDERR) ERR_print_errors_fp(stderr);
		return -1;
	}
	#endif

	//server accepts client
	#ifdef __CASE_SERVER
	if (SSL_accept(ssl) == -1)
	{
		ssds_log(logERROR, "SSL fail (server accept)\n");
		if (PRINT_SSL_ERRORS_TO_STDERR) ERR_print_errors_fp(stderr);
		return -1;
	}
	#endif

	if (ShowCerts(ssl) == -1)
	{
		ssds_log(logERROR, "SSL fail (no peer certificates avalaible)\n");
		if (PRINT_SSL_ERRORS_TO_STDERR) ERR_print_errors_fp(stderr);
		return -1;
	}
	return 0;
}
// Serve the connection
void handle_client(int client, SSL_CTX *ctx) {
    char *request = NULL;
    size_t len;
    char *response = "HTTP/1.0 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n";
    SSL *ssl;

    ssl = SSL_new(ctx); //get new SSL state with context
    SSL_set_fd(ssl, client); //set connection socket to SSL state

    // do SSL-protocol accept
    if (SSL_accept(ssl) == FAIL) {
        ERR_print_errors_fp(stderr);
        SSL_free(ssl);
        return;
    }
    
    ShowCerts(ssl); // get any certificates
    
    do {
        if (request) {
            free(request);
            request = NULL;
        }
    
        request = sslRead(ssl); // get request
        len = strlen(request);
        
        if (len > 0) {
#ifdef _WIN32
            printf("Echo(%u): %s\n", len, request);
#else
            printf("Echo(%zu): %s\n", len, request);
#endif
            
            printf("send\n");
            SSL_write(ssl, response, strlen(response)); // send request back
        }
        else {
            ERR_print_errors_fp(stderr);
            break;
        }
    }
    while (strlen(request) > 0);
    
    if (request) {
        free(request);
        request = NULL;
    }

    SSL_free(ssl); //release SSL state
}
示例#7
0
void init_clinet_ssl(int server)
{
    SSL_library_init();
    ctx = InitCTX();
    ssl = SSL_new(ctx);      /* create new SSL connection state */
    SSL_set_fd(ssl, server);    /* attach the socket descriptor */
    if ( SSL_connect(ssl) == FAIL )   /* perform the connection */
        ERR_print_errors_fp(stderr);
    else {
        printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
        ShowCerts(ssl);        /* get any certs */
    }

}
示例#8
0
文件: client.c 项目: 1075482900/FTOT
//~~~~~~~~~~~~~~~~~~~~~connect to server~~~~~~~~~~~~~~~~~~~
//成功返回1,失败返回0并且退出
int connectto(int argc,char *args[]) 
{
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~判断输入IP是否正确~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	int i,count=0;
	if(argc!=2)
		{
			printf("format error: you mast enter ipaddr like this : client 192.168.0.6\n");
			exit(0);
		}
	for(i=0;*(args[1]+i)!='\0';i++)
		{
			if(*(args[1]+i)=='.')
				count++;
		}
	if(count!=3)
		{
			printf("IP format error\n");
			exit(0);
		}
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	
	if((sockclient=socket(AF_INET,SOCK_STREAM,0))==-1)
		{
			perror("socket");	
			exit(0);
		}
	memset(&sockaddr1,0,sizeof(sockaddr1));
	sockaddr1.sin_family = AF_INET;
	sockaddr1.sin_addr.s_addr = inet_addr(args[1]);
	sockaddr1.sin_port = htons(port);
	
	if(connect(sockclient,(struct sockaddr* )&sockaddr1,sizeof(sockaddr1))==-1)
		{
			perror("connect");
			exit(0);
		}
		//-----------------------------------------------------------------------
	/* 基于 ctx 产生一个新的 SSL */
  ssl = SSL_new(ctx);
  SSL_set_fd(ssl, sockclient);
  /* 建立 SSL 连接 */
  if (SSL_connect(ssl) == -1)
    ERR_print_errors_fp(stderr);
  else
  {
    printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
    ShowCerts(ssl);
  }
	return 1;
}
示例#9
0
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{   char buf[1024];
	char out[1024];
    char reply[1024];
    int firstFlag=1;
    char firstLine[1024];
    int sd, bytes;
    int readBytes;
    char *ptr;
    int file;
    const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";

    if ( SSL_accept(ssl) == FAIL ){     /* do SSL-protocol accept */
    	ERR_print_errors_fp(stderr);
    }

    else
    {
        ShowCerts(ssl);        /* get any certificates */

    	SSL_read(ssl, buf, sizeof(buf));

    	// Para el get

    	ptr = strtok(buf, "/");
    	ptr = strtok(NULL, " ");
    		fprintf(stdout,"%s\n",ptr);

   

    	//Enviar el archivo
    	file = open(ptr, O_RDONLY);
    	
    	//Si el archivo no esta
    	if(file == -1){
    		strcpy(reply, "<html><head><title>404 NOT FOUND</title></head><body>El archivo especificado no esta</body></html>");
    		SSL_write(ssl, reply,strlen(reply));
    	}

    	else{
    		while((readBytes = read(file,buf, 255)) > 0){
    			SSL_write(ssl, buf, readBytes);
    		}
    	}
    }
    sd = SSL_get_fd(ssl);       /* get socket connection */
    SSL_free(ssl);         /* release SSL state */
    close(sd);          /* close connection */
}
示例#10
0
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{
    char buf[1024];
    char reply[1024];
    char reply2[33000];
    reply[0] = '\0';
    int sd, bytes;
 
    if ( SSL_accept(ssl) == FAIL )     /* do SSL-protocol accept */
        ERR_print_errors_fp(stderr);
    else
    {
        ShowCerts(ssl);        /* get any certificates */
        bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
        if ( bytes > 0 )
        {
            /*separate buf into parts: 
                first char: action (which function to be performed)
                remaining chars: input for function*/
            buf[bytes] = 0;
            char action = buf[0];
            memmove(buf, buf+1, strlen(buf));
            printf("Received message from Client: %s\n", buf);
            if(action == '0'){
                printf("action: create %s eCents\n", buf);
                int ecentnum = atoi(buf);
                strcpy(reply2, createeCents(ecentnum));
                printf("response: %s\n", reply2);
                SSL_write(ssl, reply2, ecentnum*33);
            }
            else {
                printf("verify eCent: %s\n", buf);
                char* ecent = malloc(32);
                strcpy(ecent, buf);
                strcpy(reply, verifyeCent(ecent));
                SSL_write(ssl, reply, strlen(reply));
                printf("response: %s\n", reply);
            }
	   
        }
        else
            ERR_print_errors_fp(stderr);
    }
    sd = SSL_get_fd(ssl);
    SSL_free(ssl);
    close(sd);
}
int main(int count, char *strings[])
{   SSL_CTX *ctx;
    int server;
    SSL *ssl;
    char buf[1024];
    int bytes;
    char *hostname, *portnum;
    char msg[1024];
 
    if ( count != 3 )
    {
        printf("usage: %s <hostname> <portnum>\n", strings[0]);
        exit(0);
    }
    printf("HELLO!!\n");
    SSL_library_init();
    hostname=strings[1];
    portnum=strings[2];
    printf("HELLO!!\n");
    ctx = InitCTX();
    server = OpenConnection(hostname, atoi(portnum));
    ssl = SSL_new(ctx);      /* create new SSL connection state */
    SSL_set_fd(ssl, server);    /* attach the socket descriptor */
    printf("HELLO!!\n");
    if ( SSL_connect(ssl) == FAIL )   /* perform the connection */
        ERR_print_errors_fp(stderr);
    else
    {   printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
        ShowCerts(ssl); 
        while(1){
        printf("Client:");
        fgets(msg,sizeof(msg),stdin);
               /* get any certs */
        SSL_write(ssl, msg, strlen(msg));   /* encrypt & send message */
        bytes = SSL_read(ssl, buf, sizeof(buf)-1); /* get reply & decrypt */
        buf[bytes] = 0;
        printf("SERVER:%s", buf);
		}
        SSL_free(ssl);        /* release connection state */
    }
    close(server);         /* close socket */
    SSL_CTX_free(ctx);        /* release context */
    return 0;
}
示例#12
0
int main(int count, char *strings[])
{
	SSL_CTX *ctx;
	int server;
	SSL *ssl;
	char buf[1024];
	int bytes;
	char *hostname, *portnum;
	if (count != 3)
	{
		printf("usage: %s <hostname> <portnum>\n", strings[0]);
		exit(0);
	}
	SSL_library_init();
	hostname = strings[1];
	portnum = strings[2];
	ctx = InitCTX();
	server = OpenConnection(hostname, atoi(portnum));
	ssl = SSL_new(ctx); /* create new SSL connection state */
	SSL_set_fd(ssl, server); /* attach the socket descriptor */
	if (SSL_connect(ssl) == FAIL) /* perform the connection */
	{
		printf("Eroor: %s\n", stderr);
		ERR_print_errors_fp(stderr);
	}
	else
	{
		char *msg = "HelloWorld";
		printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
		ShowCerts(ssl); /* get any certs */
		SSL_write(ssl, msg, strlen(msg)); /* encrypt & send message */
		bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */
		buf[bytes] = '\0';
		printf("Received %d : %s \n", strlen(buf), buf);
		SSL_free(ssl); /* release connection state */
	}
	close(server); /* close socket */
	SSL_CTX_free(ctx); /* release context */
	return 0;
}
void PeerConnectionListener::Servlet(SSL* ssl) /* Serve the connection -- threadable */{
    char buf[1024];
    int sd, bytes;
    if ( SSL_accept(ssl) == -1 )     /* do SSL-protocol accept */
        ERR_print_errors_fp(stderr);
    else{
        ShowCerts(ssl);        /* get any certificates */
        bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
        if ( bytes > 0 ){
            buf[bytes] = 0;
            printf("Client msg: \"%s\"\n", buf);
            std::string inputString(buf);
            qDebug() << "Received message" << inputString.c_str();
            cont->handleNewMessage(inputString);
        }
        else
            ERR_print_errors_fp(stderr);
    }
    sd = SSL_get_fd(ssl);       /* get socket connection */
    SSL_free(ssl);         /* release SSL state */
    close(sd);          /* close connection */
}
示例#14
0
文件: ssl.c 项目: bbidulock/dockapps
int
InitSSL( int sock_fd )
{
  ssl_infos.ctx = InitCTX();
  ssl_infos.ssl = SSL_new( ssl_infos.ctx ); /* create new SSL connection state */
  if( ssl_infos.ssl == NULL ) {
    printf( "%s: Error in SSL_new()\n", PACKAGE );
    return EXIT_FAILURE;
  }

  SSL_set_fd( ssl_infos.ssl, sock_fd ); /* attach the socket descriptor */
  if( SSL_connect( ssl_infos.ssl ) == FAIL ) { /* perform the connection */
    ERR_print_errors_fp(stderr);
    return EXIT_FAILURE;
  }

  if( wmnotify_infos.debug ) {
    printf("Connected with %s encryption\n", SSL_get_cipher( ssl_infos.ssl ));
    ShowCerts( ssl_infos.ssl ); /* get any certs */
  }

  return EXIT_SUCCESS;
}
示例#15
0
int main()
{   SSL_CTX *ctx;
    int server;
    SSL *ssl;
    char buf[1024];
    int bytes;
	
    char hostname[]="127.0.0.1";
    char portnum[]="5000";
	
    char CertFile[] = "key/certificate.crt";
    char KeyFile[] = "key/private_key.pem";

    SSL_library_init();

    ctx = InitCTX();
    LoadCertificates(ctx, CertFile, KeyFile, "12345678");
    server = OpenConnection(hostname, atoi(portnum));
    ssl = SSL_new(ctx);      /* create new SSL connection state */
    SSL_set_fd(ssl, server);    /* attach the socket descriptor */
    if ( SSL_connect(ssl) == FAIL )   /* perform the connection */
        ERR_print_errors_fp(stderr);
    else
    {   char *msg = "Hello???";

        printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
        ShowCerts(ssl);        /* get any certs */
        SSL_write(ssl, msg, strlen(msg));   /* encrypt & send message */
        bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */
        buf[bytes] = 0;
        printf("Received: \"%s\"\n", buf);
        SSL_free(ssl);        /* release connection state */
    }
    close(server);         /* close socket */
    SSL_CTX_free(ctx);        /* release context */
    return 0;
}
示例#16
0
void *Servlet(void *threadarg)	{	
   char buf[1024];
   char reply[1024];
   int sd, bytes;
   const char* HTMLecho="Esto solo es un mensaje ISO01|EOF";
   	
   struct thread_data *my_data;
   int taskid;
   /*Parser de los datos de la estructura a variables */
    my_data = (struct thread_data *) threadarg;
    taskid = my_data->thread_id;
    SSL *ssl = my_data->message;

   /*Se inicia el procedimiento del server */
    printf("Inicia Servlet \n");
    if ( SSL_accept(ssl) == FAIL ) {			
        printf("Hubo un error en el SSL_accept \n");
        ERR_print_errors_fp(stderr);
    } else {
        printf("SSL_accept fue exitoso \n");
        ShowCerts(ssl);					
        bytes = SSL_read(ssl, buf, sizeof(buf));	
        if ( bytes > 0 ) {
            buf[bytes] = 0;
            printf("Mensaje cliente: \"%s\"\n", buf);
            sprintf(reply, HTMLecho, buf);		
	    sleep(5);
            SSL_write(ssl, reply, strlen(reply));	
        }
        else
            ERR_print_errors_fp(stderr);
    }
    sd = SSL_get_fd(ssl);			
    SSL_free(ssl);				
    close(sd);					
}
示例#17
0
int main(int argc , char *argv[])
{
    
     int sfd;
     char *P_num; 
     SSL_CTX * ctx;
     struct sockaddr_in cli_addr;   
     socklen_t len ;
     int cli;
     pid_t pid;
     struct sigaction sa;

    //Innitiliaze Server
   if (checkFileStruct() == -1){
       printf("Server: Problem With OldTrusty File Structure\n");
       exit(1);
   }
   //Initialize the Vouch Structure
       initVouchStruct();
   
    //Initialize SSL 
       
    if (argc != 2) {
        printf("Usage %s <portNUMBER> \n" , argv[0]);
        exit(1);
    }
    P_num = argv[1]; //Set Port

    ctx = InitSSL();
    load_Certs(ctx, "OldTrusty/ServerCerts/server.crt", "OldTrusty/ServerCerts/server.key");  //ALL IN ONE ? 
    //Get A regular tcp socket. already bound and listening.
    sfd = sock_setup(P_num);

    sa.sa_handler = sigchld_handler; // reap all dead processes
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) == -1) {
    perror("sigaction");
    exit(1); }
    

    printf("Server: OldTrusty Awaiting Connections on Port: %s\n" , P_num);

      //***********************************MAIN ACCEPT LOOP STARTS HERE *****************************/
    for(;;) {     
             
    len  = sizeof(cli_addr);
    
    cli = accept(sfd,  (struct sockaddr *)&cli_addr, &len); 
        if (cli == -1) {
            perror("accept");
            continue;
        }
    printf("Server: OLDTRUSTY recieved A Connection from: %s:%d\n",inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));

    SSL *ssl;

   
   if ( ( pid = fork())  == 0 ){

    //WE ARE THE CHILD
    close(sfd);    //Child doesnt need listner


    //Layer SSL Over Client Socket
    ssl = SSL_new(ctx); 
    SSL_set_fd(ssl, cli); 

  
    //HANDSHAKE.. 
    if ( SSL_accept(ssl) == -1)    
       ERR_print_errors_fp(stderr);

    //Show Client Certs (If any) // CAN ADDif require client auth then     //for now jsut show client certs if has any
    ShowCerts(ssl);

    // Here is a connection to the client 
    do_clients_bidding(ssl);
    
    SSL_free(ssl);
    close(cli);

    exit(0); // kill child.

    }  

    close(cli); //Parent closes connected socket (Being Handled in child)

    }  ///***END MAIN ACCEPT LOOP *****//
     
    SSL_CTX_free(ctx); //release context TODO never get hear?? graceful shutdown of server?
   
   
return 0;

}  
int main(int count, char *strings[])
{   SSL_CTX *ctx;
    int server;
    SSL *ssl;
    char buf[10240];
    int bytes;
    char *hostname, *portnum, *filename;

	int file;

	int localerror;

	char *command;
	char **data;
	char *buffer;

	int filesize, readData;

    if ( count != 4 )
    {
        printf("usage: %s <filename> <hostname> <portnum>\n", strings[0]);
        exit(0);
    }

    SSL_library_init();

	filename=strings[1];
 	hostname=strings[2];
 	portnum=strings[3];

    ctx = InitCTX();
    
    LoadCertificates(ctx, "client.csr", "client.key"); 
    SSL_CTX_load_verify_locations(ctx, "authority.pem", ".");
	SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
	SSL_CTX_set_verify_depth(ctx,1);

    server = OpenConnection(hostname, atoi(portnum));

    ssl = SSL_new(ctx);      /* create new SSL connection state */
    SSL_set_fd(ssl, server);    /* attach the socket descriptor */
   
 if ( SSL_connect(ssl) == FAIL )   /* perform the connection */
        ERR_print_errors_fp(stderr);
    else
    {   
		char *buffer;
		int BUFFERSIZE = 1024;

        printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
        if(ShowCerts(ssl))
        {
				buffer = (char *) calloc(1,BUFFERSIZE);
				data = (char **) calloc(1,255*sizeof(char*));
				command = (char *) calloc(1,255);

				//SEND GET
				memset(buffer,0,BUFFERSIZE);
				strcpy(buffer,"GET:");
				strcat(buffer,filename);
				strcat(buffer,"\r\n");

				SSL_write(ssl, buffer, strlen(buffer));
				printf("Sent: %s\n",buffer);

				//Read OK or NOTFOUND
				memset(data,0,255*sizeof(char*));
				memset(command,0,255);
				memset(buffer,0,BUFFERSIZE);

				SSL_read(ssl, buffer, BUFFERSIZE);
				printf("Read: %s\n",buffer);
				command = getCommand(buffer,data);


				if(strcmp(command,"OK")!=0)
				{
				free(command);
				free(data);
				free(buffer);	
				return;
				}

				//SEND OK
				memset(buffer,0,BUFFERSIZE);
				strcpy(buffer,"OK");
				strcat(buffer,"\r\n");

				int sendbytes = SSL_write(ssl, buffer, strlen(buffer));
				printf("Sent: %s\n",buffer);
				printf("Bytes: %d\n",sendbytes);

				//Read Size
				memset(data,0,255*sizeof(char*));
				memset(command,0,255);
				memset(buffer,0,BUFFERSIZE);

				SSL_read(ssl, buffer, BUFFERSIZE);
				printf("Read: %s\n",buffer);
				command = getCommand(buffer,data);

				if(strcmp(command,"SIZE")!=0)
				{
				free(command);
				free(data);
				free(buffer);	
				return;
				}

				filesize = atoi(data[0]);

				//SEND OK
				memset(buffer,0,BUFFERSIZE);
				strcpy(buffer,"OK");
				strcat(buffer,"\r\n");

				SSL_write(ssl, buffer, strlen(buffer));
				printf("Sent: %s\n",buffer);

				//OPEN FILE
				if((file = open(filename+1,O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) == -1)
				{
				localerror = errno;
				fprintf(stderr,"Can't open file for write (%s)\n",strerror(localerror));
				return;
				}	

				readData = 0;
				int total = 0;

				while((readData = SSL_read(ssl, buffer, BUFFERSIZE))>0)
				{	
				total += readData;
				printf("Read: %d\n",total);
				write(file,buffer,readData);
				memset(buffer,0,BUFFERSIZE);

				if(total>=filesize)
				break;
				}

				close(file);

				//SEND OK
				memset(buffer,0,BUFFERSIZE);
				strcpy(buffer,"OK");
				strcat(buffer,"\r\n");

				SSL_write(ssl, buffer, strlen(buffer));
				printf("Sent: %s\n",buffer);

				//Read BYE
				memset(data,0,255*sizeof(char*));
				memset(command,0,255);
				memset(buffer,0,BUFFERSIZE);

				SSL_read(ssl, buffer, BUFFERSIZE);
				printf("Read: %s\n",buffer);
				command = getCommand(buffer,data);

				if(strcmp(command,"BYE")!=0)
				{
				free(command);
				free(data);
				free(buffer);	
				return;
				}

				//SEND BYE
				memset(buffer,0,BUFFERSIZE);
				strcpy(buffer,"BYE");
				strcat(buffer,"\r\n");

				SSL_write(ssl, buffer, strlen(buffer));
				printf("Sent: %s\n",buffer);
		}        /* get any certs */
        
		
        SSL_free(ssl);        /* release connection state */
    }
    close(server);         /* close socket */
    SSL_CTX_free(ctx);        /* release context */
    return 0;
}
示例#19
0
文件: order_comm.c 项目: Crabbit/c
int COMM_SSL_PROCESS( int connected_fd, SSL_CTX *ctx )
{
	SSL			*ssl;

	fd_set			rset;

	int			retval;
	int			maxfd = -1;

//if send_state == -1	means	error;
//if send_satae == 0	means	send successful;
//if send_state == 4	means	quit;
	int			send_state;

	ssl = SSL_new( ctx );

	SSL_set_fd( ssl, connected_fd );

	if( SSL_connect( ssl ) == -1 )
		my_err( "SSL_connect",__LINE__ );
	else
	{
		printf( "Connected with %s encryption\n",SSL_get_cipher( ssl ) );
		ShowCerts( ssl );
	}

	printf( "If you want to be disconnected, please input \"QUIT__\" .\n" );

	FD_ZERO( &rset );
	while( 1 )
	{
		FD_SET( fileno( stdin ) , &rset );
		FD_SET( connected_fd, &rset );

		if( fileno( stdin ) > maxfd )
			maxfd = fileno( stdin );
		if( connected_fd > maxfd )
			maxfd = connected_fd;

		maxfd = maxfd + 1;

		printf( "If you wanto to send messages.\nplease input the word you want to transport:\n" );

		retval = select( maxfd, &rset, NULL, NULL, NULL );

		if( retval == -1 )
		{
			printf( "Select Error!\n" );
			break;
		}

		if( FD_ISSET( fileno( stdin ), &rset ) )
		{
			send_state = SSL_PROCESS_SEND( ssl );

			if( send_state == -1 )
				my_err( "SSL_PROCESS_SEND",__LINE__ );
			if( send_state == 4 )
				break;

		}
		if( FD_ISSET( connected_fd, &rset ) )
		{
			if( SSL_PROCESS_RECV( ssl ) == -1 )
				my_err( "SSL_PROCESS_RECV",__LINE__ );
		}
	}

	SSL_shutdown( ssl );

	SSL_free( ssl );

	close( connected_fd );

	SSL_CTX_free( ctx );

	return 0;

}
示例#20
0
int main(int argc, char *argv[])
{
    /* deletes existeng ecents */
    remove("ecents.txt");
    SSL_CTX *ctx;
    int type, server, localport, proxyport, bankport;
    int i = 0;
    SSL *ssl;
    char buf[1024];
	char buf2[33000];
    int bytes;
    char *proxyhost;
    char *bankhost;
    
    if ( argc <6 )
    {
        printf("usage: type localport proxyhost proxyport bankhost bankport \n");
        exit(0);
    }
    /* initialises SSL library and copies line arguments */
    SSL_library_init();
    type = atoi(argv[1]);
    localport=atoi(argv[2]);
    proxyhost=argv[3];
    proxyport = atoi(argv[4]);
    bankhost = argv[5];
    bankport = atoi(argv[6]);
    registrationrequest(type, localport, proxyhost, proxyport);
    int requestedecents = 1000;
    
    
    while(1){
        char msg[1024];
        bzero(msg,1024);
        ctx = InitCTX();
        if(i == 0){
            printf("\nrequested number of eCents: \n");
	    wait(3);
	    printf("\t%i\n", requestedecents);
	    wait(3);
            sprintf(msg,"%c%i",'0',requestedecents);
	        server = OpenConnection(bankhost, localport, bankport);
        }
        else{
            printf("\ninput:\n");
            strcpy(msg, geteCent());
            if(strlen(msg) != 32){
                printf("no eCents\n");
            }
            else {
                strcat(msg, getData());
                server = OpenConnection(proxyhost, localport, proxyport);
            }
        }
	/* creates ssl context and sets socket to it*/
        ssl = SSL_new(ctx);      
        SSL_set_fd(ssl, server);   
        if ( SSL_connect(ssl) == -1 ){  
            ERR_print_errors_fp(stderr);
	    printf("connection error\n");
	}
        else
        {
            printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
            printf("sending: %s\n", msg);
            ShowCerts(ssl);  
		/* Write to Bank to verify ecent */  
            SSL_write(ssl, msg, sizeof(msg));  
            
            if(i == 0){
		bzero(buf2, 33000);
		/* Read from Bank, confirm verification*/
		bytes = SSL_read(ssl, buf2, sizeof(buf2)); 
		if(bytes < 1) 
		{
			printf("Exit read error from Bank\n");
			exit(1);
		}
            	buf2[bytes] = '\0';
                printf("eCents received: %s\n", buf2);
                puteCents(buf2);
            }
            else{
		/* Reads from Collector*/
		bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */
            	buf[bytes] = '\0';
		if(bytes < 1) 
		{
			printf("Exit: read error from Analyst\n");
			exit(1);
		}
                if(strcmp(buf, "invalid eCent") == 0)
                    printf("\n%s\n", buf);
                else
                    printf("\naverage: %s\n", buf);
            }
            SSL_free(ssl);        
        }
        sleep(1);
        close(server);         
        SSL_CTX_free(ctx);       
        i++;
    }
    return 0;
}
示例#21
0
int main(int argc, char **argv)
{
  int sockfd, new_fd, fd;
  socklen_t len;
  struct sockaddr_in my_addr, their_addr;
  unsigned int myport, lisnum;
  char buf[MAXBUF + 1];
  char new_fileName[50]="./testfile/";
  SSL_CTX *ctx;
  mode_t mode;
  char pwd[100];
  char* temp;

  mkdir("./testfile",mode);

  if (argv[1])
    myport = atoi(argv[1]);
  else
  {
    myport = 7838;
    argv[2]=argv[3]=NULL;
  }

  if (argv[2])
    lisnum = atoi(argv[2]);
  else
  {
    lisnum = 2;
    argv[3]=NULL;
  }

  SSL_library_init();

  OpenSSL_add_all_algorithms();

  SSL_load_error_strings();

  ctx = SSL_CTX_new(SSLv23_server_method());

  if (ctx == NULL)
  {
    ERR_print_errors_fp(stdout);
    exit(1);
  }
  /* load certificate */
  getcwd(pwd,100);
  if(strlen(pwd)==1)
    pwd[0]='\0';
  if (SSL_CTX_use_certificate_file(ctx, temp=strcat(pwd,"/ca.pem"), SSL_FILETYPE_PEM) <= 0)
  {
    ERR_print_errors_fp(stdout);
    exit(1);
  }
  /* load private key */
  getcwd(pwd,100);
  if(strlen(pwd)==1)
    pwd[0]='\0';
  if (SSL_CTX_use_PrivateKey_file(ctx, temp=strcat(pwd,"/privkey.pem"), SSL_FILETYPE_PEM) <= 0)
  {
    ERR_print_errors_fp(stdout);
    exit(1);
  }

  if (!SSL_CTX_check_private_key(ctx))
  {
    ERR_print_errors_fp(stdout);
    exit(1);
  }

  if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1)
  {
    perror("socket");
    exit(1);
  }
  else
    printf("socket created\n");

  bzero(&my_addr, sizeof(my_addr));
  my_addr.sin_family = PF_INET;
  my_addr.sin_port = htons(myport);
  if (argv[3])
    my_addr.sin_addr.s_addr = inet_addr(argv[3]);
  else
    my_addr.sin_addr.s_addr = INADDR_ANY;

  if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)) == -1)
  {
    perror("bind");
    exit(1);
  }
  else
    printf("binded\n");

  if (listen(sockfd, lisnum) == -1)
  {
    perror("listen");
    exit(1);
  }
  else
    printf("begin listen\n");

  while (1)
  {
    SSL *ssl;
    len = sizeof(struct sockaddr);
    /* connection from clients */
    if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &len)) == -1)
    {
      perror("accept");
      exit(errno);
    }
    else
    {
		printf("server: got connection from %s, port %d, socket %d\n", inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port), new_fd);
        //ShowCerts(ssl);
	}
    ssl = SSL_new(ctx);

    SSL_set_fd(ssl, new_fd);

    if (SSL_accept(ssl) == -1)
    {
      perror("accept");
      close(new_fd);
      break;
    }

    ShowCerts(ssl);
    while(1)
    {
      bzero(buf, MAXBUF + 1);
      len = SSL_read(ssl, buf, MAXBUF);
      if(len == 0)
      {
        printf("Receive Complete !\n");
        break;
      }
      else if(len < 0)
      {
        printf("Failure to receive message ! Error code is %d,Error messages are '%s'\n", errno, strerror(errno));
        exit(1);
      }
	
	printf("Received: %s \n",buf);
	SSL_write(ssl, buf, strlen(buf));
    }


    close(fd);

    SSL_shutdown(ssl);

    SSL_free(ssl);

    close(new_fd);
  }


  close(sockfd);
  SSL_CTX_free(ctx);
  
  return 0;
}
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{   char buf[1024];
    char reply[1024];
    
    char common_key[1024];
    
    int a1,ret;
    int sd, bytes;
    const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";
    
    MCRYPT td, td2;
  char * plaintext = "sagar jawanjal";
  char* IV = "AAAAAAAAAAAAAAAA";
  char *key = "0123456789abcdef";
  int keysize = 16; /* 128 bits */
  char* buffer;
  int buffer_len = 16;

  buffer = calloc(1, buffer_len);
    
    		
 	
    if ( SSL_accept(ssl) == FAIL )     /* do SSL-protocol accept */
        ERR_print_errors_fp(stderr);
    else
    {
        ShowCerts(ssl);        /* get any certificates */
        bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
        if ( bytes > 0 )
        {
            buf[bytes] = 0;
            printf("Client msg: \"%s\"\n", buf);
            sprintf(reply, HTMLecho, buf);   /* construct reply */
            SSL_write(ssl, "hello-client", strlen(reply)); /* send reply */
            
            printf("Enter the value of n and g : ");
 	    scanf("%d%d",&n,&g);
            
            printf("Enter the value of x for the first person : ");
 		scanf("%d",&x);
 		a1=power(g,x,n);
            
           tostring(a,a1);
           
           printf("%s %d",a, a1);
            
            SSL_write(ssl,a,sizeof(a));
            
            SSL_read(ssl,ka, sizeof(ka));
      
      		int  result = toint(ka);
      		 printf("Received: \"%s\"\n",ka);
     		    printf("Received: \"%d\"\n",result);
     		    
     		     p=power(result,x,n);
         
         printf("Common secret-key for server is : %lld\n",p);
            
             SSL_read(ssl,has1, sizeof(has1));
         
        
          //tostring(a,p);
        tostring(a,p);
         printf("%s",has1);
         
        hash(has1);
        hash(a);
         if (strcmp(a,has1) == 0)
       {
  	    printf("Client Authenticated.\n"); 
   	
   	}else{
   	    printf("Client Not Authenticated.\n");
   					   }


//====================================================================================================================================


  strncpy(buffer, plaintext, buffer_len);

  printf("==C==\n");
  printf("plain:   %s\n", plaintext);
  
  strcat(a,key);
  printf("%s",a);
  
  encrypt(buffer, buffer_len, IV, a, keysize);
   printf("cipher:  "); display(buffer , buffer_len);
  char arr[33];
    
    for(int i=0;i<buffer_len;i++)
    {
      //printf("%d ",buffer[i]);
      arr[i]=buffer[i];    
    }
    
    SSL_write(ssl,arr,sizeof(arr));
   
  printf("cipher:  "); display(buffer , buffer_len);
  
  //printf("size=%d",sizeof(buffer));
  
  //decrypt(buffer, buffer_len, IV, key, keysize);
 // printf("decrypt: %s\n", buffer);




 				
         
        
            
        }
        else
            ERR_print_errors_fp(stderr);
    }
    sd = SSL_get_fd(ssl);       /* get socket connection */
    SSL_free(ssl);         /* release SSL state */
    close(sd);          /* close connection */
    
     	//printf("4");
}
示例#23
0
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{   char buf[1024];
	char out[1024];
    char reply[1024];
    int firstFlag=1;
    char firstLine[1024];
    int sd, bytes;
    int readBytes;
    char *ptr;
    int file;
    const char* HTMLecho="<html><body><pre>%s</pre></body></html>\n\n";

    if ( SSL_accept(ssl) == FAIL ){     /* do SSL-protocol accept */
    	ERR_print_errors_fp(stderr);
    }

    else
    {
        ShowCerts(ssl);        /* get any certificates */

    	SSL_read(ssl, buf, sizeof(buf));

    	// Procesar el get

    	ptr = strtok(buf, "/");
    	ptr = strtok(NULL, " ");
    		fprintf(stdout,"%s\n",ptr);

    	//Responder con 200 ok si existe
    	//strcpy(out, "HTTP/1.1 200 ok\r\nContent-Type: text/html\r\n\r\n");
    	//sprintf(reply, HTMLecho, out);   /* construct reply */
    	//SSL_write(ssl, reply, strlen(reply));
    	//printf("Lo que mandó:  %s",reply);
    	//printf("1");
    	//strcpy(out, "Content-Type: text/html\r\n");
    	//sprintf(reply, HTMLecho, out);   /* construct reply */
    	//SSL_write(ssl, reply,strlen(reply));
    	//printf("lo que mandó:  %s",reply);
    	//strcpy(out, "Content-Lenght: 171\r\n");
    	//sprintf(reply, HTMLecho, out);   /* construct reply */
    	//SSL_write(ssl, reply,strlen(reply));
    	//printf("lo que mandó:  %s",reply);
    	//strcpy(out, "\r\n");
    	//sprintf(reply, HTMLecho, out);   /* construct reply */
    	//SSL_write(ssl, reply, strlen(reply));
    	//printf("lo que mandó:  %s",reply);

    	//Enviar el archivo
    	file = open(ptr, O_RDONLY);
    	//printf("2\n");
    	//RESPONDER CON 404 NOT FOUND SI NO EXISTE
    	if(file == -1){
    		strcpy(reply, "<html><head><title>404 NOT FOUND</title></head><body>NO EXISTE!!!</body></html>");
    		SSL_write(ssl, reply,strlen(reply));
    	}

    	else{
    		while((readBytes = read(file,buf, 255)) > 0){
    			SSL_write(ssl, buf, readBytes);
    		}
    	}
    }
    sd = SSL_get_fd(ssl);       /* get socket connection */
    SSL_free(ssl);         /* release SSL state */
    close(sd);          /* close connection */
}
int main(int count, char *strings[])
{   
	SSL_CTX *ctx;
    int server;
    int choice=0;
    SSL *ssl;
    char buf[1024];
    int bytes;
    char *hostname, *portnum;
    char filename[20] ;

    if ( count != 3 ){
        printf("usage: %s <hostname> <portnum>\n", strings[0]);
        exit(0);
    }
    
    SSL_library_init();
    hostname=strings[1];
    portnum=strings[2];

    ctx = InitCTX();
    server = OpenConnection(hostname, atoi(portnum));
    ssl = SSL_new(ctx);      /* create new SSL connection state */
    SSL_set_fd(ssl, server);    /* attach the socket descriptor */
    if ( SSL_connect(ssl) == FAIL )   /* perform the connection */
        ERR_print_errors_fp(stderr);
    else{

        printf("Connected with %s encryption\n\n", SSL_get_cipher(ssl));
        ShowCerts(ssl);        /* get any certs */
        printf("\n\n");
        printf("Welcome to Cloud Storage System :\n Enter 1 - FILE UPLOAD\n 2 - FILE DOWNLOAD \n ");
     	scanf("%d",&choice);

        if(choice ==1){
			printf("Enter the file name you want to upload :");
			scanf("    %s",filename);
			FILE *fp = fopen(filename,"r");
			if(fp==NULL){
				printf("File open error\n\n");
				SSL_free(ssl);
				 close(server);         /* close socket */
				 SSL_CTX_free(ctx);
				return 1;
			}

			SSL_write(ssl,filename,sizeof(filename));
			char ack[10];
			SSL_read(ssl,ack,sizeof(ack));
       	    printf("File name ACK received: %s\n\n",ack);
       	     /* Read data from file and send it. First read file in chunks of BUF_SIZE bytes */
            unsigned char buff[BUF_SIZE]={0};
            int nread = fread(buff,1,BUF_SIZE,fp);
            printf("Bytes read %d \n", nread);

            /* If read was success, send data. */
            if(nread > 0){
				printf("Sending File contents to server Side \n");
				SSL_write(ssl, buff, nread);  /* send file contents to server */
        		calHmac(buff,filename,choice);
            }
			
			// SSL_write(ssl, msg, strlen(msg));
 			bytes = SSL_read(ssl, buf, sizeof(buf)); /* get reply & decrypt */
 			buf[bytes] = 0;
            printf("\nReceived: File Created at Server \n" );
        }
            
        else if(choice ==2){
            printf("Enter the file name you want to download :");
            scanf("    %s",filename);
            SSL_write(ssl,"DOWNLOAD",sizeof(filename));
            char ack[30];
            int replay=0;
            SSL_read(ssl,ack,sizeof(ack));
            printf("File name ACK received: %s\n\n",ack);
            strcat(ack,"-");
            strcat(ack,filename);
            printf("Do you want to try Replay Attack? If yes, enter 1:");
            scanf("%d",&replay);
            
            if(replay ==1){
            	printf("Enter the data to replay :");
            	scanf("%s",ack);
            	SSL_write(ssl,ack,sizeof(ack));
            }
            else{
           	SSL_write(ssl,ack,sizeof(ack));
            }
            
            unsigned char fileContent[256];
  			SSL_read(ssl,fileContent,sizeof(fileContent));
            printf("File Contents received: %s\n\n",fileContent);
            calHmac(fileContent,filename,choice);
            
            //path where downloaded files are stored
            char filepath[90]="/Users/prashanth/Desktop/try-1/ProejectTry-2/Download/";
            	            strcat(filepath,filename);
            	            FILE *DownloadFp=0;

            	            //writing Downloaded file contents to a new location
            	            DownloadFp = fopen(filepath, "w");
            	            if(DownloadFp == NULL)
            	                printf("Sorry, file cannot be created\n");
            	            else{
            	                fwrite(fileContent,sizeof(unsigned char), sizeof(fileContent),DownloadFp);
            	                printf("\n Path of Downloaded file:%s \n",filepath);
            	                fclose(DownloadFp);
            	                } // Directory al

        }
        
        else{
        	printf("Invalid Choice\n");
        	exit(0);
        }
        
        SSL_free(ssl);        /* release connection state */
    }
    close(server);         /* close socket */
    SSL_CTX_free(ctx);        /* release context */
    return 0;
}
示例#25
0
void clientProccess(SSL_CTX *ctx, const int clientSocket) {
	
	char *buffer;
	char *firstLine, *host, *usr_agent, *content;		//REQUEST HEADERS
	char html[250];
	int file;
	int readBytes;
	int firstFlag;
	int tmp_size;
	
	char *type;
	char *request;
	char *protocol;
	char *pch;
	char *size;
	
	SSL *ssl;
	int sd;

	ssl = SSL_new(ctx); 				/* get new SSL state with context */
	SSL_set_fd(ssl, clientSocket);			/* set connection socket to SSL state */
	
	if ( SSL_accept(ssl) == FAIL ){     		/* do SSL-protocol accept */
		ERR_print_errors_fp(stderr);
		return;
	}
	
	ShowCerts(ssl);        				/* get any certificates */

	debug(2,"Inicio del proceso del Cliente\n");

	type = calloc(255,1);
	request = calloc(255,1);
	protocol = calloc(255,1);

	buffer = calloc(255,1);

	firstLine = calloc(255,1);
	host = calloc(255,1);
	usr_agent = calloc(255,1);
	content = calloc(255,1);

	firstFlag = 1;
	while(SSL_read(ssl,buffer,254)>0) {		/* get request */
		debug(4,"%s",buffer);
		if(strcmp(buffer,"\r\n")==0) {
			break;
		}

		switch(firstFlag){				
			case 1: strcpy(firstLine, buffer);	//Catch request method from client
				firstFlag++;
				break;
			case 2: strcpy(host, buffer);		//Catch host
				firstFlag++;
				break;
			case 3: strcpy(usr_agent, buffer);	//Catch user agent from client
				firstFlag++;
				break;
			case 4: strcpy(content, buffer);	//Catch all content-type used
				firstFlag++;
				break;
			default: break;
		}
		bzero(buffer,255);
	}	
	
	//REQUEST HEADERS
	debug(4,"%s",firstLine);
	debug(4,"%s",host);
	debug(4,"%s",usr_agent);
	debug(4,"%s",content);

	// PROCESAR EL GET
	debug(4,"First Line %s",firstLine);
	pch = strtok (firstLine," /\r\n");
	while (pch != NULL)
	{
		if(strlen(type) == 0) 			//Catch type of request
			strcpy(type, pch);
		else if(strlen(request) == 0)		//Catch URI 
			strcpy(request, pch);	
		else if(strlen(protocol) == 0)		//Catch protocol
			strcpy(protocol, pch);
		pch = strtok(NULL, " \r\n");

	}
	*request++;

	debug(4,"REQUEST %s", request);

	//RESPONDER CON 200 OK  SI EXISTE EL REQUEST
	if(strlen(request) == 0){
		sendStatus(clientSocket, "HTTP/1.1 200 OK");
	} else{
		file = open(request, O_RDONLY);			

		if(file == -1) {
			debug(4,"Error while open file %s", request);
			sendStatus(clientSocket, "HTTP/1.1 404 Not Found");
			strcpy(html, "<html><head><title>404 NOT FOUND</title></head><body>NO EXISTE!!!</body></html>\r\n");			
			//sendTCPLine4(clientSocket, html,strlen(html));
			SSL_write(ssl, html, strlen(html));

			error(errno, "No se pudo abrir el archivo");
		}else{
			debug(4,"Preparing to send file %s", request);

			sendStatus(clientSocket, "HTTP/1.1 200 OK");
			while((readBytes = read(file,buffer,255))>0) {		//Send file to client
				//sendTCPLine4(clientSocket,buffer,readBytes);
				SSL_write(ssl, buffer, readBytes);
			}

			strcpy(html, content);				//Send Content-type
			strcat(html, "\r\n");
			
			tmp_size = (int)fsize(request);			//Get size of file
			size = itoa (tmp_size);

			strcpy(html, "Content-lenght: ");		//Send Content-lenght
			strcat(html, size);
			strcat(html, "\r\n");
			//sendTCPLine4(clientSocket, html, strlen(html));
			SSL_write(ssl, html, strlen(html));
		}
	}
	
	//strcpy(html, "Content-Type: text/html\r\n");
	//sendTCPLine4(clientSocket, html, strlen(html));

	//strcpy(html, "Content-Lenght: 457838592\r\n");
	//sendTCPLine4(clientSocket, html,strlen(html));
	
	
	//CERRAMOS LA COMUNICACIÓN
	sd = SSL_get_fd(ssl); 			/* get socket connection */
	SSL_free(ssl); 				/* release SSL state */
	close(sd);				/* close connection */
	SSL_CTX_free(ctx);			/* release context */
	close(clientSocket);			/* close server socket */

	return;
}
void Servlet(SSL* ssl) /* Serve the connection -- threadable */
{   
	
    char reply[1024], file[56];
    int sd, bytes, fileint;
    int itr=0;
    SSL_CTX_set_verify(SSL_get_SSL_CTX(ssl), SSL_VERIFY_PEER, NULL);

    if ( SSL_accept(ssl) == FAIL )     /* do SSL-protocol accept */
        ERR_print_errors_fp(stderr);
    else{
        ShowCerts(ssl);        /* get any certificates */
        
        //Handling Data replay attack using rand session variable
		srand(time(NULL));
        int sessionNum = rand()%100;
        char ack[10];
        sprintf(ack,"%d",sessionNum);

        int attack=0;

        fileint = SSL_read(ssl,file, sizeof(file));
        
        if(strcmp(file, "DOWNLOAD")==0){
        	SSL_write(ssl,ack, 10);
        	printf("Command received: %s\n\n",file);
        	//Verify token and filename
        	char verifyFile[50];
        	SSL_read(ssl,verifyFile, sizeof(verifyFile) );
        	printf("filename: %s\n\n",verifyFile);
        	char * session=strtok(verifyFile,"-");
        	char * filename = strtok(NULL,"-");
        	
        	//Checking for session number to see if it is a replay attack 
        	for(itr=0; itr<25;itr++)
        	{
        		if(strcmp(UsedSessions[itr], session)==0)
        		{			attack =1;
        			break;
        		}

        	}
        	if(attack ==1)
        		SSL_write(ssl,"REPLAY ATTACK",15);
        	else{
        		AESEncryptData(filename,2);

        		printf("Client msg: \"%s\"\n", filename);
        		sprintf(reply, "%s", buf);   /* construct reply */
        		SSL_write(ssl, reply, strlen(reply)); /* send reply */
        		memset(buf,0,sizeof(buf));
        		sprintf(UsedSessions[SessionCount],"%d",sessionNum);
        		//printf("\nfdgddg: %s",UsedSessions[SessionCount++]);
        	}

        }
        
        //UPLOAD Scenario
        else{
        	SSL_write(ssl,"Uploading File", 10);
        	bytes = SSL_read(ssl, buf, sizeof(buf)); /* get request */
        	        if ( bytes > 0 ){
        	            buf[bytes] = 0;
        	            AESEncryptData(file,1);
        	            //printf(": \"%s\"\n", buf);
        	            printf("File received ... Encrypted\n");
        	            sprintf(reply, "%s", buf);   /* construct reply */
        	            SSL_write(ssl, reply, strlen(reply)); /* send reply */
        	            memset(buf,0,sizeof(buf));
        	        }
        	        else
        	            ERR_print_errors_fp(stderr);
        }

	}
	
    sd = SSL_get_fd(ssl);       /* get socket connection */
    SSL_free(ssl);         /* release SSL state */
    close(sd);          /* close connection */
}
示例#27
0
文件: ssl_client.c 项目: sklvjz/misc
int main(int argc, char **argv)
{
    int sockfd, len;
    struct sockaddr_in dest;
    char buffer[MAXBUF + 1];
    SSL_CTX *ctx;
    SSL *ssl;

    if (argc != 3) {
        printf("参数格式错误!正确用法如下:\n\t\t%s IP地址 端口\n\t比如:\t%s 127.0.0.1 80\n此程序用来从某个"
             "IP 地址的服务器某个端口接收最多 MAXBUF 个字节的消息",
             argv[0], argv[0]);
        exit(0);
    }

    /* SSL 库初始化,参看 ssl-server.c 代码 */
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    SSL_load_error_strings();
    ctx = SSL_CTX_new(SSLv23_client_method());
    if (ctx == NULL) {
        ERR_print_errors_fp(stdout);
        exit(1);
    }

    /* 创建一个 socket 用于 tcp 通信 */
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket");
        exit(errno);
    }
    printf("socket created\n");

    /* 初始化服务器端(对方)的地址和端口信息 */
    bzero(&dest, sizeof(dest));
    dest.sin_family = AF_INET;
    dest.sin_port = htons(atoi(argv[2]));
    if (inet_aton(argv[1], (struct in_addr *) &dest.sin_addr.s_addr) == 0) {
        perror(argv[1]);
        exit(errno);
    }
    printf("address created\n");

    /* 连接服务器 */
    if (connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)) != 0) {
        perror("Connect ");
        exit(errno);
    }
    printf("server connected\n");

    /* 基于 ctx 产生一个新的 SSL */
    ssl = SSL_new(ctx);
    SSL_set_fd(ssl, sockfd);
    /* 建立 SSL 连接 */
    if (SSL_connect(ssl) == -1)
        ERR_print_errors_fp(stderr);
    else {
        printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
        ShowCerts(ssl);
    }

    /* 接收对方发过来的消息,最多接收 MAXBUF 个字节 */
    bzero(buffer, MAXBUF + 1);
    /* 接收服务器来的消息 */
    len = SSL_read(ssl, buffer, MAXBUF);
    if (len > 0)
        printf("接收消息成功:'%s',共%d个字节的数据\n",
               buffer, len);
    else {
        printf
            ("消息接收失败!错误代码是%d,错误信息是'%s'\n",
             errno, strerror(errno));
        goto finish;
    }
    bzero(buffer, MAXBUF + 1);
    strcpy(buffer, "from client->server");
    /* 发消息给服务器 */
    len = SSL_write(ssl, buffer, strlen(buffer));
    if (len < 0)
        printf
            ("消息'%s'发送失败!错误代码是%d,错误信息是'%s'\n",
             buffer, errno, strerror(errno));
    else
        printf("消息'%s'发送成功,共发送了%d个字节!\n",
               buffer, len);

  finish:
    /* 关闭连接 */
    SSL_shutdown(ssl);
    SSL_free(ssl);
    close(sockfd);
    SSL_CTX_free(ctx);
    return 0;
}
示例#28
0
int main(int argc, char **argv)
{
  int i,j,sockfd, len, fd, size;
  char fileName[50],sendFN[20];
  struct sockaddr_in dest;
  char buffer[MAXBUF + 1];
  SSL_CTX *ctx;
  SSL *ssl;

  if (argc != 3)
  {
    printf("Parameter format error! Correct usage is as follows:\n\t\t%s IP Port\n\tSuch as:\t%s 127.0.0.1 80\n", argv[0], argv[0]); exit(0);
  }

  /* SSL initialize */
  SSL_library_init();
  OpenSSL_add_all_algorithms();
  SSL_load_error_strings();
  ctx = SSL_CTX_new(SSLv23_client_method());
  if (ctx == NULL)
  {
    ERR_print_errors_fp(stdout);
    exit(1);
  }

  /* create tcp socket */
  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  {
    perror("Socket");
    exit(errno);
  }
  printf("socket created\n");

  /* addr and port */
  bzero(&dest, sizeof(dest));
  dest.sin_family = AF_INET;
  dest.sin_port = htons(atoi(argv[2]));
  if (inet_aton(argv[1], (struct in_addr *) &dest.sin_addr.s_addr) == 0)
  {
    perror(argv[1]);
    exit(errno);
  }
  printf("address created\n");

  /* connect server */
  if (connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)) != 0)
  {
    perror("Connect ");
    exit(errno);
  }
  printf("server connected\n\n");

  ssl = SSL_new(ctx);
  SSL_set_fd(ssl, sockfd);

  if (SSL_connect(ssl) == -1)
    ERR_print_errors_fp(stderr);
  else
  {
    printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
    ShowCerts(ssl);
  }

  scanf("%s",fileName);
  if((fd = open(fileName,O_RDONLY,0666))<0)
  {
    perror("open:");
    exit(1);
  }

  for(i=0;i<=strlen(fileName);i++)
  {
    if(fileName[i]=='/')
    {
      j=0;
      continue;
    }
    else {sendFN[j]=fileName[i];++j;}
  }
  len = SSL_write(ssl, sendFN, strlen(sendFN));
  if (len < 0)
    printf("'%s'message Send failure !Error code is %d,Error messages are '%s'\n", buffer, errno, strerror(errno));

  bzero(buffer, MAXBUF + 1);
  while((size=read(fd,buffer,1024)))
  {
    if(size<0)
    {
      perror("read:");
      exit(1);
    }
    else
    {
      len = SSL_write(ssl, buffer, size);
      if (len < 0)
        printf("'%s'message Send failure !Error code is %d,Error messages are '%s'\n", buffer, errno, strerror(errno));
    }
    bzero(buffer, MAXBUF + 1);
  }
  printf("Send complete !\n");

  close(fd);
  SSL_shutdown(ssl);
  SSL_free(ssl);
  close(sockfd);
  SSL_CTX_free(ctx);
  return 0;
}
示例#29
0
文件: s.c 项目: Viktory2000/Cits3002
int main(int argc , char *argv[])
{
    
     int sfd;
     char *P_num; 
     SSL_CTX * ctx;
     struct sockaddr_in cli_addr;   
     socklen_t len ;
     int cli;
     pid_t pid;

    //Innitiliaze Server
   if (checkFileStruct() == -1){
       printf("Problem With OldTrusty File Structure\n");
       exit(1);
   }
   



    //Initialize SSL 
       
    if (argc != 2) {
        printf("Usage %s <portNUMBER> \n" , argv[0]);
        exit(1);
    }
    P_num = argv[1]; //Set Port

    ctx = InitSSL();
    load_Certs(ctx, "OldTrusty/ServerCerts/mycert.pem", "OldTrusty/ServerCerts/mycert.pem");  //ALL IN ONE ? 
    //Get A regular tcp socket. already bound and listening.
    sfd = sock_setup(P_num);


    printf("OldTrusty Awaiting Connections on Port: %s\n" , P_num);

      //***********************************MAIN ACCEPT LOOP STARTS HERE *****************************/
    for(;;) {     
        //Ever ?? 
        
      len  = sizeof(cli_addr);
    
    cli = accept(sfd,  (struct sockaddr *)&cli_addr, &len); 
        if (cli == -1) {
            perror("accept");
            continue;
        }
    printf("OLDTRUSTY RECIEVED A Connection from: %s:%d\n",inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));

    SSL *ssl;

   
   if ( ( pid = fork())  == 0 ){

    //WE ARE THE CHILD
    close(sfd);    //Child doesnt need listner


    //Layer SSL Over Client Socket
    ssl = SSL_new(ctx); 
    SSL_set_fd(ssl, cli); 

  
    //HANDSHAKE.. 
    if ( SSL_accept(ssl) == -1)    
       ERR_print_errors_fp(stderr);

    //CREATE BIO OBJECT FOR THE SSL ?? TODO TO US OpenSSL over other channels (not just socketS)
    //TODO

    //Show Client Certs (If any) // CAN ADDif require client auth then -- check_cert(ssl,client )
    //for now jsut show client certs if has any
    ShowCerts(ssl);

    // Here is a connection to the client 
    do_clients_bidding(ssl);


    
    SSL_free(ssl);
    close(cli);

    exit(0); // kill child.

    }  

    close(cli); //Parent closes connected socket (Being Handled in child)

    }  ///***END MAIN ACCEPT LOOP *****//
     

    SSL_CTX_free(ctx); //release context TODO never get hear?? graceful shutdown of server?
   
   
return 0;

}