コード例 #1
1
ファイル: drop.c プロジェクト: haxworx/NodeInTheWhole
BIO *Connect_SSL(char *hostname, int port)
{
	//BIO *bio = NULL;
	char bio_addr[BUF_MAX] = { 0 };
	
	snprintf(bio_addr, sizeof(bio_addr), "%s:%d", hostname, port);
	
	SSL_library_init();
	
	SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method());
	SSL *ssl = NULL;
	
	bio = BIO_new_ssl_connect(ctx);
	if (bio == NULL)
	{
		Error("BIO_new_ssl_connect");
	}
	
	BIO_get_ssl(bio, &ssl);
	SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
	BIO_set_conn_hostname(bio, bio_addr);
	
	if (BIO_do_connect(bio) <= 0)
	{
		Error("SSL Unable to connect");
	}

	return bio;
}
コード例 #2
0
/*
  The first line specifiy some settings in the ctx and ssl object:
  SSL_OP_ALL: enables all work around codes
  SSL_OP_NO_SSLv2: no SSLv2 connections are allowed (this should fail anyway because only
                   TLSv1 connection are allowed)
  SSL_OP_SINGLE_DH_USE: the server generates a new private key for each new connection
  SSL_VERIFY_PEER: asks the client for a certificate
  SSL_VERIFY_FAIL_IF_NO_PEER_CERT: if the client doesn't present a cert the connection gets
                                   terminated
  CIPHER_LIST: is defined in ssl_server.h (look there for a detailed description)

  After setting up these things the bio object will be created and a ssl object assigned.
  Then the ssl engine mode is set to SSL_MODE_AUTO_RETRY. All available modes are:

  SSL_MODE_ENABLE_PARTIAL_WRITE: Allow SSL_write(..., n) to return r with 0 < r < n 
                                (i.e. report success when just a single record has been written).
				When not set (the default), SSL_write() will only report success 
				once the complete chunk was written. Once SSL_write() returns with r, 
				r bytes have been successfully written and the next call to SSL_write() 
				must only send the n-r bytes left, imitating the behaviour of write().

  SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER: Make it possible to retry SSL_write() with changed buffer location 
                                       (the buffer contents must stay the same). This is not the default 
				       to avoid the misconception that non-blocking SSL_write() behaves 
				       like non-blocking write(). 

  SSL_MODE_AUTO_RETRY: Never bother the application with retries if the transport is blocking. If a 
                       renegotiation take place during normal operation, a ssl_read(3) or ssl_write(3)
		       would return with -1 and indicate the need to retry with SSL_ERROR_WANT_READ . In 
		       a non-blocking environment applications must be prepared to handle incomplete 
		       read/write operations. In a blocking environment, applications are not always
		       prepared to deal with read/write operations returning without success report. The 
		       flag SSL_MODE_AUTO_RETRY will cause read/write operations to only return after 
		       the handshake and successful completion. 

  The server contains 3 bio objects: bio, abio and out. 'bio' contains the context, 'abio'
  binds to the socket and 'out' is the established connection.
 */
