Page 1 of 1

Doing OpenSSL on Ultimate Edition 4.2 S.O.S

PostPosted: Mon Jul 14, 2014 9:07 pm
by PejuangSufi
I've installed all the library required and openssl 1.0.1.h, and so on
i've created a server with openssl encryption and i'm gonna test it. the server is tested with a client but somehow when i try to reconnect it back the server will crash in the second time. please help me.

/* Client Side */
Code: Select all
sufi@NL-4869:~$ cd Desktop/Working/Finish\ Today/
sufi@NL-4869:~/Desktop/Working/Finish Today$ ls
ChangeLogs   client       client.c     MultiServer.bak1  MultiServer.bak3  server.c
ChangeLogs~  client.bak1  MultiServer  MultiServer.bak2  MultiServer.c
sufi@NL-4869:~/Desktop/Working/Finish Today$ ./client
Enter PEM pass phrase:
Connected with AES256-SHA encryption
Server certificates:
Subject: /C=MY/ST=Kulim/L=Kulim/O=MIMOS/OU=MIMOS/CN=mohana/[email protected]
Issuer: /C=MY/ST=Kulim/L=Kulim/O=MIMOS/OU=MIMOS/CN=mohana/[email protected]
Received: "Siap Harini"
Received Data from dostuff: "Siap Harini"
sufi@NL-4869:~/Desktop/Working/Finish Today$ ./client
Enter PEM pass phrase:
sufi@NL-4869:~/Desktop/Working/Finish Today$ /*Second time no result??!! *


/* Server Side */
Code: Select all
sufi@NL-4869:~$ cd Desktop/Working/Finish\ Today/
sufi@NL-4869:~/Desktop/Working/Finish Today$ ls
ChangeLogs   client       client.c     MultiServer.bak1  MultiServer.bak3  server.c
ChangeLogs~  client.bak1  MultiServer  MultiServer.bak2  MultiServer.c
sufi@NL-4869:~/Desktop/Working/Finish Today$ ./MultiServer
Enter PEM pass phrase:
pid=2693
Connection: 127.0.0.1:32808
Server certificates:
Subject: /C=MY/ST=Kulim/L=Kulim/O=MIMOS/OU=MIMOS/CN=mohana/[email protected]
Issuer: /C=MY/ST=Kulim/L=Kulim/O=MIMOS/OU=MIMOS/CN=mohana/[email protected]
Client msg: "client-192.168.1.1
"
read from socket: client-192.168.1.1
received buffer - mohana: client-192.168.1.1pid=2695
Connection: 127.0.0.1:32809
Segmentation fault (core dumped)
sufi@NL-4869:~/Desktop/Working/Finish Today$



The Code for server.c
Code: Select all
/* A simple server in the internet domain using TCP
   The port number is passed as an argument
   This version runs forever, forking off a separate
   process for each connection
   gcc server2.c -lsocket
*/
#include <stdio.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <resolv.h>
#include "openssl/ssl.h"
#include "openssl/err.h"

#define MAXBUF 1024
#define FAIL    -1

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void dostuff(int,int, SSL*); /* function prototype */
void error(char *msg)
{
    perror(msg);
    exit(1);
}

SSL_CTX* InitServerCTX(void)
{   SSL_METHOD *method;
    SSL_CTX *ctx;

    OpenSSL_add_all_algorithms();  /* load & register all cryptos, etc. */
    SSL_load_error_strings();   /* load all error messages */
    method = SSLv3_server_method();  /* create new server-method instance */
    ctx = SSL_CTX_new(method);   /* create new context from method */
    if ( ctx == NULL )
    {
        ERR_print_errors_fp(stderr);
        abort();
    }
    return ctx;
}

void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile)
{
    //New lines
    if (SSL_CTX_load_verify_locations(ctx, CertFile, KeyFile) != 1)
        ERR_print_errors_fp(stderr);

    if (SSL_CTX_set_default_verify_paths(ctx) != 1)
        ERR_print_errors_fp(stderr);
    //End new lines

    /* set the local certificate from CertFile */
    if (SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0)
    {
        ERR_print_errors_fp(stderr);
        abort();
    }
    /* set the private key from KeyFile (may be the same as CertFile) */
    if (SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0)
    {
        ERR_print_errors_fp(stderr);
        abort();
    }
    /* verify private key */
    if (!SSL_CTX_check_private_key(ctx))
    {
        fprintf(stderr, "Private key does not match the public certificate\n");
        abort();
    }

    //New lines - Force the client-side have a certificate
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
    SSL_CTX_set_verify_depth(ctx, 4);
    //End new lines
}

