SSL Server cert and client no cert

// ssl_test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

/* serv.cpp  -  Minimal ssleay server for Unix
   30.9.1996, Sampo Kellomaki <[email protected]> */


/* mangled to work with SSLeay-0.9.0b and OpenSSL 0.9.2b
   Simplified to be even more minimal
   12/98 - 4/99 Wade Scholine <[email protected]> */

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

#include <memory.h>
#include <errno.h>
#include <sys/types.h>
#include <winsock2.h>

#include <openssl/rsa.h>       /* SSLeay stuff */
#include <openssl/crypto.h>
//#include <openssl/x509.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/applink.c>

/* define HOME to be dir for key and cert files... */
#define HOME "./"
/* Make these what you want for cert & key files */
#define CERTF  HOME "foo-cert.pem"
#define KEYF  HOME  "foo-cert.pem"


#define CHK_NULL(x) if ((x)==NULL) exit (1)
#define CHK_ERR(err,s) if ((err)==-1) { perror(s); exit(1); }
#define CHK_SSL(err) if ((err)==-1) { ERR_print_errors_fp(stderr); exit(2); }


string GetExePath(void);

int _tmain(int argc, _TCHAR* argv[])
{
  int err;
  int listen_sd;
  int sd;
  struct sockaddr_in sa_serv;
  struct sockaddr_in sa_cli;
  int client_len;
  SSL_CTX* ctx_host; //和客户端的SSL CTX
  SSL_CTX* ctx_client;//和服务端的SSL CTX
  SSL*     ssl_host, *ssl_client;
  //X509*    client_cert;
  char*    str;
  char     *buf;
  SSL_METHOD *meth_host, *meth_client;
  
  const unsigned int buff_size = 0x1000000;
  buf = new char[buff_size];
  if (!buf)
  {
	  exit(-1);
  }
  
  /* SSL preliminaries. We keep the certificate and key with the context. */

  SSL_load_error_strings();
  SSLeay_add_ssl_algorithms();
  meth_host = SSLv23_server_method();

  ctx_host = SSL_CTX_new (meth_host);
  if (!ctx_host) {
    ERR_print_errors_fp(stderr);
    exit(2);
  }
  
  //if (SSL_CTX_use_certificate_file(ctx_host, CERTF, SSL_FILETYPE_PEM) <= 0) {
	 // ERR_print_errors_fp(stderr);
	 // exit(3);
  //}
  //if (SSL_CTX_use_PrivateKey_file(ctx_host, KEYF, SSL_FILETYPE_PEM) <= 0) {
	 // ERR_print_errors_fp(stderr);
	 // exit(4);
  //}

  //if (!SSL_CTX_check_private_key(ctx_host)) {
	 // fprintf(stderr,"Private key does not match the certificate public key\n");
	 // exit(5);
  //}

  //设置服务器的证书
 
  string strDir = GetExePath();
  string strCertFileName = strDir + "\\cert.pem";
  string strKeyFileName = strDir + "\\key.pem";

  err = SSL_CTX_use_certificate_file(ctx_host, strCertFileName.c_str(), SSL_FILETYPE_PEM);
  if (err != 1)
  {
	  printf("SSL_CTX_use_certificate_file: %d", ERR_get_error());
	  return false;
  }

  err = SSL_CTX_use_PrivateKey_file(ctx_host, strKeyFileName.c_str(), SSL_FILETYPE_PEM);
  if (err != 1)
  {
	  printf("SSL_CTX_use_PrivateKey_file: %d", ERR_get_error());
	  return false;
  }

  err = SSL_CTX_check_private_key(ctx_host);
  if (err != 1)
  {
	  printf("SSL_CTX_check_private_key: %d", ERR_get_error());
	  return false;
  }

  /* ----------------------------------------------- */
  /* Prepare TCP socket for receiving connections */


  WSADATA WsaData;

  err = WSAStartup (0x0202, &WsaData);
  if (err == SOCKET_ERROR)
  {
	  exit(-1);
  }
  listen_sd = socket (AF_INET, SOCK_STREAM, 0);  
  CHK_ERR(listen_sd, "socket");
  
  memset (&sa_serv, '\0', sizeof(sa_serv));
  sa_serv.sin_family      = AF_INET;
  sa_serv.sin_addr.s_addr = INADDR_ANY;
  sa_serv.sin_port        = htons (xxxx);          /* Server Port number */
  
  err = bind(listen_sd, (struct sockaddr*) &sa_serv,
	     sizeof (sa_serv));          
  CHK_ERR(err, "bind");
	     
  /* Receive a TCP connection. */
	     
  err = listen (listen_sd, 5);     
  CHK_ERR(err, "listen");
  
  client_len = sizeof(sa_cli);
  sd = accept (listen_sd, (struct sockaddr*) &sa_cli, &client_len);
  CHK_ERR(sd, "accept");
  closesocket(listen_sd);

  printf ("Connection from %lx, port %x\n",
	  sa_cli.sin_addr.s_addr, sa_cli.sin_port);
  
  /* ----------------------------------------------- */
  /* TCP connection is ready. Do server side SSL. */

  ssl_host = SSL_new (ctx_host);                      
  CHK_NULL(ssl_host);
  SSL_set_fd (ssl_host, sd);
  err = SSL_accept (ssl_host);            
  CHK_SSL(err);
  
  /* Get the cipher - opt */
  
  printf ("SSL connection using %s\n", SSL_get_cipher (ssl_host));
  
  /* Get client's certificate (note: beware of dynamic allocation) - opt */

  //client_cert = SSL_get_peer_certificate (ssl);
  //if (client_cert != NULL) {
  //  printf ("Client certificate:\n");
  //  
  //  str = X509_NAME_oneline (X509_get_subject_name (client_cert), 0, 0);
  //  CHK_NULL(str);
  //  printf ("\t subject: %s\n", str);
  //  OPENSSL_free (str);
  //  
  //  str = X509_NAME_oneline (X509_get_issuer_name  (client_cert), 0, 0);
  //  CHK_NULL(str);
  //  printf ("\t issuer: %s\n", str);
  //  OPENSSL_free (str);
  //  
  //  /* We could do all sorts of certificate verification stuff here before
  //     deallocating the certificate. */
  //  
  //  X509_free (client_cert);
  //} else
  //  printf ("Client does not have certificate.\n");

  /* DATA EXCHANGE - Receive message and send reply. */


  /*连接服务器*/
  meth_client = SSLv3_client_method();
  ctx_client = SSL_CTX_new (meth_client);
  if (!ctx_client) {
	  ERR_print_errors_fp(stderr);
	  exit(2);
  }
  SOCKET s_con = socket (AF_INET, SOCK_STREAM, 0);  
  CHK_ERR(s_con, "socket");

  memset (&sa_cli, '\0', sizeof(sa_cli));
  sa_cli.sin_family      = AF_INET;
  sa_cli.sin_addr.s_addr = inet_addr("x.x.x.x");
  sa_cli.sin_port        = htons (xxxx); 

  int n = connect(s_con,  (sockaddr*)&sa_cli, sizeof(sa_cli));
  if (n==SOCKET_ERROR)
  {
	  sa_cli.sin_addr.s_addr = inet_addr("x.x.x.x");
	  n = connect(s_con,  (sockaddr*)&sa_cli, sizeof(sa_cli));
	  if (n==SOCKET_ERROR)
		  exit(-1);
  }
  
  ssl_client = SSL_new (ctx_client);                      
  CHK_NULL(ssl_client);
  SSL_set_fd (ssl_client, s_con);
  if ( SSL_connect(ssl_client)==-1)
  {
	  exit(-1);
  }

  while (1)
  {
	  fd_set fd;

	  FD_ZERO(&fd);
	  FD_SET(sd, &fd);
	  FD_SET(s_con, &fd);

	  timeval time_out;
	  const int ciTimeout = 60; // 总的超时秒数
	  int iCurTimeout = 0;

	  int ret = select(0, &fd, NULL, NULL, &time_out); //检查是否有可读的数据

	  if (0 == ret) //超时
	  {
		  iCurTimeout += time_out.tv_sec;
		  if (iCurTimeout >= ciTimeout)
		  {
			  printf("select timeout");
			  break; // 超时,可能是客户端在等待服务器端先响应。
		  }
		  continue;
	  }
	  else if (SOCKET_ERROR == ret)
	  {
		  printf("err at select: %d", WSAGetLastError());
		  break;
	  }

	  int nReadLen = 0;
	  if (FD_ISSET(sd, &fd))
	  {
		  nReadLen = SSL_read(ssl_host, buf, buff_size);
		  buf[nReadLen] = '\0';
		  printf ("Got %d chars:'%s'\n", nReadLen, buf);
		  SSL_write(ssl_client,buf, nReadLen);
	  } 
	  else if(FD_ISSET(s_con, &fd))
	  {
		  nReadLen = SSL_read(ssl_client, buf, buff_size);
		  buf[nReadLen] = '\0';
		  printf ("Got %d chars:'%s'\n", nReadLen, buf);
		  SSL_write(ssl_host,buf, nReadLen);
	  }
  }
  
  /* Clean up. */

  closesocket(sd);
  SSL_free (ssl_host);
  SSL_CTX_free (ctx_host);

  closesocket(s_con);
  SSL_free (ssl_client);
  SSL_CTX_free (ctx_client);

  delete [] buf;
  return 0;
}
/* EOF - serv.cpp */

string GetExePath(void)
{
	char szFilePath[MAX_PATH + 1]={0};
	GetModuleFileNameA(NULL, szFilePath, MAX_PATH);
	(strrchr(szFilePath, '\\'))[0] = 0; // 删除文件名,只获得路径字串
	string path = szFilePath;

	return path;
}

你可能感兴趣的:(SSL Server cert and client no cert)