Пример #1
0
static void amqp_openssl_bio_init(void) {
  memcpy(&amqp_bio_method, BIO_s_socket(), sizeof(amqp_bio_method));
  BIO_meth_set_write(&amqp_bio_method, amqp_openssl_bio_write);
  BIO_meth_set_read(&amqp_bio_method, amqp_openssl_bio_read);

  bio_initialized = 1;
}
Пример #2
0
Файл: bio.c Проект: CsBela/core
/* NOTE: Unused yet. Commented to avoid warning */
static int hb_BIO_METHOD_ptr_to_id( const BIO_METHOD * p )
{
   int n;

   if(      p == BIO_s_null()       ) n = HB_BIO_METHOD_S_NULL;
#ifndef OPENSSL_NO_FP_API
   else if( p == BIO_s_file()       ) n = HB_BIO_METHOD_S_FILE;
#endif
   else if( p == BIO_s_mem()        ) n = HB_BIO_METHOD_S_MEM;
   else if( p == BIO_s_socket()     ) n = HB_BIO_METHOD_S_SOCKET;
   else if( p == BIO_s_connect()    ) n = HB_BIO_METHOD_S_CONNECT;
   else if( p == BIO_s_accept()     ) n = HB_BIO_METHOD_S_ACCEPT;
   else if( p == BIO_s_fd()         ) n = HB_BIO_METHOD_S_FD;
#if 0 /* BIO_s_log() isn't exported via implibs on Windows at version 0.9.8k. [vszakats] */
#ifndef OPENSSL_SYS_OS2
   else if( p == BIO_s_log()        ) n = HB_BIO_METHOD_S_LOG;
#endif
#endif
   else if( p == BIO_s_bio()        ) n = HB_BIO_METHOD_S_BIO;
#ifndef OPENSSL_NO_DGRAM
   else if( p == BIO_s_datagram()   ) n = HB_BIO_METHOD_S_DATAGRAM;
#endif
   else if( p == BIO_f_null()       ) n = HB_BIO_METHOD_F_NULL;
   else if( p == BIO_f_buffer()     ) n = HB_BIO_METHOD_F_BUFFER;
#ifdef OPENSSL_SYS_VMS
   else if( p == BIO_f_linebuffer() ) n = HB_BIO_METHOD_F_LINEBUFFER;
#endif
   else if( p == BIO_f_nbio_test()  ) n = HB_BIO_METHOD_F_NBIO_TEST;
   else                               n = HB_BIO_METHOD_UNSUPPORTED;

   return n;
}
Пример #3
0
Файл: bio.c Проект: CsBela/core
static BIO_METHOD * hb_BIO_METHOD_par( int iParam )
{
   BIO_METHOD * p;

   switch( hb_parni( iParam ) )
   {
      case HB_BIO_METHOD_S_NULL:        p = BIO_s_null();       break;
#ifndef OPENSSL_NO_FP_API
      case HB_BIO_METHOD_S_FILE:        p = BIO_s_file();       break;
#endif
      case HB_BIO_METHOD_S_MEM:         p = BIO_s_mem();        break;
      case HB_BIO_METHOD_S_SOCKET:      p = BIO_s_socket();     break;
      case HB_BIO_METHOD_S_CONNECT:     p = BIO_s_connect();    break;
      case HB_BIO_METHOD_S_ACCEPT:      p = BIO_s_accept();     break;
      case HB_BIO_METHOD_S_FD:          p = BIO_s_fd();         break;
#if 0 /* BIO_s_log() isn't exported via implibs on Windows at version 0.9.8k. [vszakats] */
#ifndef OPENSSL_SYS_OS2
      case HB_BIO_METHOD_S_LOG:         p = BIO_s_log();        break;
#endif
#endif
      case HB_BIO_METHOD_S_BIO:         p = BIO_s_bio();        break;
#ifndef OPENSSL_NO_DGRAM
      case HB_BIO_METHOD_S_DATAGRAM:    p = BIO_s_datagram();   break;
#endif
      case HB_BIO_METHOD_F_NULL:        p = BIO_f_null();       break;
      case HB_BIO_METHOD_F_BUFFER:      p = BIO_f_buffer();     break;
#ifdef OPENSSL_SYS_VMS
      case HB_BIO_METHOD_F_LINEBUFFER:  p = BIO_f_linebuffer(); break;
#endif
      case HB_BIO_METHOD_F_NBIO_TEST:   p = BIO_f_nbio_test();  break;
      default:                          p = NULL;
   }

   return p;
}
Пример #4
0
BIO *BIO_new_socket(struct socket *sock, int close_flag)
	{
	BIO *ret;

	ret=BIO_new(BIO_s_socket());
	if (ret == NULL) return(NULL);
	BIO_set_sock(ret,sock,close_flag);
	return(ret);
	}
Пример #5
0
BIO *BIO_new_socket(int fd, int close_flag)
	{
	BIO *ret;

	ret=BIO_new(BIO_s_socket());
	if (ret == NULL) return(NULL);
	BIO_set_fd(ret,fd,close_flag);
	return(ret);
	}