void ShowCerts(SSL* ssl)
{   X509 *cert;
    char *line;

    cert = SSL_get_peer_certificate(ssl); /* Get certificates (if available) */
    if ( cert != NULL )
    {
        printf("Server certificates:\n");
        line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
        printf("Subject: %s\n", line);
        free(line);
        line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
        printf("Issuer: %s\n", line);
        free(line);
        X509_free(cert);
    }
    else
        printf("No certificates.\n");
}



int main(int argc, char *argv[])
{
    SSL_CTX *ctx;
    //int server =0;
    int sockfd, newsockfd, portno, clilen, pid;
     struct sockaddr_in serv_addr, cli_addr;

     char CertFile[] = "/home/sufi/OpenSSL/myCA/newkey/clientcert.pem";
     char KeyFile[] = "/home/sufi/OpenSSL/myCA/newkey/client.pem";

    SSL_library_init();

    ctx = InitServerCTX();        /* initialize SSL */
    LoadCertificates(ctx, CertFile, KeyFile); /* load certs */

/*   Creating Socket                        */
     /*if (argc < 2) {
         fprintf(stderr,"ERROR, no port provided\n");
         exit(1);
     }*/
     sockfd = socket(AF_INET, SOCK_STREAM, 0);
     if (sockfd < 0)
        error("ERROR opening socket");
     bzero((char *) &serv_addr, sizeof(serv_addr));
     portno = 5000;
     serv_addr.sin_family = AF_INET;
     serv_addr.sin_addr.s_addr = INADDR_ANY;
     serv_addr.sin_port = htons(portno);
     if (bind(sockfd, (struct sockaddr *) &serv_addr,
              sizeof(serv_addr)) < 0)
              error("ERROR on binding");
     listen(sockfd,5);
     signal(SIGCHLD,SIG_IGN);
     clilen = sizeof(cli_addr);
  //  server = OpenListener(5000);   

/*    while (1)
    {   struct sockaddr_in addr;
        socklen_t len = sizeof(addr);
        SSL *ssl;

//        int client = accept(server, (struct sockaddr*)&addr, &len);
        int client = accept(sockfd, (struct sockaddr*)&addr, &len);
         printf("Connection: %s:%d\n",inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
        ssl = SSL_new(ctx);
        SSL_set_fd(ssl, client);
        Servlet(ssl);         
    }
    //close(server);
    close(sockfd);                   
    SSL_CTX_free(ctx);      */
     
/*   Creating Threadable Socket            */
    while (1) {
       //Need to convert the normal socket into OpenSSL socket after newsockfd launch
       SSL *ssl;
         newsockfd = accept(sockfd,
               (struct sockaddr *) &cli_addr, &clilen);
         if (newsockfd < 0)
             error("ERROR on accept");
         pid = fork();
         if (pid < 0)
             error("ERROR on fork");
         if (pid == 0)  {
             close(sockfd);

             while(1)
      {
      // In the dostuff need to change the read/write into ssl read write
//      dostuff(newsockfd,pid);
        printf("Connection: %s:%d\n",inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));
        ssl = SSL_new(ctx);
        SSL_set_fd(ssl, newsockfd);
        //Servlet(ssl);
         dostuff(newsockfd,pid,ssl);
      }
             exit(0);
         }
         else
   {
   printf("pid=%d\n",pid);
   close(newsockfd);
   SSL_CTX_free(ctx); 
   }
     }
 /* end of while */
     return 0; /* we never get here */
}
/*   Finish Creating Socket                        */