void SSL_Server::bind(){
  SSL_CTX_set_verify(getCTX(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
  SSL_CTX_set_options(getCTX(), SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_SINGLE_DH_USE);
  SSL_CTX_set_tmp_dh_callback(getCTX(), tmp_dh_callback);
  if(SSL_CTX_set_cipher_list(getCTX(), CIPHER_LIST) != 1)
    msgHandler->error("setting cipher list failed (no valid ciphers)", CRITICAL);

  msgHandler->debug("trying to set context to bio");
  bio = BIO_new_ssl(getCTX(), 0);
  if(bio == NULL){
    string error("Cannot set context to bio ");
    error.append(getSocket());
    error.append("\nSSL_ERROR: ");
    error.append(ERR_reason_error_string(ERR_get_error()));
    msgHandler->error(error, CRITICAL);
  } else
    msgHandler->debug("set context to bio successful");

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

  msgHandler->debug("trying to bind to socket");
  abio = BIO_new_accept((char*)getSocket().c_str());
  BIO_set_accept_bios(abio, bio);

  if(BIO_do_accept(abio) <= 0){
    string error("Bind to socket ");
    error.append(getSocket());
    error.append(" failed.\nSSL_ERROR: ");
    error.append(ERR_reason_error_string(ERR_get_error()));
    msgHandler->error(error, CRITICAL);
  } else
    msgHandler->log("bind to socket successful");
}
コード例 #3
0
ファイル: main.c プロジェクト: GitMirar/heartbleed_exploit
BIO* connect_encrypted(char* host_and_port, char* store_path, char store_type, SSL_CTX** ctx, SSL** ssl) {
  BIO* bio = NULL;
  int r = 0;

  *ctx = SSL_CTX_new(SSLv23_client_method());
  *ssl = NULL;

  if (store_type == 'f')
    r = SSL_CTX_load_verify_locations(*ctx, store_path, NULL);
  else
    r = SSL_CTX_load_verify_locations(*ctx, NULL, store_path);
  if (r == 0) {
    return NULL;
  }

  bio = BIO_new_ssl_connect(*ctx);
  BIO_get_ssl(bio, ssl);
  if (!(*ssl)) {
    return NULL;
  }
  SSL_set_mode(*ssl, SSL_MODE_AUTO_RETRY);

  BIO_set_conn_hostname(bio, host_and_port);

  if (BIO_do_connect(bio) < 1) {
    return NULL;
  }

  return bio;
}
コード例 #4
0
ファイル: openssl.c プロジェクト: 00001/plan9port
static Pfd*
opensslconnect(char *host)
{
	Pfd *pfd;
	BIO *sbio;
	SSL_CTX *ctx;
	SSL *ssl;
	static int didinit;
	char buf[1024];

	if(!didinit){
		httpsinit();
		didinit = 1;
	}

	ctx = SSL_CTX_new(SSLv23_client_method());
	sbio = BIO_new_ssl_connect(ctx);
	BIO_get_ssl(sbio, &ssl);
	SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
	
	snprint(buf, sizeof buf, "%s:https", host);
	BIO_set_conn_hostname(sbio, buf);
	
	if(BIO_do_connect(sbio) <= 0 || BIO_do_handshake(sbio) <= 0){
		ERR_error_string_n(ERR_get_error(), buf, sizeof buf);
		BIO_free_all(sbio);
		werrstr("openssl: %s", buf);
		return nil;
	}

	pfd = emalloc(sizeof *pfd);
	pfd->sbio = sbio;
	return pfd;
}
コード例 #5
0
ファイル: tls.c プロジェクト: nayimsust/FreeRDP
BOOL tls_prepare(rdpTls* tls, BIO *underlying, const SSL_METHOD *method, int options, BOOL clientMode)
#endif
{
	tls->ctx = SSL_CTX_new(method);
	if (!tls->ctx)
	{
		fprintf(stderr, "%s: SSL_CTX_new failed\n", __FUNCTION__);
		return FALSE;
	}

	SSL_CTX_set_mode(tls->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);

	SSL_CTX_set_options(tls->ctx, options);
	SSL_CTX_set_read_ahead(tls->ctx, 1);

	tls->bio = BIO_new_rdp_tls(tls->ctx, clientMode);

	if (BIO_get_ssl(tls->bio, &tls->ssl) < 0)
	{
		fprintf(stderr, "%s: unable to retrieve the SSL of the connection\n", __FUNCTION__);
		return FALSE;
	}

	BIO_push(tls->bio, underlying);

	return TRUE;
}
コード例 #6
0
ファイル: ssl_server.c プロジェクト: warmlab/study
void *handle_connection(void *arg)
{
	char buf[1024];
	BIO *bio = (BIO *)arg;
	X509 *peer;
	SSL *ssl;

	BIO_get_ssl(bio, &ssl);

	if (BIO_do_handshake(bio) <= 0) {
		printf("Failed handshake.\n");
		ERR_print_errors_fp(stdout);
		return (void *)-1;
	}

	if ((peer = SSL_get_peer_certificate(ssl))) {
		if (SSL_get_verify_result(ssl) == X509_V_OK) {
			/* The client sent a certificate which verified OK */
			printf("The client sent a certificate which verified OK\n");
		} else {
			printf("The client sent a certificate which verified failed\n");
		}
	} else {
		fprintf(stderr, "cannot get peer certificate\n");
	}

	BIO_read(bio, buf, 1024);
	printf("Received: %s\n", buf);
	BIO_puts(bio, "Connection: Sending out Data on initial connection\n");
	printf("Sent out data on connection\n");

	BIO_free_all(bio);

	return (void *)0;
}
コード例 #7
0
ファイル: tls.c プロジェクト: JozLes77/FreeRDP
BOOL tls_prepare(rdpTls* tls, BIO *underlying, const SSL_METHOD *method, int options, BOOL clientMode)
#endif
{
	tls->ctx = SSL_CTX_new(method);
	if (!tls->ctx)
	{
		DEBUG_WARN( "%s: SSL_CTX_new failed\n", __FUNCTION__);
		return FALSE;
	}

	SSL_CTX_set_mode(tls->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);

	SSL_CTX_set_options(tls->ctx, options);
	SSL_CTX_set_read_ahead(tls->ctx, 1);

	if (tls->settings->PermittedTLSCiphers) {
		if(!SSL_CTX_set_cipher_list(tls->ctx, tls->settings->PermittedTLSCiphers)) {
			DEBUG_WARN( "SSL_CTX_set_cipher_list %s failed\n", tls->settings->PermittedTLSCiphers);
			return FALSE;
		}
	}
 
	tls->bio = BIO_new_rdp_tls(tls->ctx, clientMode);

	if (BIO_get_ssl(tls->bio, &tls->ssl) < 0)
	{
		DEBUG_WARN( "%s: unable to retrieve the SSL of the connection\n", __FUNCTION__);
		return FALSE;
	}

	BIO_push(tls->bio, underlying);

	return TRUE;
}
コード例 #8
0
ファイル: bio.c プロジェクト: NEXUS1000/Linux-learning
int main() 
{
    SSL_load_error_strings();
    ERR_load_BIO_strings();
    OpenSSL_add_all_algorithms();
    
    SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method());
    if (ctx == NULL) {
        printf("SSL_CTX_new err func:%s\n reaseon:%s", ERR_func_error_string(ERR_get_error()),
               ERR_reason_error_string(ERR_get_error()));
        exit(1);
    }

    //加载可信任证书库
    if (0 == SSL_CTX_load_verify_locations(ctx, "./push_cer.pem", NULL)) {
        printf("err func:%s\n reaseon:%s", ERR_func_error_string(ERR_get_error()),
               ERR_reason_error_string(ERR_get_error()));
        ERR_print_errors_fp(stdout);
        exit(1);
    }

    //set BIO
    BIO *bio = BIO_new_ssl_connect(ctx);
    if (bio == NULL) {
        printf("err func:%s\n", ERR_func_error_string(ERR_get_error()));
        ERR_print_errors_fp(stdout);
        exit(1);
    }

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

    //open safe connect
    BIO_set_conn_hostname(bio, "gateway.sandbox.push.apple.com:2195");

    //verify connect ok
    if (BIO_do_connect(bio) <= 0) {
        ERR_print_errors_fp(stdout);
        exit(1);
    }

    if (SSL_get_verify_result(ssl) != X509_V_OK) {
        printf("SSL_get_verify_result not success\n");
    }

    char buf[MAXBUF];
    char *json = "{\"aps\":{\"badge\":123}}";
    sendPayload(bio, token, json, strlen(json));
    int ret = BIO_read(bio, buf, MAXBUF);
    if (ret <= 0) {
        printf("BIO_read return 0\n");
    }

    SSL_CTX_free(ctx);
    BIO_free_all(bio);
    return 0;
}
コード例 #9
0
ファイル: openssl.c プロジェクト: Dan-McG/libneo4j-client
BIO *neo4j_openssl_new_bio(BIO *delegate, const char *hostname, int port,
        const neo4j_config_t *config, uint_fast32_t flags)
{
    neo4j_logger_t *logger = neo4j_get_logger(config, "tls");

    SSL_CTX *ctx = new_ctx(config, logger);
    if (ctx == NULL)
    {
        return NULL;
    }

    BIO *ssl_bio = BIO_new_ssl(ctx, 1);
    if (ssl_bio == NULL)
    {
        errno = openssl_error(logger, NEO4J_LOG_ERROR, __FILE__, __LINE__);
        SSL_CTX_free(ctx);
        goto failure;
    }

    SSL_CTX_free(ctx);

    BIO_push(ssl_bio, delegate);
    if (BIO_set_close(ssl_bio, BIO_CLOSE) != 1)
    {
        errno = openssl_error(logger, NEO4J_LOG_ERROR, __FILE__, __LINE__);
        goto failure;
    }

    int result = BIO_do_handshake(ssl_bio);
    if (result != 1)
    {
        if (result == 0)
        {
            errno = NEO4J_NO_SERVER_TLS_SUPPORT;
            goto failure;
        }
        errno = openssl_error(logger, NEO4J_LOG_ERROR, __FILE__, __LINE__);
        goto failure;
    }

    SSL *ssl = NULL;
    BIO_get_ssl(ssl_bio, &ssl);
    assert(ssl != NULL);
    if (verify(ssl, hostname, port, config, flags, logger))
    {
        goto failure;
    }

    return ssl_bio;

    int errsv;
failure:
    errsv = errno;
    BIO_free(ssl_bio);
    errno = errsv;
    return NULL;
}
コード例 #10
0
ファイル: Email.cpp プロジェクト: freddierice/OneBrown
bool Email::sendCode(std::string user, std::string code)
{
    std::string msg,to;
    
    msg = m_m1 + code + m_m2;
    to = m_to1 + user + m_to3;
    
    SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method());
    SSL* ssl;
    
    BIO* bio = BIO_new_ssl_connect(ctx);
    BIO_get_ssl(bio, &ssl);
    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
    BIO_set_conn_hostname(bio, m_amazonHostname.c_str());
    
    if(BIO_do_connect(bio) <= 0){
        BIO_free_all(bio);
        SSL_CTX_free(ctx);
        return false;
    }
    
    if(BIO_do_handshake(bio) <= 0){
        BIO_free_all(bio);
        SSL_CTX_free(ctx);
        return false;
    }

    m_len = BIO_read(bio, m_buf, BUF_LEN) - 1;
    BIO_puts(bio, "HELO localhost\r\n");
    m_len = BIO_read(bio, m_buf, BUF_LEN) - 1;
    BIO_puts(bio,"AUTH LOGIN\r\n");
    m_len = BIO_read(bio,m_buf,BUF_LEN) - 1;
    BIO_puts(bio,"QUtJQUlFVzJDMlU3RUZYTU5PUVE=\r\n"); 
    m_len = BIO_read(bio,m_buf,BUF_LEN) - 1;
    BIO_puts(bio,"QWd3TkZSOUJyb2dUTUkxYlJHeXh4dHZMYm4reldGZCtYSFJMbnJpNzZ5RC8=\r\n"); 
    m_len = BIO_read(bio,m_buf,BUF_LEN) - 1;
    BIO_puts(bio,"MAIL FROM:[email protected]\r\n"); 
    m_len = BIO_read(bio,m_buf,BUF_LEN) - 1;
    BIO_puts(bio,to.c_str()); 
    m_len = BIO_read(bio,m_buf,BUF_LEN) - 1;
    BIO_puts(bio,"DATA\r\n"); 
    m_len = BIO_read(bio,m_buf,BUF_LEN) - 1;
    BIO_puts(bio,"Subject:OneBrown Verification\r\n\r\n"); 
    BIO_puts(bio,msg.c_str()); 
    BIO_puts(bio,"\r\n.\r\n"); 
    m_len = BIO_read(bio,m_buf,BUF_LEN) - 1;
    BIO_puts(bio,"QUIT\r\n"); 
    m_len = BIO_read(bio,m_buf,BUF_LEN) - 1;
    
    BIO_free_all(bio);
    SSL_CTX_free(ctx);
    
    return true;
}
コード例 #11
0
ファイル: mod_fauth.c プロジェクト: CertCenter/mod_fauth
const char *dbapi_lookup(const char *key) {
	long res = 1;
	SSL_CTX* ctx = NULL;
	BIO *web = NULL, *out = NULL;
	SSL *ssl = NULL;
	const SSL_METHOD* method;
	char *token, *tmpout, *buf;
	int hlen=0, len=0, maxlen=2048;
	(void)SSL_library_init();
	SSL_load_error_strings();
	OPENSSL_config(NULL);
	method = SSLv23_method(); if(method==NULL) return NULL;
	ctx = SSL_CTX_new(method); if(ctx==NULL) return NULL;
	SSL_CTX_set_verify_depth(ctx, 4);
	SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3|SSL_OP_NO_TLSv1|
		SSL_OP_NO_COMPRESSION);
	web = BIO_new_ssl_connect(ctx); if(web==NULL) return NULL;
	res = BIO_set_conn_hostname(web, DB_API_SERVER); if(res!=1) return NULL;
	BIO_get_ssl(web, &ssl); if(ssl==NULL) return NULL;
	res = SSL_set_cipher_list(ssl, SECURE_CIPHER_LIST); if(res!=1) return NULL;
	res = SSL_set_tlsext_host_name(ssl, DB_API_HOST); if(res!=1) return NULL;
	out = BIO_new_fp(stdout, BIO_NOCLOSE); if(NULL==out) return NULL;
	res = BIO_do_connect(web); if(res!=1) return NULL;
	res = BIO_do_handshake(web); if(res!=1) return NULL;
	len=(60+strlen(key)+strlen(DB_API_HOST)+strlen(DB_API_AUTH));
	char *request=malloc(sizeof(char)*(len+1));
	snprintf(request,len,
		"GET %s HTTP/1.1\nHost: %s\nx-api-key: %s\nConnection: close\n\n",
		key, DB_API_HOST, DB_API_AUTH);
	request[len]='\0';
	BIO_puts(web, request);
	BIO_puts(out, "\n");
	buf = malloc(sizeof(char)*maxlen);
	do {
		char buff[1536] = {};
		len=BIO_read(web, buff, sizeof(buff));
		hlen+=len;
		if(hlen<maxlen&&len>0) strncat(buf,buff,len);
	} while (len>0 || BIO_should_retry(web));
	buf[maxlen]='\0';
	tmpout = malloc(sizeof(char)*(HASH_MAXLENGTH+1));
	token = strtok(buf, "\n");
	while (token) {
		snprintf(tmpout,HASH_MAXLENGTH,"%s",token);
		token = strtok(NULL, "\n");
	}
	tmpout[strlen(tmpout)]='\0';
	free(buf);
	free(request);
	if(out) BIO_free(out);
	if(web != NULL) BIO_free_all(web);
	if(NULL != ctx) SSL_CTX_free(ctx);
	return tmpout;
}
コード例 #12
0
/*
  At first the arguments are read and passed. Then the ssl context is gotten
  by calling 'BIO_get_ssl(client, &ssl)'. Afterwards the ssl handshake is 
  performed and the certificate verified. Then the line is read from the certificate. 
  This value is mapped to 'organizationalUnitName'.
  An example usage of the connection is shown and then the connectino will be
  terminated.
 */