Пример #6
0
/* validate the certifcate stored in 'data' by querying the ocsp-responder */
int
ocsp_validate_cert(struct iked *env, struct iked_static_id *id,
    void *data, size_t len, struct iked_sahdr sh, uint8_t type)
{
	struct iked_ocsp_entry	*ioe;
	struct iked_ocsp	*ocsp;
	BIO			*rawcert = NULL, *bissuer = NULL;
	X509			*cert = NULL, *issuer = NULL;

	if ((ioe = calloc(1, sizeof(*ioe))) == NULL)
		return (-1);
	if ((ocsp = calloc(1, sizeof(*ocsp))) == NULL) {
		free(ioe);
		return (-1);
	}

	ocsp->ocsp_env = env;
	ocsp->ocsp_sh = sh;
	ocsp->ocsp_type = type;

	if ((rawcert = BIO_new_mem_buf(data, len)) == NULL ||
	    (cert = d2i_X509_bio(rawcert, NULL)) == NULL ||
	    (bissuer = BIO_new_file(IKED_OCSP_ISSUER, "r")) == NULL ||
	    (issuer = PEM_read_bio_X509(bissuer, NULL, NULL, NULL)) == NULL ||
	    (ocsp->ocsp_cbio = BIO_new(BIO_s_socket())) == NULL ||
	    (ocsp->ocsp_req = OCSP_REQUEST_new()) == NULL ||
	    !(ocsp->ocsp_id = OCSP_cert_to_id(NULL, cert, issuer)) ||
	    !OCSP_request_add0_id(ocsp->ocsp_req, ocsp->ocsp_id))
		goto err;

	BIO_free(rawcert);
	BIO_free(bissuer);
	X509_free(cert);
	X509_free(issuer);

	ioe->ioe_ocsp = ocsp;
	TAILQ_INSERT_TAIL(&env->sc_ocsp, ioe, ioe_entry);

	/* request connection to ocsp-responder */
	proc_compose_imsg(&env->sc_ps, PROC_PARENT, -1,
	    IMSG_OCSP_FD, -1, NULL, 0);
	return (0);

 err:
	ca_sslerror(__func__);
	free(ioe);
	if (rawcert != NULL)
		BIO_free(rawcert);
	if (cert != NULL)
		X509_free(cert);
	if (bissuer != NULL)
		BIO_free(bissuer);
	if (issuer != NULL)
		X509_free(issuer);
	ocsp_validate_finish(ocsp, 0);	/* failed */
	return (-1);
}
Пример #7
0
BIO *BIO_new_socket(int fd, int close_flag) {
  BIO *ret;

  ret = BIO_new(BIO_s_socket());
  if (ret == NULL) {
    return NULL;
  }
  BIO_set_fd(ret, fd, close_flag);
  return ret;
}
Пример #8
0
/*
  Initializes SSL and allocate global
  context SSL_context

  SYNOPSIS
    my_ssl_start
      mysql        connection handle

  RETURN VALUES
    0  success
    1  error
*/
int ma_tls_start(char *errmsg, size_t errmsg_len)
{
  int rc= 1;
  if (ma_tls_initialized)
    return 0;

  /* lock mutex to prevent multiple initialization */
  pthread_mutex_init(&LOCK_openssl_config,MY_MUTEX_INIT_FAST);
  pthread_mutex_lock(&LOCK_openssl_config);
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
#else
  if (ssl_thread_init())
  {
    strncpy(errmsg, "Not enough memory", errmsg_len);
    goto end;
  }
  SSL_library_init();

#if SSLEAY_VERSION_NUMBER >= 0x00907000L
  OPENSSL_config(NULL);
#endif
#endif
  /* load errors */
  SSL_load_error_strings();
  /* digests and ciphers */
  OpenSSL_add_all_algorithms();
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
  if (!(SSL_context= SSL_CTX_new(TLS_client_method())))
#else
  if (!(SSL_context= SSL_CTX_new(SSLv23_client_method())))
#endif
  {
    ma_tls_get_error(errmsg, errmsg_len);
    goto end;
  }
#ifdef HAVE_TLS_SESSION_CACHE
  SSL_CTX_set_session_cache_mode(SSL_context, SSL_SESS_CACHE_CLIENT);
  ma_tls_sessions= (MA_SSL_SESSION *)calloc(1, sizeof(struct st_ma_tls_session) * ma_tls_session_cache_size);
  SSL_CTX_sess_set_new_cb(SSL_context, ma_tls_session_cb);
  SSL_CTX_sess_set_remove_cb(SSL_context, ma_tls_remove_session_cb);
#endif
  disable_sigpipe();
#if OPENSSL_USE_BIOMETHOD
  memcpy(&ma_BIO_method, BIO_s_socket(), sizeof(BIO_METHOD));
  ma_BIO_method.bread= ma_bio_read;
  ma_BIO_method.bwrite= ma_bio_write;
#endif
  rc= 0;
  ma_tls_initialized= TRUE;
end:
  pthread_mutex_unlock(&LOCK_openssl_config);
  return rc;
}
Пример #9
0
static BIO_METHOD *
my_BIO_s_socket(void)
{
	if (!my_bio_initialized)
	{
		memcpy(&my_bio_methods, BIO_s_socket(), sizeof(BIO_METHOD));
		my_bio_methods.bread = my_sock_read;
		my_bio_methods.bwrite = my_sock_write;
		my_bio_initialized = true;
	}
	return &my_bio_methods;
}
Пример #10
0
void SecureSocketImpl::connectSSL(bool performHandshake)
{
	poco_assert (!_pSSL);
	poco_assert (_pSocket->initialized());
	
	BIO* pBIO = BIO_new(BIO_s_socket());
	if (!pBIO) throw SSLException("Cannot create SSL BIO object");
	BIO_set_fd(pBIO, static_cast<int>(_pSocket->sockfd()), BIO_NOCLOSE);

	_pSSL = SSL_new(_pContext->sslContext());
	if (!_pSSL) 
	{
		BIO_free(pBIO);
		throw SSLException("Cannot create SSL object");
	}
	SSL_set_bio(_pSSL, pBIO, pBIO);
	
#if OPENSSL_VERSION_NUMBER >= 0x0908060L && !defined(OPENSSL_NO_TLSEXT)
	if (!_peerHostName.empty())
	{
		SSL_set_tlsext_host_name(_pSSL, _peerHostName.c_str());
	}
#endif

	if (_pSession)
	{
		SSL_set_session(_pSSL, _pSession->sslSession());
	}
	
	try
	{
		if (performHandshake && _pSocket->getBlocking())
		{
			int ret = SSL_connect(_pSSL);
			handleError(ret);
			verifyPeerCertificate();
		}
		else
		{
			SSL_set_connect_state(_pSSL);
			_needHandshake = true;
		}
	}
	catch (...)
	{
		SSL_free(_pSSL);
		_pSSL = 0;
		throw;
	}
}
Пример #11
0
SSL *
ssl_read_ssl(FILE * fp, int sock)
{
  SSL *ssl;
  BIO *bio;

  bio = BIO_new(BIO_s_socket());
  fread(bio, sizeof(BIO), 1, fp);
  ssl = SSL_new(ctx);
  fread(ssl, sizeof(SSL), 1, fp);
  SSL_set_ssl_method(ssl, SSLv23_server_method());
  SSL_set_bio(ssl, bio, bio);
  return ssl;
}
Пример #12
0
BIO *BIO_new_fd(int fd,int close_flag)
#endif
	{
	BIO *ret;

#ifndef BIO_FD
	ret=BIO_new(BIO_s_socket());
#else
	ret=BIO_new(BIO_s_fd());
#endif
	if (ret == NULL) return(NULL);
	BIO_set_fd(ret,fd,close_flag);
	return(ret);
	}