// assume that length of a line will not exceed MAXBUF
// assume that buf has length MAXBUF
ssize_t readline(int sock, char *sockBuff, int *len, char *buff, SSL* ssl)
{
  int sockBuffLen = *len;
  int hasNewLine = 0;
  int buffLen = 0;
  char reply_client[1024];
 
  while (!hasNewLine)
  {
    int i;
    // copy from sockBuff to buff, until either
    // 1. new line is detected
    // 2. end of sockBuff
    for (i = 0; i < sockBuffLen; i++)
    {
      if (sockBuff[i] == 13)
      {
        buff[buffLen] = '\0';
        if ((i+1 < sockBuffLen) && (sockBuff[i+1] == 10))
          i++;
        hasNewLine = 1;
        break;
      }
      else if (sockBuff[i] == 10)
      {
        buff[buffLen] = '\0';
        hasNewLine = 1;
        break;
      }
      else
      {
        buff[buffLen] = sockBuff[i];
        buffLen++;
      }
    }

    if (hasNewLine)
    {
      // shift unread characters in buf to the front
      memmove(sockBuff, sockBuff+i+1, sockBuffLen-i-1);
      sockBuffLen = sockBuffLen-i-1;
    }
    else
    {
      // end of sockBuff, need to get new data from socket

       if ( SSL_accept(ssl) == FAIL )     /* do SSL-protocol accept */
      ERR_print_errors_fp(stderr);
       else
       {
      ShowCerts(ssl);        /* get any certificates */
      sockBuffLen = SSL_read(ssl, sockBuff, MAXBUF); /* get request */
      if ( sockBuffLen > 0 )
      {
          sockBuff[sockBuffLen] = 0;
          printf("Client msg: \"%s\"\n", sockBuff);
          sprintf(reply_client, "Siap Harini", sockBuff);   /* construct reply */
          SSL_write(ssl, reply_client, strlen(reply_client)); /* send reply */
      }
      else
          ERR_print_errors_fp(stderr);
       }
      //sockBuffLen = read(sock, sockBuff, MAXBUF);
      if (sockBuffLen <= 0)
        return sockBuffLen;
    }
  }
  printf("Read from SOCKET: %s\n", buff);
 
  *len = sockBuffLen;
  return buffLen;
  SSL_free(ssl);         /* release SSL state */
}

/******** DOSTUFF() *********************
 There is a separate instance of this function
 for each connection.  It handles all communication
 once a connnection has been established.
 *****************************************/