void* handleConn(void *argsv){
  connArgs* args = (connArgs*) argsv;
  MessageHandler* msgHandler = args->msgHandler;
  BIO* client = args->conn;
  SSL* ssl;

  BIO_get_ssl(client, &ssl);

  /*ssl handshake*/
  msgHandler->debug("performing ssl handshake");
  if(BIO_do_handshake(client) != 1){
    string fail("handshake failed\nSSL_ERROR: ");
    fail.append(ERR_reason_error_string(ERR_get_error()));
    msgHandler->log(fail);
  } else
    msgHandler->log("handshake successful");

  /*verifying the certificate*/
  X509* peerCert;

  if(SSL_get_verify_result(ssl) != X509_V_OK){
    string error("verification failed\nSSL_Error: ");
    error.append(ERR_reason_error_string(ERR_get_error()));
    msgHandler->error(error, CRITICAL);
  } else {
    msgHandler->debug("verification successful");
    peerCert  = SSL_get_peer_certificate(ssl);
  }

  msgHandler->debug("trying to get the line");
  /*getting the line*/
  char lineN[6];
  X509_NAME* name = X509_get_subject_name(peerCert);
  X509_NAME_get_text_by_NID(name, NID_organizationalUnitName, lineN, 6);
  string line("line is: ");
  line.append(lineN);
  msgHandler->debug(line);

  /*example use of the connection (echoing the incoming msg)*/
  char buffer[1024];
  bzero(buffer, 1024);
  SSL_read(ssl, buffer, 1024);
  string debug("message received: ");
  debug.append(buffer);
  msgHandler->debug(debug);
  SSL_write(ssl, buffer, 1024);

  /*closing the connection*/
  BIO_reset(client);
  X509_free(peerCert);
  return NULL;
}
コード例 #13
0
ファイル: vndb_guile.c プロジェクト: hitchiker42/my-code
SCM scm_tls_get_cipher_info(SCM tls_smob){
  scm_assert_smob_type(tls_tag, tls_smob);
  BIO *bio = (BIO*)SCM_SMOB_DATA(tls_smob);
  SSL *ssl;
  BIO_get_ssl(bio, &ssl);

  //I'm not sure if scheme copies c strings or not, so make this static
  //so it stays valid regardless.
  static char cipher_buf[128];
  SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  SSL_CIPHER_description(cipher, cipher_buf, 128);
  return scm_from_utf8_string(cipher_buf);
}
コード例 #14
0
/**
 * mongoc_stream_tls_check_cert:
 *
 * check the cert returned by the other party
 */