Пример #13
0
BIO_METHOD* amqp_openssl_bio(void) {
#ifdef AMQP_USE_AMQP_BIO
  if (!bio_initialized) {
#ifdef ENABLE_THREAD_SAFETY
    pthread_once(&bio_init_once, amqp_openssl_bio_init);
#else
    amqp_openssl_bio_init();
#endif /* ifndef ENABLE_THREAD_SAFETY */
  }

  return &amqp_bio_method;
#else
  return BIO_s_socket();
#endif
}
Пример #14
0
connection::connection(int socketin,SSL_CTX* ctx,const unsigned int timeoutSec,const unsigned int timeoutMic)
{
	socket = socketin;
	timeout.tv_sec = timeoutSec;
	timeout.tv_usec = timeoutMic;
	int ssl_int;
	if(setsockopt(socket,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast<char*>(&timeout),sizeof(timeout)) < 0)
		throw connection_exception("Set sock opt failed");
	ssl = SSL_new(ctx);
	bio = BIO_new(BIO_s_socket());
	BIO_set_fd(bio,socket,BIO_NOCLOSE);
	SSL_set_bio(ssl,bio,bio);
	if((ssl_int = SSL_accept(ssl)) < 1)
	{
		throw connection_exception("SSL Accept failed.");	
	}

}
Пример #15
0
void SecureSocketImpl::acceptSSL()
{
	poco_assert (!_pSSL);

	BIO* pBIO = BIO_new(BIO_s_socket());
	if (!pBIO) throw SSLException("Cannot create BIO object");
	BIO_set_fd(pBIO, static_cast<int>(_pSocket->sockfd()), BIO_NOCLOSE);

	_pSSL = SSL_new(_pContext->sslContext());
	if (!_pSSL)
	{
		BIO_free(pBIO);
		throw SSLException("Cannot create SSL object");
	}
	SSL_set_bio(_pSSL, pBIO, pBIO);
	SSL_set_accept_state(_pSSL);
	_needHandshake = true;
}
Пример #16
0
static BIO_METHOD *
my_BIO_s_socket(void)
{
	if (!my_bio_methods)
	{
		BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
#ifdef HAVE_BIO_METH_NEW
		int			my_bio_index;

		my_bio_index = BIO_get_new_index();
		if (my_bio_index == -1)
			return NULL;
		my_bio_methods = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
		if (!my_bio_methods)
			return NULL;
		if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
			!BIO_meth_set_read(my_bio_methods, my_sock_read) ||
			!BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
			!BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
			!BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
			!BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
			!BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
			!BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
		{
			BIO_meth_free(my_bio_methods);
			my_bio_methods = NULL;
			return NULL;
		}
#else
		my_bio_methods = malloc(sizeof(BIO_METHOD));
		if (!my_bio_methods)
			return NULL;
		memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
		my_bio_methods->bread = my_sock_read;
		my_bio_methods->bwrite = my_sock_write;
#endif
	}
	return my_bio_methods;
}
Пример #17
0
HybridSslConnection*
hybrid_ssl_connect_with_fd(gint sk,    ssl_callback func, gpointer user_data)
{
    gint                 l;
    SSL                 *ssl;
    BIO                 *sbio;
    BIO                 *buf_io;
    BIO                 *ssl_bio;
    SSL_CTX             *ssl_ctx;
    HybridSslConnection *ssl_conn;

    SSL_load_error_strings();
    SSL_library_init();

    if (!(ssl_ctx = SSL_CTX_new(TLSv1_client_method()))) {

        hybrid_debug_error("ssl", "initialize SSL CTX: %s",
                           ERR_reason_error_string(ERR_get_error()));
        return NULL;
    }

    if (!(ssl = ssl_new_with_certs(ssl_ctx))) {
        return NULL;
    }

    if (!SSL_set_fd(ssl, sk)) {
        hybrid_debug_error("ssl", "add ssl to tcp socket:%s",
                           ERR_reason_error_string(ERR_get_error()));
        return NULL;
    }

    sbio = BIO_new(BIO_s_socket());
    BIO_set_fd(sbio, sk, BIO_NOCLOSE);
    SSL_set_bio(ssl, sbio, sbio);

    SSL_set_connect_state(ssl);

 reconnect:
    l = SSL_connect(ssl);

    switch (SSL_get_error(ssl, l)) {
    case SSL_ERROR_NONE:
        goto ssl_conn_sk_ok;
    case SSL_ERROR_WANT_WRITE:
    case SSL_ERROR_WANT_READ:
        usleep(100);
        goto reconnect;
    case SSL_ERROR_SYSCALL:
    case SSL_ERROR_WANT_X509_LOOKUP:
    case SSL_ERROR_ZERO_RETURN:
    case SSL_ERROR_SSL:
    default:
        hybrid_debug_error("ssl", "ssl hand-shake error:%s",
                           ERR_reason_error_string(ERR_get_error()));
        return NULL;
    }

ssl_conn_sk_ok:

    if (HYBRID_OK != ssl_verify_certs(ssl)) {
        return NULL;
    }

    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

    buf_io = BIO_new(BIO_f_buffer());
    ssl_bio = BIO_new(BIO_f_ssl());

    BIO_set_ssl(ssl_bio, ssl, BIO_NOCLOSE);
    BIO_push(buf_io, ssl_bio);

    ssl_conn = g_new0(HybridSslConnection, 1);

    ssl_conn->sk        = sk;
    ssl_conn->ssl       = ssl;
    ssl_conn->ssl_ctx   = ssl_ctx;
    ssl_conn->conn_cb   = func;
    ssl_conn->conn_data = user_data;
    ssl_conn->rbio      = buf_io;
    ssl_conn->wbio      = sbio;

    if (func) {
        func(ssl_conn, user_data);
    }

    return ssl_conn;
}
SSL* SDMMD_lockssl_handshake(SDMMD_lockdown_conn *lockdown_conn, CFTypeRef hostCert, CFTypeRef deviceCert, CFTypeRef hostPrivKey, uint32_t num) {
	SSL *ssl = NULL;
	SSL_CTX *sslCTX = NULL;
	sdmmd_return_t result = 0x0;
	BIO_METHOD *bioMethod = BIO_s_socket();
	BIO *bioSocket = BIO_new(bioMethod);
	if (bioSocket) {
		BIO_set_fd(bioSocket, lockdown_conn->connection, 0);
		X509 *cert = SDMMD__decode_certificate(hostCert);
		if (cert == 0) {
			printf("_create_ssl_context: Could not certificate.\n");
		}
		RSA *rsa = NULL;
		BIO *dataBIO = SDMMD__create_bio_from_data(hostPrivKey);
		if (dataBIO == 0) {
			printf("_create_ssl_context: Could not decode host private key.\n");
			if (cert) {
				X509_free(cert);
				result = 0x0;
			}
		} else {
			PEM_read_bio_RSAPrivateKey(dataBIO, &rsa, 0x0, 0x0);
			BIO_free(dataBIO);
			if (rsa) {
				if (hostCert) {
					sslCTX = SSL_CTX_new(SSLv3_method());
					if (sslCTX) {
						result = SSL_CTX_use_certificate(sslCTX, cert);
						if (result == 0)
							printf("_create_ssl_context: Could not set certificate.\n");
						result = SSL_CTX_use_RSAPrivateKey(sslCTX, rsa);
						if (result == 0)
							printf("_create_ssl_context: Could not set private key.\n");
					} else {
						printf("_create_ssl_context: Could not create SSLv3 context.\n");
					}
				}
				RSA_free(rsa);
				if (cert)
					X509_free(cert);
				if (sslCTX) {
					ssl = SSL_new(sslCTX);
					if (ssl) {
						if (num) {
							SSL_set_connect_state(ssl);
						} else {
							SSL_set_accept_state(ssl);
						}
						SSL_set_verify(ssl, 0x3, SDMMD__ssl_verify_callback);
						SSL_set_verify_depth(ssl, 0x0);
						SSL_set_bio(ssl, bioSocket, bioSocket);
						SSL_set_ex_data(ssl, SDMMobileDevice->peer_certificate_data_index, (void*)deviceCert);
						result = SSL_do_handshake(ssl);
						if (result == 1) {
							SSL_CTX_free(sslCTX);
						} else {
							uint32_t err = SSL_get_error(ssl, result);
							if (err) {
								char *reason = SDMMD_ssl_strerror(ssl, err);
								printf("lockssl_handshake: SSL handshake fatal lower level error %d: %s.\n", err, reason);
							} else {
								char *reason = SDMMD_ssl_strerror(ssl, 0x0);
								printf("lockssl_handshake: SSL handshake controlled failure %d: %s.\n", err, reason);
							}
							SSL_free(ssl);
						}
					} else {
						printf("_create_ssl: Could not create SSL thing.\n");
					}
				}
			} else {
				printf("_create_ssl_context: Could not decode private key.\n");
				if (cert) {
					X509_free(cert);
					result = 0x0;
				}
			}
		}
	} else {
		printf("lockssl_handshake: Could not create SSL bio.\n");
	}
	return ssl;
}
Пример #19
0
BSecureSocket::Private::Private()
	:
	fSSL(NULL),
	fBIO(BIO_new(BIO_s_socket()))
{
}
Пример #20
0
/*
 * S E M A P H O R E
 */