void dostuff (int sock,int pid, SSL* ssl)
{
   int dscp;
//   int n=0,dscp,len,i,a,camCount=1,ln,count=0;
//   char test[MAXBUF]={0};
   char buffer[MAXBUF];
   char sockBuffer[MAXBUF];
   int sockBufferLen = 0;
//   char buffer2[MAXBUF]={0};
//   char buff[MAXBUF]={0};
//   char buff2[MAXBUF]={0};
//   char *p,ch;
   char getCommand[MAXBUF]={0};   
   char output[MAXBUF]={0};
//   char instruct[MAXBUF]={0};
   char warning[MAXBUF]={0};
   char res[MAXBUF]={0};
//   char ipCam[MAXBUF]={0};
   char *pch, *camIP,*ac;
      
   FILE *result;
   readline(sock, sockBuffer, &sockBufferLen, buffer, ssl);
   printf("Received buffer: %s",buffer);
  // exit(1);

  while(readline(sock, sockBuffer, &sockBufferLen, buffer, ssl)>0)
  {
   //printf("start again\n");
    if (strstr(buffer,"client")!=NULL)
    {
      snprintf(getCommand, 1024, "bash /home/mimos/clientMACIP.sh");
      result = popen(getCommand,"r");
      if(result == NULL)
      {
         printf("Failed to run command\n");
      }
      else
      {
        while(fgets(res,sizeof(res),result) != NULL)
        {
          strcat(output,res);
        }
      }
      memset(getCommand,'\0',sizeof(getCommand));
      memset(buffer,'\0',sizeof(buffer));
      fflush(stdin);
      strcat(output,"\n");
      /*.........................SENDING..........................*/
      SSL_write(ssl, output, sizeof(output));
      //send(sock,output,sizeof(output),0);
      printf("output=%s\n",output);
      memset(output,'\0',sizeof(output));
      memset(res,'\0',sizeof(res));
      pclose(result);
    }

    else if (strstr(buffer,"nearby")!=NULL)
    {
      snprintf(getCommand, 1024, "bash /home/mimos/nearby.sh");
      result = popen(getCommand,"r");
      if(result == NULL)
      {
        printf("Failed to run command\n");   
      }
      else
      {
        while(fgets(res,sizeof(res),result) != NULL)
        {
          strcat(output,res);
        }
      }
      memset(getCommand,'\0',sizeof(getCommand));
      memset(buffer,'\0',sizeof(buffer));
      fflush(stdin);
      strcat(output,"\n");
      /*.........................SENDING.....................*/
      SSL_write(ssl, output, sizeof(output));
      //send(sock,output,sizeof(output),0);
      printf("output=%s\n",output);
      memset(output,'\0',sizeof(output));
      memset(res,'\0',sizeof(res));
      pclose(result);
    }
    else if (strstr(buffer,"sensors")!=NULL)
    {
      snprintf(getCommand, 1024, "bash /home/mimos/sensors.sh");
      result = popen(getCommand,"r");
      if(result == NULL)
      {
        printf("Failed to run command\n");
      }
      else
      {
        while(fgets(res,sizeof(res),result) != NULL)
        {
          strcat(output,res);
        }
      }
      memset(getCommand,'\0',sizeof(getCommand));
      memset(buffer,'\0',sizeof(buffer));
      fflush(stdin);
      strcat(output,"\n");
      /*.........................SENDING......................*/
      SSL_write(ssl, output, sizeof(output));
      //send(sock,output,sizeof(output),0);
      printf("output=%s\n",output);
      memset(output,'\0',sizeof(output));
      memset(res,'\0',sizeof(res));
      pclose(result);
    }
    else if (strstr(buffer,"prio")!=NULL)
    {
      while(readline(sock, sockBuffer, &sockBufferLen, buffer, ssl)>0)
      {
        ac = strtok(buffer," ");
        printf("ac=%s\n",ac);
        camIP = strtok(NULL," ");
        printf("camIP=%s\n",camIP);
        if(strncmp(ac,"VO",2)==0)
        {
          dscp=48;
        }
        else if(strncmp(ac,"VI",2)==0)
        {
          dscp=32;
        }
        else if(strncmp(ac,"BE",2)==0)
        {
      //dscp=0;
          printf("BE class\n");
        }
        else if(strncmp(ac,"BK",2)==0)
        {
          dscp=8;
        }

        if(strncmp(ac,"BE",2)!=0)
        {
          printf("other class,ac=%s, dscp=%d\n",ac,dscp);
          snprintf(getCommand, sizeof(getCommand), "bash /home/mimos/changeCamPrio.sh %d %s",dscp,camIP);
        }
        else if(strncmp(ac,"BE",2)==0)
        {
          printf("BE class\n");
          snprintf(getCommand, sizeof(getCommand), "bash /home/mimos/resetCamPrio.sh %s",camIP);
        }
        result = popen(getCommand,"r");
        if(result == NULL)
        {
          printf("Failed to run command\n");
        }
        else
        {
          while(fgets(res,sizeof(res),result) != NULL)
          {
            strcat(output,res);
     }
        }
        memset(getCommand,'\0',sizeof(getCommand));

        //fflush(stdin);
        strcat(output,"\n");
        /*..............SENDING..................*/
        SSL_write(ssl, output, sizeof(output));
        //send(sock,output,sizeof(output),0);
        printf("output=%s\n",output);
   //fflush(stdin);
      fflush(stdout);
        //buff[0]='\0';
   //output[0]='\0';
   memset(buffer,'\0',sizeof(buffer));
   memset(output,'\0',sizeof(output));
   memset(res,'\0',sizeof(res));
   pclose(result);
      }
         /*       read(sock,buff,MAXBUF-1);
      printf("buffer=%s,bufferLen=%d\n",buff,strlen(buff));
      if(strlen(buff)==2)
      {
      printf("enter pressed\n");
      goto start;
      }*/
      }
      
      //else if(buff[0]==13&&buff[1]==10)
      //break;
      
      
        else if(strstr(buffer,"clear")!=NULL)
   {
      snprintf(getCommand, sizeof(getCommand), "bash /home/mimos/clearPrio.sh");
   result = popen(getCommand,"r");
   if(result == NULL)
   {
      printf("Failed to run command\n");
   }
   else
   {
   while(fgets(res,sizeof(res),result) != NULL){
      strcat(output,res);
   }
   }
   memset(getCommand,'\0',sizeof(getCommand));
   memset(buffer,'\0',sizeof(buffer));
   fflush(stdin);
   strcat(output,"\n");

   /*......................................SENDING....................................*/
   SSL_write(ssl, output, sizeof(output));
   //send(sock,output,sizeof(output),0);
   printf("output=%s\n",output);
   fflush(stdout);
   memset(output,'\0',sizeof(output));
   memset(res,'\0',sizeof(res));
   pclose(result);
   }
        else if(strstr(buffer,"query")!=NULL)
   {
                pch=strtok(buffer," ");
                pch=strtok(NULL, " ");
                ac = pch;
      if(ac[strlen(ac)-1] == '\n')
      ac[strlen(ac)-1] = '\0';
      if(ac[strlen(ac)-2] == 13)
      ac[strlen(ac)-2] = '\0';
      if(strncmp(ac,"VO",2)==0){
      dscp=48;
      }else if(strncmp(ac,"VI",2)==0){
      dscp=32;
      }
      else if(strncmp(ac,"BE",2)==0){
      dscp=0;
      }
      else if(strncmp(ac,"BK",2)==0){
      dscp=8;
      }else
      {
      snprintf(warning,sizeof(warning),"No such access category\n");
      /*.........................SENDING..........................*/
      SSL_write(ssl, warning, sizeof(warning));
      //send(sock,warning,sizeof(warning),0);
      }
      printf("buffer=%s\n",buffer);
      printf("ac=%s\n",ac);
      printf("buffer len=%d\n",strlen(buffer));
      printf("ac len=%d\n",strlen(ac));
      
      snprintf(getCommand, sizeof(getCommand), "bash /home/mimos/queryAC.sh %d",dscp);
   printf("getcom=%s\n",getCommand);
   result = popen(getCommand,"r");
   if(result == NULL)
   {
      printf("Failed to run command\n");
   }
   else
   {
   while(fgets(res,sizeof(res),result) != NULL){
      strcat(output,res);
   }
   }
   memset(getCommand,'\0',sizeof(getCommand));
   memset(buffer,'\0',sizeof(buffer));
   fflush(stdin);
   strcat(output,"\n");
   /*.........................SENDING..........................*/
   SSL_write(ssl, output, sizeof(output));
   //send(sock,output,sizeof(output),0);
   printf("output=%s\n",output);
   memset(output,'\0',sizeof(output));
   memset(res,'\0',sizeof(res));
   pclose(result);
   }
        else if(strstr(buffer,"exit")!=NULL)
   {
      close(sock);
   }
   else
   {
      //printf("No such command");
   memset(buffer,'\0',sizeof(buffer));
      //goto start;
   }

   fflush(stdin);
   fflush(stdout);
   }
   //else if(strlen(buffer)==0)
//   {
   fflush(stdin);
   fflush(stdout);
   close(sock);
   exit(0);
//   }
}