bool
mongoc_stream_tls_check_cert (mongoc_stream_t *stream,
                              const char      *host)
{
   mongoc_stream_tls_t *tls = (mongoc_stream_tls_t *)stream;
   SSL *ssl;

   BSON_ASSERT (tls);
   BSON_ASSERT (host);

   BIO_get_ssl (tls->bio, &ssl);

   return _mongoc_ssl_check_cert (ssl, host, tls->weak_cert_validation);
}
コード例 #15
0
ファイル: bio.c プロジェクト: Shaddy1884/lua-openssl
static LUA_FUNCTION(openssl_bio_get_ssl)
{
  BIO* bio = CHECK_OBJECT(1, BIO, "openssl.bio");
  SSL* ssl = NULL;
  int ret = BIO_get_ssl(bio, &ssl);
  if (ret == 1)
  {
    openssl_newvalue(L, ssl);
    PUSH_OBJECT(ssl, "openssl.ssl");
    openssl_refrence(L, ssl, +1);
    return 1;
  }
  return 0;
}
コード例 #16
0
ファイル: oh_ssl.c プロジェクト: openhpi1/testrepo
/**
 * oh_ssl_disconnect
 * @bio:        pointer to a BIO as returned by oh_ssl_connect()
 * @shutdown:   Selects a uni-directional or bi-directional SSL shutdown.
 *              See the SSL_shutdown() man page.
 *
 * Close the SSL connection and free the memory associated with it.
 *
 * Return value: 0 for success, -1 for failure
 **/
int             oh_ssl_disconnect(BIO *bio, enum OH_SSL_SHUTDOWN_TYPE shutdown)
{
        SSL             *ssl;
        int             ret, fd;

        if (bio == NULL) {
                CRIT("NULL bio in oh_ssl_disconnect()");
                return(-1);
        }

        /* Shut down the SSL connection.  This may involve a handshake with
         * the server.
         */
        BIO_get_ssl(bio, &ssl);
        if (ssl == NULL) {
                CRIT("BIO_get_ssl() failed");
                return(-1);
        }
        ret = SSL_shutdown(ssl);
        if (ret == -1) {
                CRIT("SSL_shutdown() failed");
                /* Continuing on to free BIO memory */
        }
        else if ((ret == 0) && (shutdown == OH_SSL_BI)) {
                /* Still need stage 2 shutdown (see SSL_shutdown() man page) */
                ret = SSL_shutdown(ssl);
                if (ret == -1) {
                        CRIT("SSL_shutdown() failed");
                        /* Continuing on to free BIO memory */
                }
                else if (ret == 0) {
                        CRIT("stage 2 of SSL_shutdown() failed");
                        /* Continuing on to free BIO memory */
                }
        }
        /* Close the socket */
        fd = SSL_get_fd(ssl);
        if (fd == -1) {
                CRIT("SSL_get_fd() failed");
                return(-1);
        }
        close(fd);

        /* Free the connection */
        BIO_free_all(bio);

        return(0);
}
コード例 #17
0
ファイル: example_client.c プロジェクト: eltommo/licenceliber
/**
 * Connect to a host using an encrypted stream
 */
BIO* connect_encrypted(char* host_and_port, char* store_path, char store_type, SSL_CTX** ctx, SSL** ssl) {

    BIO* bio = NULL;
    int r = 0;

    /* Set up the SSL pointers */
    *ctx = SSL_CTX_new(SSLv23_client_method());
    *ssl = NULL;

    /* Load the trust store from the pem location in argv[2] */
    if (store_type == 'f')
        r = SSL_CTX_load_verify_locations(*ctx, store_path, NULL);
    else
        r = SSL_CTX_load_verify_locations(*ctx, NULL, store_path);
    if (r == 0) {

        print_ssl_error_2("Unable to load the trust store from %s.\n", store_path, stdout);
        return NULL;
    }

    /* Setting up the BIO SSL object */
    bio = BIO_new_ssl_connect(*ctx);
    BIO_get_ssl(bio, ssl);
    if (!(*ssl)) {

        print_ssl_error("Unable to allocate SSL pointer.\n", stdout);
        return NULL;
    }
    SSL_set_mode(*ssl, SSL_MODE_AUTO_RETRY);

    /* Attempt to connect */
    BIO_set_conn_hostname(bio, host_and_port);

    /* Verify the connection opened and perform the handshake */
    if (BIO_do_connect(bio) < 1) {

        print_ssl_error_2("Unable to connect BIO.%s\n", host_and_port, stdout);
        return NULL;
    }

    if (SSL_get_verify_result(*ssl) != X509_V_OK) {

        print_ssl_error("Unable to verify connection result.\n", stdout);
    }

    return bio;
}
コード例 #18
0
ファイル: socket.cpp プロジェクト: Oky12/xmr-stak
bool tls_socket::set_hostname(const char* sAddr)
{
	sock_closed = false;
	if(ctx == nullptr)
	{
		init_ctx();
		if(ctx == nullptr)
		{
			print_error();
			return false;
		}
	}

	if((bio = BIO_new_ssl_connect(ctx)) == nullptr)
	{
		print_error();
		return false;
	}

	int flag = 1;
	/* If it fails, it fails, we won't loose too much sleep over it */
	setsockopt(BIO_get_fd(bio, nullptr), IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));

	if(BIO_set_conn_hostname(bio, sAddr) != 1)
	{
		print_error();
		return false;
	}

	BIO_get_ssl(bio, &ssl);
	if(ssl == nullptr)
	{
		print_error();
		return false;
	}

	if(jconf::inst()->TlsSecureAlgos())
	{
		if(SSL_set_cipher_list(ssl, "HIGH:!aNULL:!PSK:!SRP:!MD5:!RC4:!SHA1") != 1)
		{
			print_error();
			return false;
		}
	}

	return true;
}
コード例 #19
0
ファイル: ssl.c プロジェクト: witchu/lua-openssl
static int openssl_ssl_ctx_new_bio(lua_State*L)
{
  SSL_CTX* ctx = CHECK_OBJECT(1, SSL_CTX, "openssl.ssl_ctx");
  const char* host_addr = luaL_checkstring(L, 2);
  int server = lua_isnoneornil(L, 3) ? 0 : auxiliar_checkboolean(L, 3);
  int autoretry = lua_isnoneornil(L, 4) ? 1 : auxiliar_checkboolean(L, 4);

  SSL *ssl = NULL;
  BIO *bio = server ? BIO_new_ssl(ctx, 0) : BIO_new_ssl_connect(ctx);
  int ret = BIO_get_ssl(bio, &ssl);
  if (ret == 1 && ssl)
  {
    if (autoretry)
      SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
    if (server)
    {
      BIO* acpt = BIO_new_accept((char*)host_addr);
      BIO_set_accept_bios(acpt, bio);
      bio = acpt;
    }
    else
    {
      ret = BIO_set_conn_hostname(bio, host_addr);
    }
    if (ret == 1)
    {
      PUSH_OBJECT(bio, "openssl.bio");
      openssl_newvalue(L, bio);

      lua_pushboolean(L, 1);
      openssl_setvalue(L, bio, "free_all");

      return 1;
    }
    else
      return openssl_pushresult(L, ret);
  }
  else
  {
    BIO_free(bio);
    bio = NULL;
    return 0;
  }
}
コード例 #20
0
ファイル: socket.cpp プロジェクト: baudy2/xmr-stak
bool tls_socket::set_hostname(const char* sAddr)
{
	if(ctx == nullptr)
	{
		init_ctx();
		if(ctx == nullptr)
		{
			print_error();
			return false;
		}
	}

	if((bio = BIO_new_ssl_connect(ctx)) == nullptr)
	{
		print_error();
		return false;
	}

	if(BIO_set_conn_hostname(bio, sAddr) != 1)
	{
		print_error();
		return false;
	}

	BIO_get_ssl(bio, &ssl);
	if(ssl == nullptr)
	{
		print_error();
		return false;
	}

	if(jconf::inst()->TlsSecureAlgos())
	{
		if(SSL_set_cipher_list(ssl, "HIGH:!aNULL:!kRSA:!PSK:!SRP:!MD5:!RC4:!SHA1") != 1)
		{
			print_error();
			return false;
		}
	}

	return true;
}
コード例 #21
0
ファイル: main.c プロジェクト: bupt007/deo
static BIO *
start_tls(SSL_CTX *ctx)
{
    AUTO(BIO, sio);
    SSL *ssl;

    sio = BIO_new_ssl(ctx, 0);
    if (sio == NULL)
        return NULL;

    if (BIO_get_ssl(sio, &ssl) <= 0)
        return NULL;

    if (SSL_set_fd(ssl, SD_LISTEN_FDS_START) <= 0)
        return NULL;

    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

    return STEAL(sio);
}
コード例 #22
0
bool ClientSSLSocket::Read(char* buffer, int bufferSize, int* bytesRead) {
  assert(buffer);
  assert(bufferSize > 0);

  SSL* ssl = nullptr;
  BIO_get_ssl(_bio.Get(), &ssl);

  int rv = SSL_read(ssl, buffer, bufferSize);

  if (bytesRead)
    *bytesRead = (rv <= 0) ? 0 : rv;

  if (rv <= 0) {
    if (rv == 0 && BIO_should_retry(_bio.Get()))
      return Read(buffer, bufferSize, bytesRead);
    return false;
  }

  return true;
}
コード例 #23
0
bool ClientSSLSocket::Write(const char* buffer, int bufferSize,
                            int* bytesWritten) {
  assert(buffer);
  assert(bufferSize > 0);

  SSL* ssl = nullptr;
  BIO_get_ssl(_bio.Get(), &ssl);

  int rv = SSL_write(ssl, buffer, bufferSize);

  if (bytesWritten)
    *bytesWritten = (rv <= 0) ? 0 : rv;

  if (rv <= 0) {
    if (rv == 0 && BIO_should_retry(_bio.Get()))
      return Write(buffer, bufferSize, bytesWritten);
    return false;
  }

  return true;
}
コード例 #24
0
ファイル: tls.c プロジェクト: matthew-n/FreeRDP
BOOL tls_prepare(rdpTls* tls, BIO* underlying, const SSL_METHOD* method, int options, BOOL clientMode)
#endif
{
	rdpSettings* settings = tls->settings;

	tls->ctx = SSL_CTX_new(method);

	if (!tls->ctx)
	{
		WLog_ERR(TAG, "SSL_CTX_new failed");
		return FALSE;
	}

	SSL_CTX_set_mode(tls->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);

	SSL_CTX_set_options(tls->ctx, options);
	SSL_CTX_set_read_ahead(tls->ctx, 1);

	if (settings->AllowedTlsCiphers)
	{
		if (!SSL_CTX_set_cipher_list(tls->ctx, settings->AllowedTlsCiphers))
		{
			WLog_ERR(TAG, "SSL_CTX_set_cipher_list %s failed", settings->AllowedTlsCiphers);
			return FALSE;
		}
	}
 
	tls->bio = BIO_new_rdp_tls(tls->ctx, clientMode);

	if (BIO_get_ssl(tls->bio, &tls->ssl) < 0)
	{
		WLog_ERR(TAG, "unable to retrieve the SSL of the connection");
		return FALSE;
	}

	BIO_push(tls->bio, underlying);
	tls->underlying = underlying;

	return TRUE;
}
コード例 #25
0
ファイル: vndb_guile.c プロジェクト: hitchiker42/my-code
/*
  Connect to host on the given port using tls and return the BIO object
  representing the connection.
*/
BIO* connect_tls(const char *host, const char *port){
  init_ssl_lib();
  //the assignment is redundant, but it's weird not having it
  ctx = init_ssl_ctx();
  if(!ctx){return NULL;}

  BIO *bio = BIO_new_ssl_connect(ctx);
  if(!bio){goto err;}

  if(BIO_set_conn_hostname(bio, host) == 0){
    goto err;
  }
  if(BIO_set_conn_port(bio, port) == 0){
    goto err;
  }

  SSL *ssl;
  BIO_get_ssl(bio, &ssl);
  //Handle renegotiation transparently
  SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
  //this is to let the server know what name we used to connect to it
  SSL_set_tlsext_host_name(ssl, host);
  if(BIO_do_connect(bio) == 0){
    goto err;
  }
  if(BIO_do_handshake(bio) == 0){
    goto err;
  }
  //make sure that the certificate was valid
  if(SSL_get_verify_result(ssl) != X509_V_OK){
    goto err;
  }

  return bio;
 err:
  print_errors();
  BIO_free_all(bio);
  SSL_CTX_free(ctx);
  return NULL;
}
コード例 #26
0
// ----------------------------------------------------------------------------
void SecureClient::init() {
  SSL_load_error_strings();
  ERR_load_BIO_strings();
  OpenSSL_add_all_algorithms();

  m_ssl_context = SSL_CTX_new(SSLv23_client_method());

  // loading the Trust Store
  if(!SSL_CTX_load_verify_locations(m_ssl_context, "../client/certs/TrustStore.pem", nullptr)) {
    ERR("Failed to load the Trust Store of certificates: %s", ERR_reason_error_string(ERR_get_error()));
    throw ClientException();
  }

  m_bio = BIO_new_ssl_connect(m_ssl_context);
  if (m_bio == nullptr) {
    ERR("Failed to prepare new secure connection: %s", ERR_reason_error_string(ERR_get_error()));
    throw ClientException();
  }
  BIO_get_ssl(m_bio, &m_ssl);
  SSL_set_mode(m_ssl, SSL_MODE_AUTO_RETRY);  // retry handshake transparently if Server suddenly wants

  // establish secure connection
  BIO_set_conn_hostname(m_bio, m_ip_address.c_str());
  BIO_set_conn_port(m_bio, m_port.c_str());
  if (BIO_do_connect(m_bio) <= 0) {
    ERR("Failed to securely connect to [%s:%s]: %s", m_ip_address.c_str(), m_port.c_str(), ERR_reason_error_string(ERR_get_error()));
    m_is_connected = false;
  } else {
    m_is_connected = true;
  }

  // checking certificate from Server
  if (SSL_get_verify_result(m_ssl) != X509_V_OK) {
    WRN("Certificate verification has failed: %s", ERR_reason_error_string(ERR_get_error()));
    // TODO: probably, proceed further
  }

  INF("Secure connection has been established");
  m_api_impl = new SecureClientApiImpl(m_bio, m_ip_address, m_port);
}
コード例 #27
0
ファイル: main.c プロジェクト: ep69/petera
static bool
do_accept(SSL_CTX *ctx, int fd, int *client, BIO **sio)
{
    SSL *ssl;

    *client = accept(fd, NULL, NULL);
    if (*client < 0)
        return false;

    *sio = BIO_new_ssl(ctx, 0);
    if (*sio == NULL)
        return false;

    if (BIO_get_ssl(*sio, &ssl) <= 0)
        return false;

    if (SSL_set_fd(ssl, *client) <= 0)
        return false;

    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
    return true;
}
コード例 #28
0
bool ClientSSLSocket::Connect(std::string hostAndPort) {
  SSL_library_init();
  _ctx.Reset(SSL_CTX_new(SSLv23_client_method()));
  if (!_ctx.Get()) {
    ERR_print_errors_fp(stderr);
    return false;
  }

  _bio.Reset(BIO_new_ssl_connect(_ctx.Get()));

  SSL* ssl = nullptr;

  // Set some flags.
  BIO_get_ssl(_bio.Get(), &ssl);
  SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

  // Create and setup the connection.
  BIO_set_conn_hostname(_bio.Get(), hostAndPort.c_str());
  
  if (BIO_do_connect(_bio.Get()) <= 0) {
    std::cerr << "ERROR: Could not connect to \"" << hostAndPort << "\""
              << std::endl;
    ERR_print_errors_fp(stderr);
    return false;
  }

#if 0  // We don't care about the certificate validity at the moment.
  // Check the certificate.
  if (SSL_get_verify_result(ssl) != X509_V_OK) {
    std::cerr << "ERROR: Certificate verification error ("
              << SSL_get_verify_result(ssl) << ")" << std::endl;
    ERR_print_errors_fp(stderr);
    return false;
  }
#endif  // 0

  return true;
}
コード例 #29
0
static BIO *
my_connect(char *host, int port, int ssl, SSL_CTX **ctx) {
  BIO *conn;
  SSL *ssl_ptr;

  if (ssl) {
    if (!(conn = my_connect_ssl(host, port, ctx))) goto error_exit;
    BIO_get_ssl(conn, &ssl_ptr);
    if (!verify_cert_hostname(SSL_get_peer_certificate(ssl_ptr), host))
      goto error_exit;
    if (SSL_get_verify_result(ssl_ptr) != X509_V_OK) goto error_exit;
    return conn;
  }

  if (!(conn = BIO_new_connect(host))) goto error_exit;
  BIO_set_conn_int_port(conn, &port);
  if (BIO_do_connect(conn) <= 0) goto error_exit;
  return conn;

error_exit:
  if (conn) BIO_free_all(conn);
  return 0;
}
コード例 #30
0
BIO* establishSSLConnection(char * serveraddress, char * port){
	printf("Attempting to establish SSL Connection.\n");
    //============================
    // SSL init 
	SSL_library_init(); 
	SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method());
	SSL *ssl;
	
	SSL_CTX_set_verify(ctx,SSL_VERIFY_NONE,NULL); 
	
	// Establish an SSL Connection
    strcat(serveraddress, ":");
    strcat(serveraddress, port);
    char * concatenate = serveraddress;
    char * connection = malloc(sizeof(char) * (sizeof(concatenate) + 1));
	strcpy(connection, concatenate); 

	BIO* bio = BIO_new_connect(connection); 
	
	BIO_get_ssl(bio,&ssl); 
	SSL_set_mode(ssl,SSL_MODE_AUTO_RETRY); 
	if (BIO_do_connect(bio) <= 0){
		printf("Error: SSL connect failed.\n"); 
		BIO_free_all(bio);
		SSL_CTX_free(ctx); 
		exit(1); 
	}
	if (BIO_do_handshake(bio)<=0){
		printf("Error: SSL handshake failed.\n"); 
		SSL_CTX_free(ctx); 
		exit(1); 
	}
	// ============== SSL init //

	printf("SSL Connection has been established!\n");
	return bio;
}