static void handleDbpSession(int connFd) {
	
	CommHndl conn_fd;
   	struct sembuf procReleaseUnDo = {0,1,SEM_UNDO};

   	int r,b2,c, by=0, h;
 
   	char buffer[1024],bc[1];
   	char buffer2[500];
   	char *response=NULL; 	//Fehlermeldung reinschreiben und an Client zurückschicken.
   					//Vermutlich später nicht mehr notwendig!!
   	char *header=NULL;char *payload;
   	int nbytes;
      
   
   _SFCB_ENTER(TRACE_DBPDAEMON, "handledbpRequest");
   _SFCB_TRACE(1, ("--- Forking sql handler"));
   		
   // printf("dbpProcSem %p dbpProcId: %d hMax: %d doFork: %d\n",dbpProcSem,dbpProcId,hMax,doFork);
   // printf("dbpProcId: %d hMax: %d doFork: %d\n",dbpProcId,hMax,doFork);
    if (doFork) {
      	semAcquire(dbpWorkSem,0);
      	semAcquire(dbpProcSem,0);
      	for (dbpProcId=0; dbpProcId<hMax; dbpProcId++)
        	if (semGetValue(dbpProcSem,dbpProcId+1)==0) break;
        printf("dbpProcId: %d hMax: %d\n",dbpProcId,hMax);
      	procReleaseUnDo.sem_num=dbpProcId+1; 
         
      	r = fork();

      	if (r==0) {
         	currentProc=getpid();
         	processName="CIMSQL-Processor";
         	semRelease(dbpProcSem,0);
         	semAcquireUnDo(dbpProcSem,0);
         	semReleaseUnDo(dbpProcSem,dbpProcId+1);
         	semRelease(dbpWorkSem,0);

         	if (sfcbSSLMode) {
#if defined USE_SSL
            	conn_fd.socket=-2;
            	conn_fd.bio=BIO_new(BIO_s_socket());
            	BIO_set_fd(conn_fd.bio,connFd,BIO_CLOSE);
            	if (!(conn_fd.ssl = SSL_new(ctx)))
               		intSSLerror("Error creating SSL context");
            	SSL_set_bio(conn_fd.ssl, conn_fd.bio, conn_fd.bio);
            	if (SSL_accept(conn_fd.ssl) <= 0)
               		intSSLerror("Error accepting SSL connection");
#endif
         	}
         	else {
            	conn_fd.socket=connFd;
#if defined USE_SSL
            	conn_fd.bio=NULL;
            	conn_fd.ssl=NULL;
#endif
         	}
      	}
      	else if (r>0) {
         	running++;
         	_SFCB_EXIT();
      	}
   	}
   	else r = 0;

  	if (r < 0) {
      	char *emsg=strerror(errno);
      	mlogf(M_ERROR,M_SHOW,"--- fork handler: %s\n",emsg);
      	exit(1);
   	}

   	if (r == 0) {
      	if (doFork) {
         	_SFCB_TRACE(1,("--- Forked sql handler %d", currentProc))
         	resultSockets=sPairs[hBase+dbpProcId];
      	}

      	_SFCB_TRACE(1,("--- Started sql handler %d %d", currentProc,
                   resultSockets.receive));

      	if (getenv("SFCB_PAUSE_HTTP")) for (;;) {
        	fprintf(stderr,"-#- Pausing - pid: %d\n",currentProc);
         	sleep(5);
      	}   
       
      	conn_fd.socket=connFd;
#if defined USE_SSL
      	conn_fd.bio=NULL;
      	conn_fd.ssl=NULL;
#endif
    	for(;;){ 
     	//c onn_fd.socket=connFd;

     	// doHttpRequest(conn_fd);
			nbytes = read (connFd, buffer, HEADER);
			header = (char *) malloc(nbytes);//sowas wie \n Steuerzeichen
			strncpy(header,buffer,nbytes);
   			header[nbytes]=0;
			h = atoi(header);
				printd("Ein Client h: %d header: %s nbytes: %d\n",h,header,nbytes);
			//Sonderfall, noch nicht eingeloggt
			if(by&h){
				//login
				nbytes = read(connFd, buffer, 2);
				c = atoi((char*)&buffer);
				if(c==CONNECT){ 
					printd("Ein Client hat sich korrekt angemeldet\n");
					response = "1 1 1\n";//"Sie sind angemeldet. Warte auf Anfragen:\n";
					write(connFd, response , strlen(response));
					by=0;
					h=CONTINUE;//dummy, um switch sofort zu verlassen
				}
				else{
					printd("Ein Client hat sich NICHT korrekt angemeldet %d\n",c);
					response = "1 1 0\n";//"Sie sind nicht angemeldet. Auf wiedersehen.\n";
					write(connFd, response , strlen(response));
					break;
				} 
				while((nbytes = read(connFd, bc, 1))>0)//
	  				if(bc[0]=='\n')
	  					break;
			}
			if(by){
				printd("Ein Client hat sich NICHT korrekt angemeldet %d\n",h);
				response = "1 1 0\n";//"Sie sind nicht angemeldet. Auf wiedersehen.\n";
				write(connFd, response , strlen(response));
				break;	
			}
			switch(h){
				case CONTINUE: break;
				case PROTOCOL: {
					nbytes = read(connFd, buffer, 2);
					c = atoi((char*)&buffer);
					
					//Pipe leersaugen
					while((nbytes = read(connFd, bc, 1))>0)//
	      				if(bc[0]=='\n')
	      					break;
						
						
						if(c==CONNECT){ 
						   	response = "1 1 0\n"; //"Sie sind bereits angemeldet, Operation wird ignoriert:\n";
							write(connFd, response , strlen(response));
						}
						else if(c==LOGOUT){
							printd("Der Client hat die Verbindung beendet\n");
					   		response = "1 2 1\n";//"By\n";
				    		write(connFd, response ,strlen(response));
				    		by=1; 
						}
						else{
							b2 = sprintf(buffer2,"%d %d %d",1,c,0);//sprintf(buffer2, "Syntxfehler: Operation %d ist keine Protokolloperation\n",c);
							printd("%s",buffer2);
	   						write(connFd, buffer2 , b2);
						}
					break;	
				}
				case SQL:
					while((nbytes = read(connFd, buffer, 1024))>0){
						if(buffer[nbytes-1]=='\n')
							break;
						//falls Anweisung laenerg als 1024, muss buffer mit vorgaengerbuffer konkadiniert werden. vgl. adrian		
					}
					// abschließendes $ finden:
					
					//printd("SQL: %d\n",nbytes);
					nbytes--;
					while((nbytes>0) && (buffer[nbytes]!='$'))
						nbytes--;
					//printf("malloc %d bytes",nbytes);
					payload = (char *) malloc(nbytes+1+1);
					
					//ein \n voranstellen, yyerror()s wegen
					//*payload = '\n';
					strcpy(payload,"\n");
					strncat(payload,buffer,nbytes);
					
					response = processSQLQuery(payload,conn_fd); //--> Datenstruktur, in die das Statement reinkommt
					
					free(payload);payload=NULL;	
					//ResultMetaData
					
					
					write(connFd, response , strlen(response)); 
					free(response);response=NULL;
					
					break;
				case META:  
					nbytes = read(connFd, buffer, 2);
					c = atoi((char*)&buffer);
					if(c==METADB){
						response = (char *) malloc(strlen(metaDB)+7);
						response = strcpy(response,"3 1 1\n");
						response = strcat(response,metaDB);
						write(connFd, response , strlen(response));
						free(response);
						break;
					}
					
					if(c==TABLES||c==STABLES||c==KEYS||c==COLS){
					  //printf("UND los\n");
						
						while((nbytes = read(connFd, buffer, 1024))>0){
							if(buffer[nbytes-1]=='\n')
								break;
							//falls Anweisung laenerg als 1024, muss buffer mit vorgaengerbuffer konkadiniert werden. vgl. adrian		
						}
						// abschließendes $ finden:
					
						printd("SQL: %d\n",nbytes);
						nbytes--;
						while((nbytes>0) && (buffer[nbytes]!='$'))
							nbytes--;
						//printf("malloc %d bytes",nbytes);
						
						buffer[nbytes] = 0;
						if(nbytes==0)
							payload = NULL;
						else{
							payload = (char *) malloc(nbytes+1);
							strcpy(payload,buffer);
							//printd(">%s< %d\n",payload,c);
						}
						if(c==TABLES)
							response = processMetaTables(payload,"root/cimv2");
						else if(c==STABLES)
							response = processSuperTables(payload,"root/cimv2");
						else if(c==KEYS)
							response = processKeyTable(payload,"root/cimv2");
						else if(c==COLS){
							char *arg2 = strstr(payload,"::");
							
							char *arg1 = strtok(payload,"::");
							//printf("lllllll\n");
							//printf(">%s< >%s< >%s< >%s<\n",payload,arg2,arg1,arg2+2);
							response = processMetaColumns(arg1,arg2+2,"root/cimv2");
							//printf("zurück\n");
						}
						//printf(">>%s<<",response);
						free(payload);payload=NULL;
						write(connFd, response , strlen(response));
						//free(response);
						//dieses free tut nicht, weil irgendwo anders was nicht stimmt!!!
						break;	
					}
					break;
				case SPOOLIN: break;
				case SPOOLOUT: break;
				default: 
					printd("Unbekannter Befehl: \"%s\"\n",header);
					b2 = sprintf(buffer2,"Fehler: unbekannter Befehl:  %s \n", header);
					//strncpy(response,buffer2,b2);
				
	    			//response = "Fehler: Unbekannter Befehl\n";
	    			write(connFd, buffer2 , b2);
	    			break;
				
				
			}
	     	free(header);
	      	if(by)
	      		break;
      	}
      
      
     	if (!doFork) return;

      	_SFCB_TRACE(1, ("--- SQL handler exiting %d", currentProc));
      	printf("--- SQL handler exiting %d\n", currentProc);
      	dumpTiming(currentProc);
      	exit(0);
   }
        
    
}
Пример #21
0
 idevice_error_t idevice_connection_enable_ssl(idevice_connection_t connection)
{
	if (!connection || connection->ssl_data)
		return IDEVICE_E_INVALID_ARG;

	idevice_error_t ret = IDEVICE_E_SSL_ERROR;
	uint32_t return_me = 0;
	plist_t pair_record = NULL;

	userpref_read_pair_record(connection->udid, &pair_record);
	if (!pair_record) {
		debug_info("ERROR: Failed enabling SSL. Unable to read pair record for udid %s.", connection->udid);
		return ret;
	}

#ifdef HAVE_OPENSSL
	key_data_t root_cert = { NULL, 0 };
	key_data_t root_privkey = { NULL, 0 };

	pair_record_import_crt_with_name(pair_record, USERPREF_ROOT_CERTIFICATE_KEY, &root_cert);
	pair_record_import_key_with_name(pair_record, USERPREF_ROOT_PRIVATE_KEY_KEY, &root_privkey);

	if (pair_record)
		plist_free(pair_record);
	/* Set up OpenSSL */
	if (openssl_init_done == 0) {
		SSL_library_init();
		openssl_init_done = 1;
	}
	BIO *ssl_bio = BIO_new(BIO_s_socket());
	if (!ssl_bio) {
		debug_info("ERROR: Could not create SSL bio.");
		return ret;
	}
	BIO_set_fd(ssl_bio, (int)(long)connection->data, BIO_NOCLOSE);

	//SSL_CTX *ssl_ctx = SSL_CTX_new(SSLv3_method());
	SSL_CTX *ssl_ctx = SSL_CTX_new(SSLv3_client_method());
	if (ssl_ctx == NULL) {
		debug_info("ERROR: Could not create SSL context.");
		BIO_free(ssl_bio);
		return ret;
	}

	BIO* membp;
	X509* rootCert = NULL;
	membp = BIO_new_mem_buf(root_cert.data, root_cert.size);
	PEM_read_bio_X509(membp, &rootCert, NULL, NULL);
	BIO_free(membp);
	if (SSL_CTX_use_certificate(ssl_ctx, rootCert) != 1) {
		debug_info("WARNING: Could not load RootCertificate");
	}
	X509_free(rootCert);
	free(root_cert.data);

	RSA* rootPrivKey = NULL;
	membp = BIO_new_mem_buf(root_privkey.data, root_privkey.size);
	PEM_read_bio_RSAPrivateKey(membp, &rootPrivKey, NULL, NULL);
	BIO_free(membp);
	if (SSL_CTX_use_RSAPrivateKey(ssl_ctx, rootPrivKey) != 1) {
		debug_info("WARNING: Could not load RootPrivateKey");
	}
	RSA_free(rootPrivKey);
	free(root_privkey.data);

	SSL *ssl = SSL_new(ssl_ctx);
	if (!ssl) {
		debug_info("ERROR: Could not create SSL object");
		BIO_free(ssl_bio);
		SSL_CTX_free(ssl_ctx);
		return ret;
	}
	SSL_set_connect_state(ssl);
	SSL_set_verify(ssl, 0, ssl_verify_callback);
	SSL_set_bio(ssl, ssl_bio, ssl_bio);

	return_me = SSL_do_handshake(ssl);
	if (return_me != 1) {
		debug_info("ERROR in SSL_do_handshake: %s", ssl_error_to_string(SSL_get_error(ssl, return_me)));
		SSL_free(ssl);
		SSL_CTX_free(ssl_ctx);
	} else {
		ssl_data_t ssl_data_loc = (ssl_data_t)malloc(sizeof(struct ssl_data_private));
		ssl_data_loc->session = ssl;
		ssl_data_loc->ctx = ssl_ctx;
		connection->ssl_data = ssl_data_loc;
		ret = IDEVICE_E_SUCCESS;
		debug_info("SSL mode enabled, cipher: %s", SSL_get_cipher(ssl));
	}
	/* required for proper multi-thread clean up to prevent leaks */
#ifdef HAVE_ERR_REMOVE_THREAD_STATE
	ERR_remove_thread_state(NULL);
#else
	ERR_remove_state(0);
#endif
#else
	ssl_data_t ssl_data_loc = (ssl_data_t)malloc(sizeof(struct ssl_data_private));

	/* Set up GnuTLS... */
	debug_info("enabling SSL mode");
	errno = 0;
	gnutls_certificate_allocate_credentials(&ssl_data_loc->certificate);
	gnutls_certificate_client_set_retrieve_function(ssl_data_loc->certificate, internal_cert_callback);
	gnutls_init(&ssl_data_loc->session, GNUTLS_CLIENT);
	gnutls_priority_set_direct(ssl_data_loc->session, "NONE:+VERS-SSL3.0:+ANON-DH:+RSA:+AES-128-CBC:+AES-256-CBC:+SHA1:+MD5:+COMP-NULL", NULL);
	gnutls_credentials_set(ssl_data_loc->session, GNUTLS_CRD_CERTIFICATE, ssl_data_loc->certificate);
	gnutls_session_set_ptr(ssl_data_loc->session, ssl_data_loc);

	gnutls_x509_crt_init(&ssl_data_loc->root_cert);
	gnutls_x509_crt_init(&ssl_data_loc->host_cert);
	gnutls_x509_privkey_init(&ssl_data_loc->root_privkey);
	gnutls_x509_privkey_init(&ssl_data_loc->host_privkey);

	pair_record_import_crt_with_name(pair_record, USERPREF_ROOT_CERTIFICATE_KEY, ssl_data_loc->root_cert);
	pair_record_import_crt_with_name(pair_record, USERPREF_HOST_CERTIFICATE_KEY, ssl_data_loc->host_cert);
	pair_record_import_key_with_name(pair_record, USERPREF_ROOT_PRIVATE_KEY_KEY, ssl_data_loc->root_privkey);
	pair_record_import_key_with_name(pair_record, USERPREF_HOST_PRIVATE_KEY_KEY, ssl_data_loc->host_privkey);

	if (pair_record)
		plist_free(pair_record);

	debug_info("GnuTLS step 1...");
	gnutls_transport_set_ptr(ssl_data_loc->session, (gnutls_transport_ptr_t)connection);
	debug_info("GnuTLS step 2...");
	gnutls_transport_set_push_function(ssl_data_loc->session, (gnutls_push_func) & internal_ssl_write);
	debug_info("GnuTLS step 3...");
	gnutls_transport_set_pull_function(ssl_data_loc->session, (gnutls_pull_func) & internal_ssl_read);
	debug_info("GnuTLS step 4 -- now handshaking...");
	if (errno) {
		debug_info("WARNING: errno says %s before handshake!", strerror(errno));
	}
	return_me = gnutls_handshake(ssl_data_loc->session);
	debug_info("GnuTLS handshake done...");

	if (return_me != GNUTLS_E_SUCCESS) {
		internal_ssl_cleanup(ssl_data_loc);
		free(ssl_data_loc);
		debug_info("GnuTLS reported something wrong.");
		gnutls_perror(return_me);
		debug_info("oh.. errno says %s", strerror(errno));
	} else {
		connection->ssl_data = ssl_data_loc;
		ret = IDEVICE_E_SUCCESS;
		debug_info("SSL mode enabled");
	}
#endif
	return ret;
}
Пример #22
0
void Test_OpenSSL_ClientServerAuth()
{
    LCD_Clear();
    lcd_printf("Testing SSL Client/Server negotiations...\n");
	int err;
	int client_numbytes, server_numbytes;
	int listen_sd;
	int server_sd;
	int client_sd;
	struct TINYCLR_SSL_SOCKADDR_IN sa_serv;
	struct TINYCLR_SSL_SOCKADDR_IN sa_cli;
	size_t client_len;
	SSL_CTX* server_ctx = NULL;
	SSL*     server_ssl = NULL;
	X509*    server_cert = NULL;
	SSL_CTX* client_ctx = NULL;
	SSL*     client_ssl = NULL;
	X509*    client_cert = NULL;
	char*    str = NULL;
	char     client_buf [256];
	char	 server_buf [256];
	SSL_METHOD *server_meth = NULL;
	SSL_METHOD *client_meth = NULL;
	BIO *cert = NULL;
	X509 *x = NULL;
	EVP_PKEY *pkey = NULL;

	// SSL preliminaries. 
	// create client ssl
	client_meth = (SSL_METHOD*)SSLv3_client_method();
	client_ctx = SSL_CTX_new (client_meth);
	if (!client_ctx) goto cleanup;

	server_meth = (SSL_METHOD*)SSLv3_server_method();
	server_ctx = SSL_CTX_new (server_meth);
	if (!server_ctx) goto cleanup;

	
	if ((cert=BIO_new(BIO_s_mem())) == NULL)
	{
		TINYCLR_SSL_PRINTF("Unable to create new BIO");
		goto cleanup;
	}
	BIO_puts(cert,server_pem);
	x=PEM_read_bio_X509_AUX(cert, NULL, 0, NULL);
	
	pkey=PEM_read_bio_PrivateKey(cert,NULL,
		server_ctx->default_passwd_callback,server_ctx->default_passwd_callback_userdata);
	//if (SSL_CTX_use_certificate_file(server_ctx, CERTF, SSL_FILETYPE_PEM) <= 0) {
	if (SSL_CTX_use_certificate(server_ctx, x) <= 0) 
	{ 
		TINYCLR_SSL_PRINTF("Use certifcate chain file failed");
		goto cleanup;
	}
	if (SSL_CTX_use_PrivateKey(server_ctx, pkey) <= 0) 
	{
		TINYCLR_SSL_PRINTF("Unable to use Private Key");
		goto cleanup;
	}

	if (!SSL_CTX_check_private_key(server_ctx)) {
		TINYCLR_SSL_PRINTF("Private key does not match the certificate public key\n");
		goto cleanup;
	}

	//if (SSL_CTX_set_cipher_list(server_ctx, );

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

	listen_sd = TINYCLR_SSL_SOCKET (AF_INET, SOCK_STREAM, IPPROTO_TCP);   
	if (listen_sd < 0) goto cleanup;

	// set it to non-blocking
	int nonblock = 1;
	err = TINYCLR_SSL_IOCTL(listen_sd,SOCK_FIONBIO,&nonblock);
	if (err < 0)
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Nonblocking call failed for server: %d.\n", wsa);
		goto cleanup;
	}

	TINYCLR_SSL_MEMSET(&sa_serv, '\0', sizeof(sa_serv));
	sa_serv.sin_family      		= AF_INET;
	sa_serv.sin_addr.S_un.S_addr 	= inet_addr("127.0.0.1");
	sa_serv.sin_port        		= TINYCLR_SSL_HTONS (1111);          /* Server Port number */

	TINYCLR_SSL_PRINTF("Binding to %d...\n", TINYCLR_SSL_NTOHS(sa_serv.sin_port));
	err = TINYCLR_SSL_BIND(listen_sd, (struct TINYCLR_SSL_SOCKADDR*) &sa_serv,
	     sizeof (sa_serv));                   

	if (err < 0)
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Bind Socket error %d\n", wsa);
		goto cleanup;
	}

	TINYCLR_SSL_PRINTF("Listening...\n");
	/* Receive a TCP connection. */     
	err = TINYCLR_SSL_LISTEN (listen_sd, 5);                    
	if (err < 0) 
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Listen Socket error %d\n", wsa);
		goto cleanup;
	}

	// create a client socket
	client_sd = TINYCLR_SSL_SOCKET (AF_INET, SOCK_STREAM, IPPROTO_TCP);   
	if (client_sd < 0) goto cleanup;

	// set it to non-blocking
	err = TINYCLR_SSL_IOCTL(client_sd,SOCK_FIONBIO,&nonblock);
	if (err < 0)
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Nonblocking call failed for client: %d.\n", wsa);
		goto cleanup;
	}
	// Set up a tcp connection for client: Bind, Connect
	err == TINYCLR_SSL_CONNECT( client_sd, (const struct TINYCLR_SSL_SOCKADDR*)&sa_serv, sizeof(sa_serv));
	if (err < 0)
	{
		int wsa = TINYCLR_SSL_GETLASTSOCKETERROR();
		TINYCLR_SSL_PRINTF("Client connect failed with: %d.\n", wsa);
	}

	
	client_len = sizeof(sa_cli);
	char nodename[128] = "";
	char servname[128] = "";
	SOCK_addrinfo hints;
	SOCK_addrinfo *res = NULL;
	
	TINYCLR_SSL_MEMSET(&hints, '\0', sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;

	SOCK_getaddrinfo(nodename,servname,&hints,&res);

	SOCK_addrinfo *ptr = NULL;
	for (ptr=res; ptr!=NULL; ptr=ptr->ai_next)
	{	
		struct sockaddr_in *ip = (struct sockaddr_in*) ptr->ai_addr;
		TINYCLR_SSL_PRINTF("Accepting connections on...%s:%d\n", 
			inet_ntoa(ip->sin_addr), 1111 );
	}

	int counter=0;
	do
	{
		server_sd = TINYCLR_SSL_ACCEPT (listen_sd, (struct TINYCLR_SSL_SOCKADDR*) &sa_cli, (int*)&client_len);
        Events_WaitForEvents(0,2000);
		TINYCLR_SSL_PRINTF("Accept again %d:%d\n", TINYCLR_SSL_GETLASTSOCKETERROR(), counter++);
	} while (server_sd == -1);
	
	TINYCLR_SSL_CLOSESOCKET (listen_sd);

	TINYCLR_SSL_PRINTF ("Connection from %lx, port %x\n",
	sa_cli.sin_addr.S_un.S_addr, sa_cli.sin_port);


	// connections are completed between server & client
	// now lets do the SSL negotiations
	// create server ssl
	server_ssl = SSL_new(server_ctx);
	if (server_ssl == NULL) goto cleanup;
	SSL_set_fd (server_ssl, server_sd);

	//Create server bio and set as non-blocking
	BIO* server_bio = BIO_new(BIO_s_socket());
	if (server_bio == NULL) goto cleanup;
	//CHK_NULL(bio);
	BIO_set_nbio(server_bio,1);
	BIO_set_fd(server_bio, server_sd, BIO_NOCLOSE);
	SSL_set_bio(server_ssl,server_bio,server_bio);

	// create client ssl & connect
	client_ssl = SSL_new(client_ctx);
	if (client_ssl == NULL) goto cleanup;
	SSL_set_fd(client_ssl, client_sd);

	//Create client bio and set as non-blocking
	BIO* client_bio = BIO_new(BIO_s_socket());
	if (client_bio == NULL) goto cleanup;
	BIO_set_nbio(client_bio,1);
	BIO_set_fd(client_bio, client_sd, BIO_NOCLOSE);
	SSL_set_bio(client_ssl,client_bio,client_bio);

	
	
	// loop until server accepts ssl client connect
	int ssl_err =0;
	do
	{
		err = SSL_connect(client_ssl);
		if (err <= 0) 
		{
			ssl_err = SSL_get_error(client_ssl,err);
			TINYCLR_SSL_PRINTF("SSL_Connect error: %d\n", ssl_err);
		}
        Events_WaitForEvents(0,1000);
		err = SSL_accept (server_ssl);
		if (err <= 0) 
		{
			ssl_err = SSL_get_error(server_ssl, err);
			TINYCLR_SSL_PRINTF("SSL_Accept error: %d\n", ssl_err);
		}
        Events_WaitForEvents(0,1000);
	} while (err != 1);

	//Get the cipher - opt
	TINYCLR_SSL_PRINTF("SSL connection using %s\n", SSL_get_cipher (server_ssl));

	//Get client's certificate (note: beware of dynamic allocation) - opt
	client_cert = SSL_get_peer_certificate (server_ssl);
	if (client_cert != NULL) 
	{
		TINYCLR_SSL_PRINTF("Client certificate:\n");

		str = X509_NAME_oneline (X509_get_subject_name (client_cert), 0, 0);
		if (str == NULL) goto cleanup;

		TINYCLR_SSL_PRINTF("subject: %s\n", str);
		OPENSSL_free (str);

		str = X509_NAME_oneline (X509_get_issuer_name  (client_cert), 0, 0);
		if (str == NULL) goto cleanup;
		TINYCLR_SSL_PRINTF("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
		TINYCLR_SSL_PRINTF("Client does not have certificate.\n");
	
	//Get server's certificate (note: beware of dynamic allocation) - opt
	server_cert = SSL_get_peer_certificate (client_ssl);
	if (server_cert != NULL) 
	{
		TINYCLR_SSL_PRINTF("Server certificate:\n");

		str = X509_NAME_oneline (X509_get_subject_name (server_cert), 0, 0);
		if (str == NULL) goto cleanup;

		TINYCLR_SSL_PRINTF("subject: %s\n", str);
		OPENSSL_free (str);

		str = X509_NAME_oneline (X509_get_issuer_name  (server_cert), 0, 0);
		if (str == NULL) goto cleanup;
		TINYCLR_SSL_PRINTF("issuer: %s\n", str);
		OPENSSL_free (str);

		/* We could do all sorts of certificate verification stuff here before
		   deallocating the certificate. */

		X509_free (server_cert);
	} 
	else
		TINYCLR_SSL_PRINTF("Server with no certificate?!?!?.\n");

	do
	{

		// DATA EXCHANGE - Receive message and send reply. 
		err = SSL_write(client_ssl,"Hello World!",TINYCLR_SSL_STRLEN("Hello World!"));
		if (err <= 0) ssl_err = SSL_get_error(client_ssl, err);
        Events_WaitForEvents(0,1000);
		server_numbytes= SSL_read (server_ssl, server_buf, sizeof(server_buf) - 1);                   
		if (server_numbytes <= 0) 
			ssl_err = SSL_get_error(server_ssl, server_numbytes);
		else
			server_buf[server_numbytes] = '\0';
        Events_WaitForEvents(0,1000);

		err = SSL_write (server_ssl, "I hear you.", TINYCLR_SSL_STRLEN("I hear you."));  
		if (err <= 0) ssl_err = SSL_get_error(server_ssl, err);
        Events_WaitForEvents(0,1000);

		client_numbytes= SSL_read(client_ssl, client_buf, sizeof(client_buf) -1);
		if (client_numbytes <= 0) 
			ssl_err = SSL_get_error(client_ssl, client_numbytes);
		else
			client_buf[client_numbytes] = '\0';
        Events_WaitForEvents(0,1000);
		
	} while (err <= 0);

	TINYCLR_SSL_PRINTF("Server got %d chars:'%s'\n", server_numbytes, server_buf);
	TINYCLR_SSL_PRINTF("Client go %d chars:'%s'\n", client_numbytes, client_buf);
	/* Clean up. */

	cleanup:
	if (pkey) EVP_PKEY_free(pkey);
	if (cert) BIO_free(cert);
	if (x) X509_free(x);
	TINYCLR_SSL_CLOSESOCKET(server_sd);
	if (server_ssl) SSL_shutdown(server_ssl);
	if (server_ssl) SSL_free (server_ssl);
	server_ssl = NULL;
	if (server_ctx) SSL_CTX_free(server_ctx);
	server_ctx = NULL;
	TINYCLR_SSL_CLOSESOCKET(client_sd);
	if (client_ssl) SSL_shutdown(client_ssl);
	if (client_ssl) SSL_free (client_ssl);
	client_ssl = NULL;
	if (client_ctx) SSL_CTX_free(client_ctx);
	client_ctx = NULL;
}
Пример #23
0
int main()
{
    BIO * bio;
    SSL * ssl;
    SSL_CTX * ctx;
    
    int sockfd;
	int len;
	struct sockaddr_in address;
	int result=0;
	char ch = 'A';

    int p;

    char * request = "GET / HTTP/1.1\x0D\x0AHost: localhost\x0D\x0A\x43onnection: Close\x0D\x0A\x0D\x0A";
    char r[1024];

    /* Set up the library */

    ERR_load_BIO_strings();
    SSL_load_error_strings();
    SSL_library_init();
    OpenSSL_add_all_algorithms();

    /* Set up the SSL context */

    ctx = SSL_CTX_new(SSLv23_client_method());

    /* Load the trust store */

    if(! SSL_CTX_load_verify_locations(ctx, "TrustStore.pem", NULL))
    {
        fprintf(stderr, "Error loading trust store\n");
        ERR_print_errors_fp(stderr);
        SSL_CTX_free(ctx);
        return 0;
    }

    /* Setup the connection 

	bio = BIO_new_ssl_connect(ctx);

    /* Set the SSL_MODE_AUTO_RETRY flag 

    BIO_get_ssl(bio, & ssl);
    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

    /* Create and setup the connection 

    BIO_set_conn_hostname(bio, "localhost:4422");

    if(BIO_do_connect(bio) <= 0)
    {
        fprintf(stderr, "Error attempting to connect\n");
        ERR_print_errors_fp(stderr);
        BIO_free_all(bio);
        SSL_CTX_free(ctx);
        return 0;
    }
    
    /* Check the certificate */

	//socket for client
	sockfd = socket(AF_INET, SOCK_STREAM, 0);

	//naming socket
	address.sin_family = AF_INET;
	address.sin_addr.s_addr = inet_addr("127.0.0.1");
	address.sin_port = htons(9738);
	len = sizeof(address);
	printf("length=%d\n",len);
	printf("Socket done\n");

    //connecting server
	result = connect(sockfd, (struct sockaddr *)&address, len);
	if(result <0)
	{
		perror("oops: client\n");
		exit(1);
	}
	else
	{
		printf("Socket Connected\n");
	}
	ssl = SSL_new(ctx);
	BIO *sbio;
	sbio = BIO_new(BIO_s_socket());
	BIO_set_fd(sbio, sockfd, BIO_NOCLOSE);
	SSL_set_bio(ssl, sbio, sbio);
	//SSL_CTX_set_verify_depth(ctx, 1);
	//SSL_set_fd(ssl, sockfd);
	result = SSL_connect(ssl);
	printf("SSL_connect: %d\n", result);
	
	if(SSL_get_verify_result(ssl) != X509_V_OK)
    {
        fprintf(stderr, "Certificate verification error: %i\n", SSL_get_verify_result(ssl));
        BIO_free_all(bio);
        SSL_CTX_free(ctx);
        return 0;
    }
    
    SSL_read(ssl, &ch, 1);
	printf("char from server = %c\n", ch);
	SSL_shutdown(ssl);  
	close(sockfd);
	exit(0);
    
    
    /*for(;;)
    {
        p = BIO_read(bio, r, 1023);
        if(p <= 0) break;
        r[p] = 0;
        printf("%s", r);
    }
    
    FILE *fp = NULL;
	while (fp == NULL) {
		fp = fopen("/home/herat/Downloads/openssl-backup/shared","r");
	}
	remove("/home/herat/Downloads/openssl-backup/shared");*/

    /* Send the request */

    //BIO_write(bio, request, strlen(request));

    /* Read in the response */

    /*for(;;)
    {
        p = BIO_read(bio, r, 1023);
        if(p <= 0) break;
        r[p] = 0;
        printf("%s", r);
    }

    /* Close the connection and free the context 

    BIO_free_all(bio);
    SSL_CTX_free(ctx);*/
    return 0;
}
Пример #24
0
static int connect_to_peer(struct sockaddr_in *peeraddr, uint16_t bindport)
{
	int s;
	int yes = 1;
	struct sockaddr_in self;
	if(ssl == NULL) {
		//OpenSSL
		/* Set up the SSL context */
		ctx = SSL_CTX_new(SSLv23_client_method());

		/* Load the trust store */
		if(! SSL_CTX_load_verify_locations(ctx, CERT_FILE, NULL))
		{
			fprintf(stderr, "Error loading trust store\n");
			ERR_print_errors_fp(stderr);
			SSL_CTX_free(ctx);
			return 0;
		}
		//////////////

		s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (s < 0)
			return -1;

		if (bindport) {
			self.sin_family = AF_INET;
			self.sin_addr.s_addr = htonl(INADDR_ANY);
			self.sin_port = htons(bindport);

			setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));

			if (bind(s, (struct sockaddr *)&self, sizeof(self)) < 0) {
				close(s);
				return -1;
			}
		}
		
		if (connect(s, (struct sockaddr *)peeraddr, sizeof(*peeraddr)) < 0) {
			close(s);
			return -1;
		}
		
		get_tcpr_state(&state1, tcpr_sock, &pulladdr1, port1);
		
		//OpenSSL
		SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY);
		SSL_CTX_set_timeout(ctx, 6000);
		ssl = SSL_new(ctx);
		sbio = BIO_new(BIO_s_socket());
		BIO_set_fd(sbio, s, BIO_NOCLOSE);
		SSL_set_bio(ssl, sbio, sbio);
		BIO_set_callback(sbio,test);
		//SSL_set_connect_state(ssl);
		printf("SSL Connect: %d\n", SSL_connect(ssl));		
		/////////////
		
		setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
				
	} else {
		//OpenSSL
		/* Set up the SSL context */
		ctx1 = SSL_CTX_new(SSLv23_client_method());

		/* Load the trust store */
		if(! SSL_CTX_load_verify_locations(ctx1, CERT_FILE, NULL))
		{
			fprintf(stderr, "Error loading trust store\n");
			ERR_print_errors_fp(stderr);
			SSL_CTX_free(ctx1);
			return 0;
		}
		//////////////

		s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		if (s < 0)
			return -1;

		if (bindport) {
			self.sin_family = AF_INET;
			self.sin_addr.s_addr = htonl(INADDR_ANY);
			self.sin_port = htons(bindport);

			setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));

			if (bind(s, (struct sockaddr *)&self, sizeof(self)) < 0) {
				close(s);
				return -1;
			}
		}
		
		if (connect(s, (struct sockaddr *)peeraddr, sizeof(*peeraddr)) < 0) {
			close(s);
			return -1;
		}
		
		get_tcpr_state(&state1, tcpr_sock, &pulladdr1, port1);
		
		//OpenSSL
		SSL_CTX_set_mode(ctx1, SSL_MODE_AUTO_RETRY);
		SSL_CTX_set_timeout(ctx1, 6000);
		ssl1 = SSL_new(ctx1);
		sbio1 = BIO_new(BIO_s_socket());
		BIO_set_fd(sbio1, s, BIO_NOCLOSE);
		SSL_set_bio(ssl1, sbio1, sbio1);
		//BIO_set_callback(sbio1,test);
		//SSL_set_connect_state(ssl1);
		printf("SSL Connect: %d\n", SSL_connect(ssl1));		
		/////////////
		
		setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));
	}
	return s;
}