/* Client's Code */
Code: Select all
//client.c
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

#define FAIL    -1

    //Added the LoadCertificates how in the server-side makes.   
void LoadCertificates(SSL_CTX* ctx, char* CertFile, char* KeyFile)
{
 /* set the local certificate from CertFile */
    if ( SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM) <= 0 )
    {
        ERR_print_errors_fp(stderr);
        abort();
    }
    /* set the private key from KeyFile (may be the same as CertFile) */
    if ( SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM) <= 0 )
    {
        ERR_print_errors_fp(stderr);
        abort();
    }
    /* verify private key */
    if ( !SSL_CTX_check_private_key(ctx) )
    {
        fprintf(stderr, "Private key does not match the public certificate\n");
        abort();
    }
}

int OpenConnection(const char *hostname, int port)
{   int sd;
    struct hostent *host;
    struct sockaddr_in addr;

    if ( (host = gethostbyname(hostname)) == NULL )
    {
        perror(hostname);
        abort();
    }
    sd = socket(PF_INET, SOCK_STREAM, 0);
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = *(long*)(host->h_addr);
    if ( connect(sd, (struct sockaddr*)&addr, sizeof(addr)) != 0 )
    {
        close(sd);
        perror(hostname);
        abort();
    }
    return sd;
}

SSL_CTX* InitCTX(void)
{   SSL_METHOD *method;
    SSL_CTX *ctx;

    OpenSSL_add_all_algorithms();  /* Load cryptos, et.al. */
    SSL_load_error_strings();   /* Bring in and register error messages */
    method = SSLv3_client_method();  /* Create new client-method instance */
    ctx = SSL_CTX_new(method);   /* Create new context */
    if ( ctx == NULL )
    {
        ERR_print_errors_fp(stderr);
        abort();
    }
    return ctx;
}

void ShowCerts(SSL* ssl)
{   X509 *cert;
    char *line;

    cert = SSL_get_peer_certificate(ssl); /* get the server's certificate */
    if ( cert != NULL )
    {
        printf("Server certificates:\n");
        line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
        printf("Subject: %s\n", line);
        free(line);       /* free the malloc'ed string */
        line = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
        printf("Issuer: %s\n", line);
        free(line);       /* free the malloc'ed string */
        X509_free(cert);     /* free the malloc'ed certificate copy */
    }
    else
        printf("No certificates.\n");
}

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[] = "/home/sufi/OpenSSL/myCA/newkey/clientcert.pem";
    char KeyFile[] = "/home/sufi/OpenSSL/myCA/newkey/client.pem";

    SSL_library_init();

    ctx = InitCTX();
    LoadCertificates(ctx, CertFile, KeyFile);
    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 = "client-192.168.1.1\n";

        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);
       
        printf("Received Data from dostuff: \"%s\"\n", buf);
        SSL_free(ssl);        /* release connection state */
    }
    close(server);         /* close socket */
    SSL_CTX_free(ctx);        /* release context */
    return 0;
}


you can create the public and private keys yourself

:cry: :?: