Example #1
33
SSL_CTX *SSLSocket::sslCreateCtx(bool client, bool verify, const char *CAfile, const char *CRTfile, const char *KEYfile, void *passwd) {
    SSL_CTX *sctx = SSL_CTX_new(client ? SSLv23_client_method() : SSLv23_server_method());
    if (sctx == NULL) {
        throw SSLSocketException ( "Could not create SSL context." );
    }
    else {
        // Generate a new DH key during each handshake
        SSL_CTX_set_options(sctx, SSL_OP_SINGLE_DH_USE);

        // The verification contextof certificates is activated
        if (verify) SSL_CTX_set_verify(sctx, SSL_VERIFY_PEER, NULL);

        // Sets the password of the private key
        SSL_CTX_set_default_passwd_cb_userdata(sctx, passwd);

        if (!client) {
            int s_server_session_id_context = 1;
            SSL_CTX_set_session_id_context(sctx, (const unsigned char*) &s_server_session_id_context, sizeof(s_server_session_id_context));
        }
        
        if (SSL_CTX_load_verify_locations(sctx, CAfile, NULL) == 0) {
            throw CertificateException ( "CA file could not be loaded." );
        }

        if (SSL_CTX_use_certificate_file(sctx, CRTfile, SSL_FILETYPE_PEM) == 0) {
            ERR_print_errors_fp(stderr);
            throw CertificateException ( "CRT file could not be loaded." );
        }

        if (SSL_CTX_use_PrivateKey_file(sctx, KEYfile, SSL_FILETYPE_PEM) == 0) {
            throw CertificateException ( "KEY file could not be loaded." );
        }
    }
    
    return sctx;
}
Example #2
0
	SSLModule(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, EXTRA | VENDOR)
		, service(this, "ssl")
	{
		me = this;

		this->SetPermanent(true);

		SSL_library_init();
		SSL_load_error_strings();

		client_ctx = SSL_CTX_new(SSLv23_client_method());
		server_ctx = SSL_CTX_new(SSLv23_server_method());

		if (!client_ctx || !server_ctx)
			throw ModuleException("Error initializing SSL CTX");

		long opts = SSL_OP_NO_SSLv2 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE;
		SSL_CTX_set_options(client_ctx, opts);
		SSL_CTX_set_options(server_ctx, opts);

		SSL_CTX_set_mode(client_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
		SSL_CTX_set_mode(server_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);

		Anope::string context_name = "Anope";
		SSL_CTX_set_session_id_context(client_ctx, reinterpret_cast<const unsigned char *>(context_name.c_str()), context_name.length());
		SSL_CTX_set_session_id_context(server_ctx, reinterpret_cast<const unsigned char *>(context_name.c_str()), context_name.length());
	}
Example #3
0
int
ssl_setup(SSL_CTX **ctxp, struct pki *pki)
{
	DH	*dh;
	SSL_CTX	*ctx;

	ctx = ssl_ctx_create(pki->pki_name, pki->pki_cert, pki->pki_cert_len);

	if (!SSL_CTX_set_session_id_context(ctx,
		(const unsigned char *)pki->pki_name,
		strlen(pki->pki_name) + 1))
		goto err;

	if (pki->pki_dhparams_len == 0)
		dh = get_dh1024();
	else
		dh = get_dh_from_memory(pki->pki_dhparams,
		    pki->pki_dhparams_len);
	ssl_set_ephemeral_key_exchange(ctx, dh);
	DH_free(dh);

	ssl_set_ecdh_curve(ctx, SSL_ECDH_CURVE);

	*ctxp = ctx;
	return 1;

err:
	SSL_CTX_free(ctx);
	ssl_error("ssl_setup");
	return 0;
}
Example #4
0
int CSSLContext::AddContext(int iVerifyMode, LPCTSTR lpszPemCertFile, LPCTSTR lpszPemKeyFile, LPCTSTR lpszKeyPasswod, LPCTSTR lpszCAPemCertFileOrPath)
{
	int iIndex		= -1;
	SSL_CTX* sslCtx	= SSL_CTX_new(SSLv23_method());

	SSL_CTX_set_quiet_shutdown(sslCtx, 1);
	SSL_CTX_set_verify(sslCtx, iVerifyMode, nullptr);
	SSL_CTX_set_cipher_list(sslCtx, "ALL:!aNULL:!eNULL");

	if(m_enSessionMode == SSL_SM_SERVER)
	{
		static volatile ULONG s_session_id_context = 0;
		ULONG session_id_context = ::InterlockedIncrement(&s_session_id_context);

		SSL_CTX_set_session_id_context(sslCtx, (BYTE*)&session_id_context, sizeof(session_id_context));
	}

	if(!LoadCertAndKey(sslCtx, iVerifyMode, lpszPemCertFile, lpszPemKeyFile, lpszKeyPasswod, lpszCAPemCertFileOrPath))
		SSL_CTX_free(sslCtx);
	else
	{
		iIndex = (int)m_lsSslCtxs.size();
		m_lsSslCtxs.push_back(sslCtx);
	}
	
	return iIndex;
}
Example #5
0
int
ssl_setup(SSL_CTX **ctxp, struct pki *pki,
    int (*sni_cb)(SSL *,int *,void *), const char *ciphers)
{
	SSL_CTX	*ctx;
	uint8_t sid[SSL_MAX_SID_CTX_LENGTH];

	ctx = ssl_ctx_create(pki->pki_name, pki->pki_cert, pki->pki_cert_len, ciphers);

	/*
	 * Set session ID context to a random value.  We don't support
	 * persistent caching of sessions so it is OK to set a temporary
	 * session ID context that is valid during run time.
	 */
	arc4random_buf(sid, sizeof(sid));
	if (!SSL_CTX_set_session_id_context(ctx, sid, sizeof(sid)))
		goto err;

	if (sni_cb)
		SSL_CTX_set_tlsext_servername_callback(ctx, sni_cb);

	SSL_CTX_set_dh_auto(ctx, pki->pki_dhe);

	SSL_CTX_set_ecdh_auto(ctx, 1);

	*ctxp = ctx;
	return 1;

err:
	SSL_CTX_free(ctx);
	ssl_error("ssl_setup");
	return 0;
}
Example #6
0
File: main.c Project: jkniiv/burp
static int ssl_setup(int *rfd, SSL **ssl, SSL_CTX **ctx, struct conf *conf)
{
	BIO *sbio=NULL;
	char buf[256]="";
	ssl_load_globals();
	if(!(*ctx=ssl_initialise_ctx(conf)))
	{
		logp("error initialising ssl ctx\n");
		return -1;
	}

	SSL_CTX_set_session_id_context(*ctx,
		(const unsigned char *)&s_server_session_id_context,
		sizeof(s_server_session_id_context));

	if((*rfd=init_client_socket(conf->server, conf->port))<0)
		return -1;

	if(!(*ssl=SSL_new(*ctx))
	  || !(sbio=BIO_new_socket(*rfd, BIO_NOCLOSE)))
	{
		ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
		logp("Problem joining SSL to the socket: %s\n", buf);
		return -1;
	}
	SSL_set_bio(*ssl, sbio, sbio);
	if(SSL_connect(*ssl)<=0)
	{
		ERR_error_string_n(ERR_get_error(), buf, sizeof(buf));
		logp("SSL connect error: %s\n", buf);
		return -1;
	}
	return 0;
}
Example #7
0
File: main.c Project: scosu/burp
static int ssl_setup(int *rfd, SSL **ssl, SSL_CTX **ctx,
	enum action action, struct conf **confs)
{
	BIO *sbio=NULL;
	ssl_load_globals();
	if(!(*ctx=ssl_initialise_ctx(confs)))
	{
		logp("error initialising ssl ctx\n");
		return -1;
	}

	SSL_CTX_set_session_id_context(*ctx,
		(const uint8_t *)&s_server_session_id_context,
		sizeof(s_server_session_id_context));

	if((*rfd=init_client_socket(get_string(confs[OPT_SERVER]),
	  action==ACTION_MONITOR?
	  get_string(confs[OPT_STATUS_PORT]):get_string(confs[OPT_PORT])))<0)
		return -1;

	if(!(*ssl=SSL_new(*ctx))
	  || !(sbio=BIO_new_socket(*rfd, BIO_NOCLOSE)))
	{
		logp_ssl_err("Problem joining SSL to the socket\n");
		return -1;
	}
	SSL_set_bio(*ssl, sbio, sbio);
	if(SSL_connect(*ssl)<=0)
	{
		logp_ssl_err("SSL connect error\n");
		return -1;
	}
	return 0;
}
Example #8
0
void SSLContext::setSessionCacheContext(const std::string& context) {
  SSL_CTX_set_session_id_context(
      ctx_,
      reinterpret_cast<const unsigned char*>(context.data()),
      std::min(
          static_cast<int>(context.length()), SSL_MAX_SSL_SESSION_ID_LENGTH));
}
Example #9
0
static int openssl_ssl_ctx_sessions(lua_State*L)
{
  SSL_CTX* ctx = CHECK_OBJECT(1, SSL_CTX, "openssl.ssl_ctx");
  if (lua_isstring(L, 2))
  {
    size_t s;
    unsigned char* sid_ctx = (unsigned char*)luaL_checklstring(L, 2, &s);
    int ret = SSL_CTX_set_session_id_context(ctx, sid_ctx, s);
    lua_pushboolean(L, ret);
    return 1;
  }
  else
  {
    SSL_SESSION *s = CHECK_OBJECT(2, SSL_SESSION, "openssl.ssl_session");
    int add = 1;
    if (!lua_isnoneornil(L, 3))
      add = auxiliar_checkboolean(L, 3);

    if (add)
      add = SSL_CTX_add_session(ctx, s);
    else
      add = SSL_CTX_remove_session(ctx, s);

    lua_pushboolean(L, add);
    return 1;
  }
}
Example #10
0
    SSLManager::SSLManager(const Params& params) :
        _validateCertificates(false),
        _weakValidation(params.weakCertificateValidation) {

        SSL_library_init();
        SSL_load_error_strings();
        ERR_load_crypto_strings();

        if (params.fipsMode) {
            _setupFIPS();
        }

        // Add all digests and ciphers to OpenSSL's internal table
        // so that encryption/decryption is backwards compatible
        OpenSSL_add_all_algorithms();

        _context = SSL_CTX_new(SSLv23_method());
        massert(15864,
                mongoutils::str::stream() << "can't create SSL Context: " <<
                _getSSLErrorMessage(ERR_get_error()),
                _context);

        // Activate all bug workaround options, to support buggy client SSL's.
        SSL_CTX_set_options(_context, SSL_OP_ALL);

        // If renegotiation is needed, don't return from recv() or send() until it's successful.
        // Note: this is for blocking sockets only.
        SSL_CTX_set_mode(_context, SSL_MODE_AUTO_RETRY);

        // Set context within which session can be reused
        int status = SSL_CTX_set_session_id_context(
            _context,
            static_cast<unsigned char*>(static_cast<void*>(&_context)),
            sizeof(_context));
        if (!status) {
            uasserted(16768,"ssl initialization problem");
        }

        SSLThreadInfo::init();
        SSLThreadInfo::get();

        if (!params.pemfile.empty()) {
            if (!_setupPEM(params.pemfile, params.pempwd)) {
                uasserted(16562, "ssl initialization problem"); 
            }
        }
        if (!params.cafile.empty()) {
            // Set up certificate validation with a certificate authority
            if (!_setupCA(params.cafile)) {
                uasserted(16563, "ssl initialization problem"); 
            }
        }
        if (!params.crlfile.empty()) {
            if (!_setupCRL(params.crlfile)) {
                uasserted(16582, "ssl initialization problem");
            }
        }
    }
Example #11
0
    bool SSLManager::_initSSLContext(SSL_CTX** context, const Params& params) {
        *context = SSL_CTX_new(SSLv23_method());
        massert(15864,
                mongoutils::str::stream() << "can't create SSL Context: " <<
                getSSLErrorMessage(ERR_get_error()),
                context);

        // SSL_OP_ALL - Activate all bug workaround options, to support buggy client SSL's.
        // SSL_OP_NO_SSLv2 - Disable SSL v2 support 
        SSL_CTX_set_options(*context, SSL_OP_ALL|SSL_OP_NO_SSLv2);

        // If renegotiation is needed, don't return from recv() or send() until it's successful.
        // Note: this is for blocking sockets only.
        SSL_CTX_set_mode(*context, SSL_MODE_AUTO_RETRY);

        // Set context within which session can be reused
        int status = SSL_CTX_set_session_id_context(
            *context,
            static_cast<unsigned char*>(static_cast<void*>(context)),
            sizeof(*context));
 
        if (!status) {
            error() << "failed to set session id context: " << 
                getSSLErrorMessage(ERR_get_error()) << endl;
            return false;
        }

        // Use the clusterfile for internal outgoing SSL connections if specified 
        if (context == &_clientContext && !params.clusterfile.empty()) {
            EVP_set_pw_prompt("Enter cluster certificate passphrase");
            if (!_setupPEM(*context, params.clusterfile, params.clusterpwd)) {
                return false;
            }
        }
        // Use the pemfile for everything else
        else if (!params.pemfile.empty()) {
            EVP_set_pw_prompt("Enter PEM passphrase");
            if (!_setupPEM(*context, params.pemfile, params.pempwd)) {
                return false;
            }
        }

        if (!params.cafile.empty()) {
            // Set up certificate validation with a certificate authority
            if (!_setupCA(*context, params.cafile)) {
                return false;
            }
        }

        if (!params.crlfile.empty()) {
            if (!_setupCRL(*context, params.crlfile)) {
                return false;
            }
        }

        return true;
    }
Example #12
0
		Context(SSL_CTX* context)
			: ctx(context)
		{
			SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
			SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, OnVerify);

			const unsigned char session_id[] = "inspircd";
			SSL_CTX_set_session_id_context(ctx, session_id, sizeof(session_id) - 1);
		}
Example #13
0
static void tls_init_cache(void)
{
    static const char *tls_ctx_id = "pure-ftpd";

    SSL_CTX_set_session_cache_mode(tls_ctx, SSL_SESS_CACHE_SERVER);
    SSL_CTX_set_session_id_context(tls_ctx, (unsigned char *) tls_ctx_id,
                                   (unsigned int) strlen(tls_ctx_id));
    SSL_CTX_sess_set_cache_size(tls_ctx, 10);
    SSL_CTX_set_timeout(tls_ctx, 60 * 60L);
}
 void start() override {
   if(set_session_id_context) {
     // Creating session_id_context from address:port but reversed due to small SSL_MAX_SSL_SESSION_ID_LENGTH
     session_id_context = std::to_string(config.port) + ':';
     session_id_context.append(config.address.rbegin(), config.address.rend());
     SSL_CTX_set_session_id_context(context.native_handle(), reinterpret_cast<const unsigned char *>(session_id_context.data()),
                                    std::min<size_t>(session_id_context.size(), SSL_MAX_SSL_SESSION_ID_LENGTH));
   }
   ServerBase::start();
 }
Example #15
0
SSL_CTX * KSSLSocket::init_server(const char *cert_file, const char *key_file,
		const char *verified_file) {
	SSL_CTX * ctx = init_ctx(true);
	if (ctx == NULL) {
		fprintf(stderr, "cann't init_ctx\n");
		return NULL;
	}
	if (cert_file == NULL) {
		cert_file = key_file;
	}
	if (SSL_CTX_use_certificate_chain_file(ctx, cert_file) <= 0) {
		fprintf(stderr,
				"SSL use certificate file : Error allocating handle: %s\n",
				ERR_error_string(ERR_get_error(), NULL));
		clean_ctx(ctx);
		return NULL;
	}
	if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) {
		fprintf(stderr,
				"SSL use privatekey file: Error allocating handle: %s\n",
				ERR_error_string(ERR_get_error(), NULL));
		clean_ctx(ctx);
		return NULL;
	}

	if (!SSL_CTX_check_private_key(ctx)) {
		fprintf(stderr, "SSL: Error allocating handle: %s\n", ERR_error_string(
				ERR_get_error(), NULL));
		clean_ctx(ctx);
		return NULL;
	}
	if (verified_file) {
		SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER
				| SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL);
		SSL_CTX_set_verify_depth(ctx, 1);
		if (SSL_CTX_load_verify_locations(ctx, verified_file, NULL) <= 0) {
			fprintf(stderr, "SSL error %s:%d: Error allocating handle: %s\n",
					__FILE__, __LINE__, ERR_error_string(ERR_get_error(), NULL));
			clean_ctx(ctx);
			return NULL;
		}
	}
	int session_context_len = strlen(cert_file);
	const char *session_context = cert_file;
	int pos = session_context_len - SSL_MAX_SSL_SESSION_ID_LENGTH;
	if (pos>0) {
		session_context_len -= pos;
		session_context += pos;
	}
	SSL_CTX_set_session_id_context(ctx,(const unsigned char *)session_context,session_context_len);
	SSL_CTX_set_session_cache_mode(ctx,SSL_SESS_CACHE_SERVER);
	//SSL_CTX_sess_set_cache_size(ctx,1000);
	return ctx;
}
Example #16
0
/*
 * Setup default SSL_CTX (and SSL * ) behavior:
 *     verification, cipherlist, acceptable versions, ...
 */
static void
init_ssl_ctx_behavior( SSL_CTX *_ctx ) {
	int verify_mode;
	if( tls_ciphers_list != 0 ) {
		if( SSL_CTX_set_cipher_list(_ctx, tls_ciphers_list) == 0 )
			LOG( L_ERR, "init_tls: failure to set SSL context cipher list\n");
		else
			LOG( 2, "TLS: cipher list set to %s\n", tls_ciphers_list);
	} else {
		DBG( "TLS: cipher list null ... setting default\n");
	}

	/* Set a bunch of options: 
	 *     do not accept SSLv2
	 *     no session resumption
	 *     choose cipher according to server's preference's*/

#if OPENSSL_VERSION_NUMBER >= 0x000907000
	SSL_CTX_set_options(_ctx, 
			SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | SSL_OP_CIPHER_SERVER_PREFERENCE);
#else
	SSL_CTX_set_options(_ctx, 
			SSL_OP_ALL | SSL_OP_NO_SSLv2 );
#endif

	/* Set verification procedure
	 * The verification can be made null with SSL_VERIFY_NONE, or 
	 * at least easier with SSL_VERIFY_CLIENT_ONCE instead of SSL_VERIFY_FAIL_IF_NO_PEER_CERT.
	 *   For extra control, instead of 0, we can specify a callback function:
	 *           int (*verify_callback)(int, X509_STORE_CTX *)
	 * Also, depth 2 may be not enough in some scenarios ... though no need
	 * to increase it much further */
	/*SSL_CTX_set_verify( _ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); */
	//SSL_CTX_set_verify( _ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, verify_callback);
	//SSL_CTX_set_verify( _ctx, SSL_VERIFY_NONE, NULL);
	verify_mode = SSL_VERIFY_NONE;
	if( tls_verify_cert ) {
		verify_mode |= SSL_VERIFY_PEER;
		if( tls_require_cert ) {
			LOG( L_WARN, "TLS: Verification activated. Client certificates are mandatory.\n");
			verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
		} else
			LOG( L_WARN, "TLS: Verification activated. Client certificates are NOT mandatory.\n");
	} else 
		LOG( L_WARN, "TLS: Verification NOT activated. Weaker security.\n");
	
	SSL_CTX_set_verify( _ctx, verify_mode, verify_callback);	
	SSL_CTX_set_verify_depth( _ctx, VERIFY_DEPTH_S);
	
	SSL_CTX_set_session_cache_mode( _ctx, SSL_SESS_CACHE_SERVER );
	SSL_CTX_set_session_id_context( _ctx, SER_SSL_SESS_ID, SER_SSL_SESS_ID_LEN );
}
Example #17
0
void SslHelper::enableSslSessionCache(SSL_CTX* ctx)
{
    unsigned char        sidCtx[16]{};
    const unsigned char* ln = reinterpret_cast<const unsigned char*>(
        "0123456789abcdefghijklmnopqrstuvwxyz");
    MtRandom r;

    for (auto i = 0u; i < sizeof(sidCtx) - 1; ++i)
    {
        sidCtx[i] = ln[r.random(36)]; // 10 numbers + 26 letters.
    }

    SSL_CTX_set_session_id_context(ctx, sidCtx, sizeof(sidCtx));
}
Example #18
0
/**
 * It initializes the global context ssl
 * @param : path of the server certificate
 * @param : cert verification mode @see SSL_CTX_set_verify
 * @return: 0 on success;
 */
SSL_CTX * Sock_init_ctx(char *key, char * cafile, char * capath)
{
    SSL_CTX *global_ctx = NULL;
    char cipher[] = "ALL:eNULL";
    int s_server_session_id_context = 1;
    SSL_METHOD *method;

    SSL_load_error_strings();
    SSL_library_init();

    method = SSLv23_method();
    global_ctx = SSL_CTX_new(method);
    if(!global_ctx) {
        net_log(NET_LOG_ERR,"Creation of a new SSL_CTX object failed");
        return NULL;
    }

    /* Loads a certificate chain from file into ctx */
    if(!(SSL_CTX_use_certificate_chain_file(global_ctx,key))) {
        net_log(NET_LOG_ERR,"Failure in reading certificate file");
        return NULL;
    }

    /* Adds the first private key found in file to ctx */
    if(!(SSL_CTX_use_PrivateKey_file(global_ctx,key,SSL_FILETYPE_PEM))) {
        net_log(NET_LOG_ERR,"Failure in reading key file");
        return NULL;
    }

    /* Set default locations for trusted CA certificates */
    if(!(SSL_CTX_load_verify_locations(global_ctx, cafile, capath))) {
        net_log(NET_LOG_ERR,"Failure in reading CA list");
        return NULL;
    }

    /* Set context within which session can be reused */
    SSL_CTX_set_session_id_context(global_ctx,
                                   (void*)&s_server_session_id_context,
        sizeof(s_server_session_id_context));

    /* Choose list of available SSL_CIPHER */
    SSL_CTX_set_cipher_list(global_ctx,cipher);

    /* Manipulate SSL engine options */
    //SSL_CTX_set_options(ctx,SSL_OP_ALL);

    SSL_CTX_set_verify(global_ctx,SSL_VERIFY_PEER,0);

    return global_ctx;
}
Example #19
0
int
tls_configure_server(struct tls *ctx)
{
	EC_KEY *ecdh_key;
	unsigned char sid[SSL_MAX_SSL_SESSION_ID_LENGTH];

	if ((ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) {
		tls_set_error(ctx, "ssl context failure");
		goto err;
	}

	if (tls_configure_ssl(ctx) != 0)
		goto err;
	if (tls_configure_keypair(ctx) != 0)
		goto err;

	if (ctx->config->dheparams == -1)
		SSL_CTX_set_dh_auto(ctx->ssl_ctx, 1);
	else if (ctx->config->dheparams == 1024)
		SSL_CTX_set_dh_auto(ctx->ssl_ctx, 2);

	if (ctx->config->ecdhecurve == -1) {
		SSL_CTX_set_ecdh_auto(ctx->ssl_ctx, 1);
	} else if (ctx->config->ecdhecurve != NID_undef) {
		if ((ecdh_key = EC_KEY_new_by_curve_name(
		    ctx->config->ecdhecurve)) == NULL) {
			tls_set_error(ctx, "failed to set ECDHE curve");
			goto err;
		}
		SSL_CTX_set_options(ctx->ssl_ctx, SSL_OP_SINGLE_ECDH_USE);
		SSL_CTX_set_tmp_ecdh(ctx->ssl_ctx, ecdh_key);
		EC_KEY_free(ecdh_key);
	}

	/*
	 * Set session ID context to a random value.  We don't support
	 * persistent caching of sessions so it is OK to set a temporary
	 * session ID context that is valid during run time.
	 */
	arc4random_buf(sid, sizeof(sid));
	if (!SSL_CTX_set_session_id_context(ctx->ssl_ctx, sid, sizeof(sid))) {
		tls_set_error(ctx, "failed to set session id context");
		goto err;
	}

	return (0);

err:
	return (-1);
}
Example #20
0
int
rb_init_ssl(void)
{
	int ret = 1;
	char libratbox_data[] = "libratbox data";
	SSL_load_error_strings();
	SSL_library_init();
	libratbox_index = SSL_get_ex_new_index(0, libratbox_data, NULL, NULL, NULL);
	ssl_server_ctx = SSL_CTX_new(SSLv23_server_method());
	if(ssl_server_ctx == NULL)
	{
		rb_lib_log("rb_init_openssl: Unable to initialize OpenSSL server context: %s",
			   get_ssl_error(ERR_get_error()));
		ret = 0;
	}
	/* Disable SSLv2, make the client use our settings */
	SSL_CTX_set_options(ssl_server_ctx, SSL_OP_NO_SSLv2 | SSL_OP_CIPHER_SERVER_PREFERENCE
#ifdef SSL_OP_SINGLE_DH_USE
			| SSL_OP_SINGLE_DH_USE
#endif
			);
	SSL_CTX_set_verify(ssl_server_ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, verify_accept_all_cb);
	SSL_CTX_set_session_id_context(ssl_server_ctx,
			(const unsigned char *)"libratbox", 9);
	SSL_CTX_set_cipher_list(ssl_server_ctx, "EECDH+HIGH:EDH+HIGH:HIGH:!aNULL");

	/* Set ECDHE on OpenSSL 1.00+, but make sure it's actually available because redhat are dicks
	   and bastardise their OpenSSL for stupid reasons... */
	#if (OPENSSL_VERSION_NUMBER >= 0x10000000) && defined(NID_secp384r1)
		EC_KEY *key = EC_KEY_new_by_curve_name(NID_secp384r1);
		if (key) {
			SSL_CTX_set_tmp_ecdh(ssl_server_ctx, key);
			EC_KEY_free(key);
		}
#ifdef SSL_OP_SINGLE_ECDH_USE
		SSL_CTX_set_options(ssl_server_ctx, SSL_OP_SINGLE_ECDH_USE);
#endif
	#endif

	ssl_client_ctx = SSL_CTX_new(TLSv1_client_method());

	if(ssl_client_ctx == NULL)
	{
		rb_lib_log("rb_init_openssl: Unable to initialize OpenSSL client context: %s",
			   get_ssl_error(ERR_get_error()));
		ret = 0;
	}
	return ret;
}
Example #21
0
tls_t *tls_init_master(tls_issues_t *ti)
{
  /* Default id in case RAND fails */
  unsigned char sessionId[32] = "sofia/tls";
  tls_t *tls;

#if HAVE_SIGPIPE
  signal(SIGPIPE, SIG_IGN);  /* Ignore spurios SIGPIPE from OpenSSL */
#endif

  tls_set_default(ti);

  if (!(tls = tls_create(tls_master)))
    return NULL;

  if (tls_init_context(tls, ti) < 0) {
    int err = errno;
    tls_free(tls);
    errno = err;
    return NULL;
  }

  RAND_pseudo_bytes(sessionId, sizeof(sessionId));

  SSL_CTX_set_session_id_context(tls->ctx,
                                 (void*) sessionId,
				 sizeof(sessionId));

  if (ti->CAfile != NULL)
    SSL_CTX_set_client_CA_list(tls->ctx,
                               SSL_load_client_CA_file(ti->CAfile));

#if 0
  if (sock != -1) {
    tls->bio_con = BIO_new_socket(sock, BIO_NOCLOSE);

    if (tls->bio_con == NULL) {
      tls_log_errors(1, "tls_init_master", 0);
      tls_free(tls);
      errno = EIO;
      return NULL;
    }
  }
#endif

  return tls;
}
Example #22
0
void swSSL_server_http_advise(SSL_CTX* ssl_context, swSSL_config *cfg)
{
#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
    SSL_CTX_set_alpn_select_cb(ssl_context, swSSL_alpn_advertised, cfg);
#endif

#ifdef TLSEXT_TYPE_next_proto_neg
    SSL_CTX_set_next_protos_advertised_cb(ssl_context, swSSL_npn_advertised, cfg);
#endif

    if (cfg->http)
    {
        SSL_CTX_set_session_id_context(ssl_context, (const unsigned char *) "HTTP", strlen("HTTP"));
        SSL_CTX_set_session_cache_mode(ssl_context, SSL_SESS_CACHE_SERVER);
        SSL_CTX_sess_set_cache_size(ssl_context, 1);
    }
}
Example #23
0
void SSLContext::enableSessionCache(bool flag, const std::string& sessionIdContext)
{
    assert(isForServerUse());

    if (flag)
    {
        SSL_CTX_set_session_cache_mode(_sslContext, SSL_SESS_CACHE_SERVER);
    }
    else
    {
        SSL_CTX_set_session_cache_mode(_sslContext, SSL_SESS_CACHE_OFF);
    }
    
    unsigned length = static_cast<unsigned>(sessionIdContext.length());
    if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) length = SSL_MAX_SSL_SESSION_ID_LENGTH;
    int rc = SSL_CTX_set_session_id_context(_sslContext, reinterpret_cast<const unsigned char*>(sessionIdContext.data()), length);
    if (rc != 1) throw std::runtime_error("SSL Error: cannot set session ID context");
}
Example #24
0
SSL_CTX * KSSLSocket::init_client(const char *path, const char *file) {
	SSL_CTX *ctx = init_ctx(false);
	if (ctx) {
		if (file != NULL) {
			SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
			SSL_CTX_set_verify_depth(ctx, 1);

			if (SSL_CTX_load_verify_locations(ctx, file, path) <= 0) {
				fprintf(stderr, "SSL error %s:%d: Error allocating handle: %s\n",
						__FILE__, __LINE__, ERR_error_string(ERR_get_error(), NULL));
				clean_ctx(ctx);
				return NULL;
			}
		}
		SSL_CTX_set_session_id_context(ctx,(const unsigned char *)PROGRAM_NAME,sizeof(PROGRAM_NAME)-1);
		SSL_CTX_set_session_cache_mode(ctx,SSL_SESS_CACHE_BOTH);
	}
	return ctx;
}
Example #25
0
int
ssl_setup(SSL_CTX **ctxp, struct pki *pki, int (*sni_cb)(SSL *,int *,void *),
    const char *ciphers, const char *curve)
{
	DH	*dh;
	SSL_CTX	*ctx;
	u_int8_t sid[SSL_MAX_SID_CTX_LENGTH];

	ctx = ssl_ctx_create(pki->pki_name, pki->pki_cert, pki->pki_cert_len, ciphers);

        /*
         * Set session ID context to a random value.  We don't support
         * persistent caching of sessions so it is OK to set a temporary
         * session ID context that is valid during run time.
         */
        arc4random_buf(sid, sizeof(sid));
        if (!SSL_CTX_set_session_id_context(ctx, sid, sizeof(sid)))
                goto err;

	SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, dummy_verify);
	if (sni_cb)
		SSL_CTX_set_tlsext_servername_callback(ctx, sni_cb);

	if (pki->pki_dhparams_len == 0)
		dh = get_dh();
	else
		dh = get_dh_from_memory(pki->pki_dhparams,
		    pki->pki_dhparams_len);
	ssl_set_ephemeral_key_exchange(ctx, dh);
	DH_free(dh);

	ssl_set_ecdh_curve(ctx, curve);

	*ctxp = ctx;
	return 1;

err:
	SSL_CTX_free(ctx);
	ssl_error("ssl_setup");
	return 0;
}
Example #26
0
int swSSL_server_config(SSL_CTX* ssl_context, swSSL_config *cfg)
{
#ifndef TLS1_2_VERSION
    return SW_OK;
#endif
    SSL_CTX_set_read_ahead(ssl_context, 1);

#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
    SSL_CTX_set_alpn_select_cb(ssl_context, swSSL_alpn_advertised, cfg);
#endif

#ifdef TLSEXT_TYPE_next_proto_neg
    SSL_CTX_set_next_protos_advertised_cb(ssl_context, swSSL_npn_advertised, cfg);
#endif

    if (SSL_CTX_set_cipher_list(ssl_context, cfg->ciphers) == 0)
    {
        swWarn("SSL_CTX_set_cipher_list(\"%s\") failed", SW_SSL_CIPHER_LIST);
        return SW_ERR;
    }
    if (cfg->prefer_server_ciphers)
    {
        SSL_CTX_set_options(ssl_context, SSL_OP_CIPHER_SERVER_PREFERENCE);
    }

#ifndef LIBRESSL_VERSION_NUMBER
    SSL_CTX_set_tmp_rsa_callback(ssl_context, swSSL_rsa512_key_callback);
#endif

    swSSL_set_dhparam(ssl_context);
    swSSL_set_ecdh_curve(ssl_context);

    if (cfg->http)
    {
        SSL_CTX_set_session_id_context(ssl_context, (const unsigned char *) "HTTP", strlen("HTTP"));
        SSL_CTX_set_session_cache_mode(ssl_context, SSL_SESS_CACHE_SERVER);
        SSL_CTX_sess_set_cache_size(ssl_context, 1);
    }
    return SW_OK;
}
Example #27
0
/**
 * @brief Configure TLS session cache parameters 
 * @param d domain
 * @return 0
 */
static int set_session_cache(tls_domain_t* d)
{
	int i;
	int procs_no;
	str tls_session_id;
	
	procs_no=get_max_procs();
	tls_session_id=cfg_get(tls, tls_cfg, session_id);
	for(i = 0; i < procs_no; i++) {
		/* janakj: I am not sure if session cache makes sense in ser, session
		 * cache is stored in SSL_CTX and we have one SSL_CTX per process,
		 * thus sessions among processes will not be reused
		 */
		SSL_CTX_set_session_cache_mode(d->ctx[i],
				cfg_get(tls, tls_cfg, session_cache) ? SSL_SESS_CACHE_SERVER :
				SSL_SESS_CACHE_OFF);
		/* not really needed is SSL_SESS_CACHE_OFF */
		SSL_CTX_set_session_id_context(d->ctx[i],
					(unsigned char*)tls_session_id.s, tls_session_id.len);
	}
	return 0;
}
SSLSessionCacheManager::SSLSessionCacheManager(
    uint32_t maxCacheSize,
    uint32_t cacheCullSize,
    SSLContext* ctx,
    const folly::SocketAddress& sockaddr,
    const string& context,
    EventBase* eventBase,
    SSLStats* stats,
    const std::shared_ptr<SSLCacheProvider>& externalCache):
    ctx_(ctx),
    stats_(stats),
    externalCache_(externalCache) {

    SSL_CTX* sslCtx = ctx->getSSLCtx();

    SSLUtil::getSSLCtxExIndex(&sExDataIndex_);

    SSL_CTX_set_ex_data(sslCtx, sExDataIndex_, this);
    SSL_CTX_sess_set_new_cb(sslCtx, SSLSessionCacheManager::newSessionCallback);
    SSL_CTX_sess_set_get_cb(sslCtx, SSLSessionCacheManager::getSessionCallback);
    SSL_CTX_sess_set_remove_cb(sslCtx,
                               SSLSessionCacheManager::removeSessionCallback);
    if (!FLAGS_dcache_unit_test && !context.empty()) {
        // Use the passed in context
        SSL_CTX_set_session_id_context(sslCtx, (const uint8_t *)context.data(),
                                       std::min((int)context.length(),
                                                SSL_MAX_SSL_SESSION_ID_LENGTH));
    }

    SSL_CTX_set_session_cache_mode(sslCtx, SSL_SESS_CACHE_NO_INTERNAL
                                   | SSL_SESS_CACHE_SERVER);

    localCache_ = SSLSessionCacheManager::getLocalCache(maxCacheSize,
                  cacheCullSize);

    VLOG(2) << "On VipID=" << sockaddr.describe() << " context=" << context;
}
Example #29
0
int
lws_tls_server_client_cert_verify_config(struct lws_vhost *vh)
{
	int verify_options = SSL_VERIFY_PEER;

	/* as a server, are we requiring clients to identify themselves? */

	if (!lws_check_opt(vh->options,
			  LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT))
		return 0;

	if (!lws_check_opt(vh->options,
			   LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED))
		verify_options |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;

	SSL_CTX_set_session_id_context(vh->tls.ssl_ctx, (uint8_t *)vh->context,
				       sizeof(void *));

	/* absolutely require the client cert */
	SSL_CTX_set_verify(vh->tls.ssl_ctx, verify_options,
			   OpenSSL_verify_callback);

	return 0;
}
Example #30
0
SslContext_t::SslContext_t (bool is_server, const string &privkeyfile, const string &certchainfile):
	pCtx (NULL),
	PrivateKey (NULL),
	Certificate (NULL)
{
	/* TODO: the usage of the specified private-key and cert-chain filenames only applies to
	 * client-side connections at this point. Server connections currently use the default materials.
	 * That needs to be fixed asap.
	 * Also, in this implementation, server-side connections use statically defined X-509 defaults.
	 * One thing I'm really not clear on is whether or not you have to explicitly free X509 and EVP_PKEY
	 * objects when we call our destructor, or whether just calling SSL_CTX_free is enough.
	 */

	if (!bLibraryInitialized) {
		bLibraryInitialized = true;
		SSL_library_init();
		OpenSSL_add_ssl_algorithms();
		OpenSSL_add_all_algorithms();
		SSL_load_error_strings();
		ERR_load_crypto_strings();

		InitializeDefaultCredentials();
	}

	bIsServer = is_server;
	pCtx = SSL_CTX_new (is_server ? SSLv23_server_method() : SSLv23_client_method());
	if (!pCtx)
		throw std::runtime_error ("no SSL context");

	SSL_CTX_set_options (pCtx, SSL_OP_ALL);
	//SSL_CTX_set_options (pCtx, (SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3));
#ifdef SSL_MODE_RELEASE_BUFFERS
	SSL_CTX_set_mode (pCtx, SSL_MODE_RELEASE_BUFFERS);
#endif

	if (is_server) {
		// The SSL_CTX calls here do NOT allocate memory.
		int e;
		if (privkeyfile.length() > 0)
			e = SSL_CTX_use_PrivateKey_file (pCtx, privkeyfile.c_str(), SSL_FILETYPE_PEM);
		else
			e = SSL_CTX_use_PrivateKey (pCtx, DefaultPrivateKey);
		if (e <= 0) ERR_print_errors_fp(stderr);
		assert (e > 0);

		if (certchainfile.length() > 0)
			e = SSL_CTX_use_certificate_chain_file (pCtx, certchainfile.c_str());
		else
			e = SSL_CTX_use_certificate (pCtx, DefaultCertificate);
		if (e <= 0) ERR_print_errors_fp(stderr);
		assert (e > 0);
	}

	SSL_CTX_set_cipher_list (pCtx, "ALL:!ADH:!LOW:!EXP:!DES-CBC3-SHA:@STRENGTH");

	if (is_server) {
		SSL_CTX_sess_set_cache_size (pCtx, 128);
		SSL_CTX_set_session_id_context (pCtx, (unsigned char*)"eventmachine", 12);
	}
	else {
		int e;
		if (privkeyfile.length() > 0) {
			e = SSL_CTX_use_PrivateKey_file (pCtx, privkeyfile.c_str(), SSL_FILETYPE_PEM);
			if (e <= 0) ERR_print_errors_fp(stderr);
			assert (e > 0);
		}
		if (certchainfile.length() > 0) {
			e = SSL_CTX_use_certificate_chain_file (pCtx, certchainfile.c_str());
			if (e <= 0) ERR_print_errors_fp(stderr);
			assert (e > 0);
		}
	}
}