Exemple #1
0
void ssl_init_Engine(server_rec *s, apr_pool_t *p)
{
    SSLModConfigRec *mc = myModConfig(s);
    ENGINE *e;

    if (mc->szCryptoDevice) {
        if (!(e = ENGINE_by_id(mc->szCryptoDevice))) {
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
                         "Init: Failed to load Crypto Device API `%s'",
                         mc->szCryptoDevice);
            ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
            ssl_die();
        }

        if (strEQ(mc->szCryptoDevice, "chil")) {
            ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
        }

        if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
            ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
                         "Init: Failed to enable Crypto Device API `%s'",
                         mc->szCryptoDevice);
            ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
            ssl_die();
        }
        ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, 
                     "Init: loaded Crypto Device API `%s'", 
                     mc->szCryptoDevice);

        ENGINE_free(e);
    }
}
Exemple #2
0
static int openssl_engine_set_default(lua_State*L){
	ENGINE* eng = CHECK_OBJECT(1,ENGINE,"openssl.engine");
	int ret = 0;
	int first = 3;
	int top = lua_gettop(L);
	if(top==2){
		if(lua_isnumber(L, 2))
		{
			int methods = luaL_checkint(L, 2);
			ret = ENGINE_set_default(eng, methods);
		}else if(lua_isstring(L,2)){
			const char* s = luaL_checkstring(L, 2);
			ret = ENGINE_set_default_string(eng, s);
		}else
			luaL_error(L, "#2 must be a number or string");
		lua_pushboolean(L, ret);
		return 1;
	}

	while(first<=top){
		int c = luaL_checkoption(L, first, "RSA",list);
		switch(c){
		case 0:
			ret = ENGINE_set_default_RSA(eng);
			break;
		case 1:
			ret = ENGINE_set_default_DSA(eng);
			break;
		case 2:
			ret = ENGINE_set_default_ECDH(eng);
			break;
		case 3:
			ret = ENGINE_set_default_ECDSA(eng);
			break;
		case 4:
			ret = ENGINE_set_default_DH(eng);
			break;
		case 5:
			ret = ENGINE_set_default_RAND(eng);
			break;
		case 7:
			ret = ENGINE_set_default_ciphers(eng);
			break;
		case 8:
			ret = ENGINE_set_default_digests(eng);
			break;
		case 6:
		default:
			luaL_error(L,"not support %d for %s",c, list[c]);
			break;
		}
		first++;
		if(ret!=1){
			lua_pushboolean(L, 0);
			return 1;
		}
	}
	lua_pushboolean(L, ret);
	return 1;
};
Exemple #3
0
void
tor_init_with_engine (const char* name, const char* path)
{
	ENGINE* engine;

	if (initialized) {
		return;
	}

	tor_init();

	if (path == NULL) {
		engine = ENGINE_by_id(name);
	}
	else {
		engine = ENGINE_by_id("dynamic");

		if (!ENGINE_ctrl_cmd_string(engine, "ID", name, 0) ||
		    !ENGINE_ctrl_cmd_string(engine, "DIR_LOAD", "2", 0) ||
		    !ENGINE_ctrl_cmd_string(engine, "DIR_ADD", path, 0) ||
		    !ENGINE_ctrl_cmd_string(engine, "LOAD", NULL, 0)) {
			ENGINE_free(engine);
			engine = NULL;
		}
	}

	if (engine) {
		ENGINE_set_default(engine, ENGINE_METHOD_ALL);
	}
}
Exemple #4
0
int TS_CONF_set_default_engine(const char *name)
	{
	ENGINE *e = NULL;
	int ret = 0;

	/* Leave the default if builtin specified. */
	if (strcmp(name, "builtin") == 0) return 1;

	if (!(e = ENGINE_by_id(name))) goto err;
	/* Enable the use of the NCipher HSM for forked children. */
	if (strcmp(name, "chil") == 0) 
		ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
	/* All the operations are going to be carried out by the engine. */
	if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) goto err;
	ret = 1;
 err:
	if (!ret)
		{
		TSerr(TS_F_TS_CONF_SET_DEFAULT_ENGINE, 
		      TS_R_COULD_NOT_SET_ENGINE);
		ERR_add_error_data(2, "engine:", name);
		}
	if (e) ENGINE_free(e);
	return ret;
	}
Exemple #5
0
static int load_engine(void **ctx,MESSAGE *msg)
{
	int i;
	ENGINE **e=(ENGINE **)ctx;

	ENGINE_load_dynamic();

	if(!(*e=ENGINE_by_id("dynamic")))goto err1;

	if(!ENGINE_ctrl_cmd_string(*e,"SO_PATH",msg->engine,0))goto err2;
	for(i=0;pkcs11[i].name;i++)
		if(!ENGINE_ctrl_cmd_string(*e,pkcs11[i].name,pkcs11[i].value,0))
			goto err2;
	if(!ENGINE_ctrl_cmd_string(*e,"MODULE_PATH",msg->pkcs11,0))goto err2;
	if(msg->nopin)if(!ENGINE_ctrl_cmd_string(*e,"NOLOGIN","1",0))goto err2;
	if(!ENGINE_ctrl_cmd_string(*e,"PIN",msg->nopin?"":msg->pin,0))goto err2;
	if(!ENGINE_init(*e))
	{
err2:		ENGINE_free(*e);
err1:		ENGINE_cleanup();
		return ENGFAIL;
	}

	ENGINE_free(*e);

	ENGINE_set_default(*e,ENGINE_METHOD_ALL&~ENGINE_METHOD_RAND);

	return OK;
}
Exemple #6
0
static ENGINE *
setup_engine (const char *engine)
{
  ENGINE *e = NULL;

  ENGINE_load_builtin_engines ();

  if (engine)
    {
      if (strcmp (engine, "auto") == 0)
	{
	  msg (M_INFO, "Initializing OpenSSL auto engine support");
	  ENGINE_register_all_complete ();
	  return NULL;
	}
      if ((e = ENGINE_by_id (engine)) == NULL
	 && (e = try_load_engine (engine)) == NULL)
	{
	  msg (M_FATAL, "OpenSSL error: cannot load engine '%s'", engine);
	}

      if (!ENGINE_set_default (e, ENGINE_METHOD_ALL))
	{
	  msg (M_FATAL, "OpenSSL error: ENGINE_set_default failed on engine '%s'",
	       engine);
	}

      msg (M_INFO, "Initializing OpenSSL support for engine '%s'",
	   ENGINE_get_id (e));
    }
  return e;
}
Exemple #7
0
int main(int argc, char **argv) {
	OpenSSL_add_all_algorithms();
	
	int len = 128 * MB;
	if (argc > 1) {
		len = atoi(argv[1]) * MB;
	}
	
	unsigned char *buf = (unsigned char *) malloc(TOTAL_LEN);
	if (!buf) {
		fprintf(stderr, "Error Allocating Memory");
	}
	
	ENGINE_load_builtin_engines();
#ifdef OPENCL_ENGINE
	ENGINE *e = ENGINE_by_id("dynamic");
	if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", OPENCL_ENGINE, 0) ||
		!ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) {
		fprintf(stderr, "Failed to load OpenCL engine!\n");
		return -1;
	}
	ENGINE_set_default(e, ENGINE_METHOD_ALL);
#endif
	
	run(argv[0], buf, len);
	
	free(buf);
	
	return 0;
}
/* Use AES-NI if available. This is not supported with low-level calls,
   we have to use EVP) */
static void init_aesni(void)
{
	ENGINE *e;
	const char *engine_id = "aesni";

	ENGINE_load_builtin_engines();
	e = ENGINE_by_id(engine_id);
	if (!e) {
		//fprintf(stderr, "AES-NI engine not available\n");
		return;
	}
	if (!ENGINE_init(e)) {
		fprintf(stderr, "AES-NI engine could not init\n");
		ENGINE_free(e);
		return;
	}
	if (!ENGINE_set_default(e, ENGINE_METHOD_ALL & ~ENGINE_METHOD_RAND)) {
		/* This should only happen when 'e' can't initialise, but the
		 * previous statement suggests it did. */
		fprintf(stderr, "AES-NI engine initialized but then failed\n");
		abort();
	}
	ENGINE_finish(e);
	ENGINE_free(e);
}
Exemple #9
0
void
sc_pkcs11_register_openssl_mechanisms(struct sc_pkcs11_card *card)
{
#if OPENSSL_VERSION_NUMBER >= 0x10000000L && !defined(OPENSSL_NO_ENGINE)
	void (*locking_cb)(int, int, const char *, int);
	ENGINE *e;

	locking_cb = CRYPTO_get_locking_callback();
	if (locking_cb)
		CRYPTO_set_locking_callback(NULL);

	e = ENGINE_by_id("gost");
	if (!e)
	{
#if !defined(OPENSSL_NO_STATIC_ENGINE) && !defined(OPENSSL_NO_GOST)
		ENGINE_load_gost();
		e = ENGINE_by_id("gost");
#else
		/* try to load dynamic gost engine */
		e = ENGINE_by_id("dynamic");
		if (!e) {
			ENGINE_load_dynamic();
			e = ENGINE_by_id("dynamic");
		}
		if (e && (!ENGINE_ctrl_cmd_string(e, "SO_PATH", "gost", 0) ||
					!ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))) {
			ENGINE_free(e);
			e = NULL;
		}
#endif /* !OPENSSL_NO_STATIC_ENGINE && !OPENSSL_NO_GOST */
	}
	if (e) {
		ENGINE_set_default(e, ENGINE_METHOD_ALL);
		ENGINE_free(e);
	}

	if (locking_cb)
		CRYPTO_set_locking_callback(locking_cb);
#endif /* OPENSSL_VERSION_NUMBER >= 0x10000000L && !defined(OPENSSL_NO_ENGINE) */

	openssl_sha1_mech.mech_data = EVP_sha1();
	sc_pkcs11_register_mechanism(card, &openssl_sha1_mech);
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
	openssl_sha256_mech.mech_data = EVP_sha256();
	sc_pkcs11_register_mechanism(card, &openssl_sha256_mech);
	openssl_sha384_mech.mech_data = EVP_sha384();
	sc_pkcs11_register_mechanism(card, &openssl_sha384_mech);
	openssl_sha512_mech.mech_data = EVP_sha512();
	sc_pkcs11_register_mechanism(card, &openssl_sha512_mech);
#endif
	openssl_md5_mech.mech_data = EVP_md5();
	sc_pkcs11_register_mechanism(card, &openssl_md5_mech);
	openssl_ripemd160_mech.mech_data = EVP_ripemd160();
	sc_pkcs11_register_mechanism(card, &openssl_ripemd160_mech);
#if OPENSSL_VERSION_NUMBER >= 0x10000000L
	openssl_gostr3411_mech.mech_data = EVP_get_digestbynid(NID_id_GostR3411_94);
	sc_pkcs11_register_mechanism(card, &openssl_gostr3411_mech);
#endif
}
Exemple #10
0
int ENGINE_set_default_string(ENGINE *e, const char *def_list)
{
    unsigned int flags = 0;
    if (!CONF_parse_list(def_list, ',', 1, int_def_cb, &flags)) {
        ENGINEerr(ENGINE_F_ENGINE_SET_DEFAULT_STRING,
                  ENGINE_R_INVALID_STRING);
        ERR_add_error_data(2, "str=", def_list);
        return 0;
    }
    return ENGINE_set_default(e, flags);
}
Exemple #11
0
static VALUE
ossl_engine_set_default(VALUE self, VALUE flag)
{
    ENGINE *e;
    int f = NUM2INT(flag);

    GetEngine(self, e);
    ENGINE_set_default(e, f);

    return Qtrue;
}
void initializeSecHandler()
{
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();

	// <FS:ND If we can, enabled the rdrand engine. It is available as a CPU instruction on newer Intel CPUs
	ENGINE_load_builtin_engines();
	
	ENGINE* engRdRand = ENGINE_by_id("rdrand");
	if( engRdRand )
		ENGINE_set_default(engRdRand, ENGINE_METHOD_RAND);
	
	unsigned long lErr ( ERR_get_error() );
	while( lErr )
	{
		char aError[128];
		ERR_error_string_n( lErr, aError, sizeof( aError ) );
		LL_WARNS() << aError << LL_ENDL;

		lErr = ERR_get_error();
	}
	// </FS:ND>
		
	gHandlerMap[BASIC_SECHANDLER] = new LLSecAPIBasicHandler();
	
	
	// Currently, we only have the Basic handler, so we can point the main sechandler
	// pointer to the basic handler.  Later, we'll create a wrapper handler that
	// selects the appropriate sechandler as needed, for instance choosing the
	// mac keyring handler, with fallback to the basic sechandler
	gSecAPIHandler = gHandlerMap[BASIC_SECHANDLER];

	// initialize all SecAPIHandlers
	std::string exception_msg;
	std::map<std::string, LLPointer<LLSecAPIHandler> >::const_iterator itr;
	for(itr = gHandlerMap.begin(); itr != gHandlerMap.end(); ++itr)
	{
		LLPointer<LLSecAPIHandler> handler = (*itr).second;
		try 
		{
			handler->init();
		}
		catch (LLProtectedDataException e)
		{
			exception_msg = e.getMessage();
		}
	}
	if (!exception_msg.empty())  // an exception was thrown.
	{
		throw LLProtectedDataException(exception_msg.c_str());
	}

}
Exemple #13
0
isc_result_t
dst__openssl_setdefault(const char *name) {

	UNUSED(name);

#if defined(USE_ENGINE)
	ENGINE_set_default(e, ENGINE_METHOD_ALL);
#endif
	/*
	 * XXXMPA If the engine does not have a default RAND method
	 * restore our method.
	 */
	return (ISC_R_SUCCESS);
}
Exemple #14
0
int
sldns_key_EVP_load_gost_id(void)
{
	static int gost_id = 0;
	const EVP_PKEY_ASN1_METHOD* meth;
	ENGINE* e;

	if(gost_id) return gost_id;

	/* see if configuration loaded gost implementation from other engine*/
	meth = EVP_PKEY_asn1_find_str(NULL, "gost2001", -1);
	if(meth) {
		EVP_PKEY_asn1_get0_info(&gost_id, NULL, NULL, NULL, NULL, meth);
		return gost_id;
	}

	/* see if engine can be loaded already */
	e = ENGINE_by_id("gost");
	if(!e) {
		/* load it ourself, in case statically linked */
		ENGINE_load_builtin_engines();
		ENGINE_load_dynamic();
		e = ENGINE_by_id("gost");
	}
	if(!e) {
		/* no gost engine in openssl */
		return 0;
	}
	if(!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
		ENGINE_finish(e);
		ENGINE_free(e);
		return 0;
	}

	meth = EVP_PKEY_asn1_find_str(&e, "gost2001", -1);
	if(!meth) {
		/* algo not found */
		ENGINE_finish(e);
		ENGINE_free(e);
		return 0;
	}
        /* Note: do not ENGINE_finish and ENGINE_free the acquired engine
         * on some platforms this frees up the meth and unloads gost stuff */
        sldns_gost_engine = e;
	
	EVP_PKEY_asn1_get0_info(&gost_id, NULL, NULL, NULL, NULL, meth);
	return gost_id;
} 
Exemple #15
0
void Engines::setEngineDefault(Engine &engine, Engine::Algorithm algorithm)
		throw (EngineException)
{
	unsigned int flag;
	ENGINE *e;
	e = engine.getEngine();
	if (!e)
	{
		throw EngineException(EngineException::INVALID_ENGINE, "Engines::setEngineDefault");
	}
	flag = Engines::getAlgorithmFlags(algorithm);
	if (!(ENGINE_set_default(e, flag)))
	{
		throw EngineException(EngineException::INTERNAL_ERROR, "Engines::setEngineDefault");
	}
}
Exemple #16
0
/* Sets engine as default for all SSL operations
 */
CURLcode Curl_ossl_set_engine_default(struct SessionHandle *data)
{
#ifdef HAVE_OPENSSL_ENGINE_H
  if (data->state.engine) {
    if (ENGINE_set_default(data->state.engine, ENGINE_METHOD_ALL) > 0) {
      infof(data,"set default crypto engine %s\n", data->state.engine);
    }
    else {
      failf(data, "set default crypto engine %s failed", data->state.engine);
      return CURLE_SSL_ENGINE_SETFAILED;
    }
  }
#else
  (void) data;
#endif
  return CURLE_OK;
}
Exemple #17
0
int
_openssl_env_init(openssl_env *env, char *engine, int server) {
  /*
   * Create an OpenSSL environment (method and context).
   * If ``server'' is 1, the environment is that of a SSL
   * server.
   */
  const long options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION;
  env->meth = SSLv23_method();
  env->ctx = SSL_CTX_new(env->meth);
  SSL_CTX_set_options(env->ctx, options);
  if (_options.sslciphers) {
    SSL_CTX_set_cipher_list(env->ctx, _options.sslciphers);
  }
#ifdef HAVE_OPENSSL_ENGINE
  if (engine) {
 retry:
    if ((env->engine = ENGINE_by_id(engine)) == NULL) {
      fprintf(stderr,"invalid engine \"%s\"\n", engine);
      ENGINE_free(env->engine);
      engine = "openssl";
      goto retry;
    }
    if (!ENGINE_set_default(env->engine, ENGINE_METHOD_ALL)) {
      fprintf(stderr,"can't use that engine\n");
      ENGINE_free(env->engine);
      engine = "openssl";
      goto retry;
    }
  }
#endif

#ifdef HAVE_OPENSSL_ENGINE
  SSL_CTX_set_app_data(env->ctx, env);
#endif

  if (server) {
    SSL_CTX_set_options(env->ctx, SSL_OP_SINGLE_DH_USE);
    SSL_CTX_set_session_cache_mode(env->ctx, SSL_SESS_CACHE_OFF);
    SSL_CTX_set_quiet_shutdown(env->ctx, 1);
  }
  return 1;
}
Exemple #18
0
static int rand_openssl_init_rdrand(void)
{
	ENGINE *e;

#if 0
	OPENSSL_cpuid_setup();
#endif
	ENGINE_load_rdrand();

	e = ENGINE_by_id("rdrand");
	if (!e)
		return 1;

	if (ENGINE_init(e) == 0)
		return 1;

	if (ENGINE_set_default(e, ENGINE_METHOD_RAND) == 0)
		return 1;

	return 0;
}
Exemple #19
0
/* Attempt to hook up the hardware random number
 * generator, if it's available. */
static void load_hardware_engine () {
  if (rand_loaded)
    return;

  OPENSSL_cpuid_setup ();
  ENGINE_load_rdrand ();

  reng = ENGINE_by_id ("rdrand");
  ERR_get_error ();

  if (!reng)
    return;

  int rc = ENGINE_set_default (reng, ENGINE_METHOD_RAND);
  ERR_get_error ();

  if (!rc) {
    unload_hardware_engine ();
  }

  rand_loaded = 1;
}
Exemple #20
0
int TS_CONF_set_default_engine(const char *name)
{
    ENGINE *e = NULL;
    int ret = 0;

    if (strcmp(name, "builtin") == 0)
        return 1;

    if ((e = ENGINE_by_id(name)) == NULL)
        goto err;
    if (strcmp(name, "chil") == 0)
        ENGINE_ctrl(e, ENGINE_CTRL_CHIL_SET_FORKCHECK, 1, 0, 0);
    if (!ENGINE_set_default(e, ENGINE_METHOD_ALL))
        goto err;
    ret = 1;

 err:
    if (!ret) {
        TSerr(TS_F_TS_CONF_SET_DEFAULT_ENGINE, TS_R_COULD_NOT_SET_ENGINE);
        ERR_add_error_data(2, "engine:", name);
    }
    ENGINE_free(e);
    return ret;
}
Exemple #21
0
isc_result_t
dst__openssl_init(const char *engine) {
	isc_result_t result;
#ifdef USE_ENGINE
	ENGINE *re;
#else

	UNUSED(engine);
#endif

#ifdef  DNS_CRYPTO_LEAKS
	CRYPTO_malloc_debug_init();
	CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
#endif
	CRYPTO_set_mem_functions(mem_alloc, mem_realloc, mem_free);
	nlocks = CRYPTO_num_locks();
	locks = mem_alloc(sizeof(isc_mutex_t) * nlocks);
	if (locks == NULL)
		return (ISC_R_NOMEMORY);
	result = isc_mutexblock_init(locks, nlocks);
	if (result != ISC_R_SUCCESS)
		goto cleanup_mutexalloc;
	CRYPTO_set_locking_callback(lock_callback);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
	CRYPTO_set_id_callback(id_callback);
#endif

	ERR_load_crypto_strings();

	rm = mem_alloc(sizeof(RAND_METHOD));
	if (rm == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup_mutexinit;
	}
	rm->seed = NULL;
	rm->bytes = entropy_get;
	rm->cleanup = NULL;
	rm->add = entropy_add;
	rm->pseudorand = entropy_getpseudo;
	rm->status = entropy_status;

#ifdef USE_ENGINE
	OPENSSL_config(NULL);

	if (engine != NULL && *engine == '\0')
		engine = NULL;

	if (engine != NULL) {
		e = ENGINE_by_id(engine);
		if (e == NULL) {
			result = DST_R_NOENGINE;
			goto cleanup_rm;
		}
		/* This will init the engine. */
		if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
			result = DST_R_NOENGINE;
			goto cleanup_rm;
		}
	}

	re = ENGINE_get_default_RAND();
	if (re == NULL) {
		re = ENGINE_new();
		if (re == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup_rm;
		}
		ENGINE_set_RAND(re, rm);
		ENGINE_set_default_RAND(re);
		ENGINE_free(re);
	} else
		ENGINE_finish(re);
#else
	RAND_set_rand_method(rm);
#endif /* USE_ENGINE */
	return (ISC_R_SUCCESS);

#ifdef USE_ENGINE
 cleanup_rm:
	if (e != NULL)
		ENGINE_free(e);
	e = NULL;
	mem_free(rm);
	rm = NULL;
#endif
 cleanup_mutexinit:
	CRYPTO_set_locking_callback(NULL);
	DESTROYMUTEXBLOCK(locks, nlocks);
 cleanup_mutexalloc:
	mem_free(locks);
	locks = NULL;
	return (result);
}
Exemple #22
0
isc_result_t
dst__openssl_init() {
	isc_result_t result;
#ifdef USE_ENGINE
	/* const char  *name; */
	ENGINE *re;
#endif

#ifdef  DNS_CRYPTO_LEAKS
	CRYPTO_malloc_debug_init();
	CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
#endif
	CRYPTO_set_mem_functions(mem_alloc, mem_realloc, mem_free);
	nlocks = CRYPTO_num_locks();
	locks = mem_alloc(sizeof(isc_mutex_t) * nlocks);
	if (locks == NULL)
		return (ISC_R_NOMEMORY);
	result = isc_mutexblock_init(locks, nlocks);
	if (result != ISC_R_SUCCESS)
		goto cleanup_mutexalloc;
	CRYPTO_set_locking_callback(lock_callback);
	CRYPTO_set_id_callback(id_callback);

	rm = mem_alloc(sizeof(RAND_METHOD));
	if (rm == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup_mutexinit;
	}
	rm->seed = NULL;
	rm->bytes = entropy_get;
	rm->cleanup = NULL;
	rm->add = entropy_add;
	rm->pseudorand = entropy_getpseudo;
	rm->status = entropy_status;
#ifdef USE_ENGINE
	OPENSSL_config(NULL);
#ifdef USE_PKCS11
#ifndef PKCS11_SO_PATH
#define PKCS11_SO_PATH		"/usr/local/lib/engines/engine_pkcs11.so"
#endif
#ifndef PKCS11_MODULE_PATH
#define PKCS11_MODULE_PATH	"/usr/lib/libpkcs11.so"
#endif
	{
		/*
		 * to use this to config the PIN, add in openssl.cnf:
		 *  - at the beginning: "openssl_conf = openssl_def"
		 *  - at any place these sections:
		 * [ openssl_def ]
		 * engines = engine_section
		 * [ engine_section ]
		 * pkcs11 = pkcs11_section
		 * [ pkcs11_section ]
		 * PIN = my___pin
		 */

		const char *pre_cmds[] = {
			"SO_PATH", PKCS11_SO_PATH,
			"LOAD", NULL,
			"MODULE_PATH", PKCS11_MODULE_PATH
		};
		const char *post_cmds[] = {
			/* "PIN", "my___pin" */
		};
		result = dst__openssl_load_engine("pkcs11", "pkcs11",
						  pre_cmds, 0,
						  post_cmds, /*1*/ 0);
		if (result != ISC_R_SUCCESS)
			goto cleanup_rm;
	}
#endif /* USE_PKCS11 */
	if (engine_id != NULL) {
		e = ENGINE_by_id(engine_id);
		if (e == NULL) {
			result = ISC_R_NOTFOUND;
			goto cleanup_rm;
		}
		if (!ENGINE_init(e)) {
			result = ISC_R_FAILURE;
			ENGINE_free(e);
			goto cleanup_rm;
		}
		ENGINE_set_default(e, ENGINE_METHOD_ALL);
		ENGINE_free(e);
	} else {
		ENGINE_register_all_complete();
		for (e = ENGINE_get_first(); e != NULL; e = ENGINE_get_next(e)) {

			/*
			 * Something weird here. If we call ENGINE_finish()
			 * ENGINE_get_default_RAND() will fail.
			 */
			if (ENGINE_init(e)) {
				if (he == NULL)
					he = e;
			}
		}
	}
	re = ENGINE_get_default_RAND();
	if (re == NULL) {
		re = ENGINE_new();
		if (re == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup_rm;
		}
		ENGINE_set_RAND(re, rm);
		ENGINE_set_default_RAND(re);
		ENGINE_free(re);
	} else
		ENGINE_finish(re);

#else
	RAND_set_rand_method(rm);
#endif /* USE_ENGINE */
	return (ISC_R_SUCCESS);

#ifdef USE_ENGINE
 cleanup_rm:
	mem_free(rm);
#endif
 cleanup_mutexinit:
	CRYPTO_set_locking_callback(NULL);
	DESTROYMUTEXBLOCK(locks, nlocks);
 cleanup_mutexalloc:
	mem_free(locks);
	return (result);
}
Exemple #23
0
ENGINE *scep_engine_init(ENGINE *e) {
	

		ENGINE_load_builtin_engines();
		ENGINE_load_dynamic();
		//if its not dynamic, try to load it directly. If OpenSSL has it already we are good to go!
		if(strcmp(g_char, "dynamic") != 0)
		{
			e = ENGINE_by_id(g_char);
			if ((e==NULL) && v_flag){
				printf("%s: Engine %s could not be loaded. Trying to load dynamically...\n", pname, g_char);
			}
		}

		if(e == NULL)
		{
			ERR_clear_error();
			e = scep_engine_load_dynamic(e);
		}

		if(scep_conf->engine->module_path) {
			if(ENGINE_ctrl_cmd_string(e, "MODULE_PATH", scep_conf->engine->module_path, 0) == 0) {
				fprintf(stderr, "%s: Adding MODULE PATH %s was not successful!\n", pname, scep_conf->engine->module_path);
				sscep_engine_report_error();
				exit (SCEP_PKISTATUS_ERROR);
			}
		}

		//define this engine as a default for all our crypto operations. This way OpenSSL automatically chooses the right functions
		if(ENGINE_set_default(e, ENGINE_METHOD_ALL) == 0) {
				fprintf(stderr, "%s: Error loading on setting defaults\n", pname);
				sscep_engine_report_error();
				exit (SCEP_PKISTATUS_ERROR);
		} else if(v_flag)
			printf("%s: Engine %s made default for all operations\n", pname, g_char);

		//we need a functional reference and as such need to initialize
		if(ENGINE_init(e) == 0) {
			fprintf(stderr, "%s: Engine Init did not work\n", pname);
			sscep_engine_report_error();
			exit (SCEP_PKISTATUS_ERROR);
		} else if(v_flag)
			printf("%s: Engine %s initialized\n", pname, g_char);


		//TODO: remove capi specific part!
		if(v_flag && strncmp(scep_conf->engine->engine_id, "capi", 4) == 0) {
			// set debug level
			if(!ENGINE_ctrl(e, (ENGINE_CMD_BASE + 2), 2, NULL, NULL)) {
				fprintf(stderr, "%s: Could not set debug level to %i\n", pname, 2);
				sscep_engine_report_error();
				exit (SCEP_PKISTATUS_ERROR);
			}
			// set debug file (log)
			if(!ENGINE_ctrl(e, (ENGINE_CMD_BASE + 3), 0, "capi.log", NULL)) {
				fprintf(stderr, "%s: Could not set debug file to %s\n", pname, "capi.log");
				sscep_engine_report_error();
				exit (SCEP_PKISTATUS_ERROR);
			}
		}

		//TODO: remove JKSEngine specific part!
		if(strncmp(scep_conf->engine->engine_id, "jksengine", 9) == 0) {
			if(scep_conf->engine->storepass) {
				if(!ENGINE_ctrl(e, 2, 0, scep_conf->engine->storepass, NULL)) {
					fprintf(stderr, "%s: Could not set %s\n", pname, SCEP_CONFIGURATION_ENGINE_JKSENGINE_KEYSTOREPASS);
					sscep_engine_report_error();
					exit (SCEP_PKISTATUS_ERROR);
				}
			}

			if(scep_conf->engine->jconnpath) {
				if(!ENGINE_ctrl(e, 3, 0, scep_conf->engine->jconnpath, 0)) {
					fprintf(stderr, "%s: Could not set %s\n", pname, SCEP_CONFIGURATION_ENGINE_JKSENGINE_JCONNPATH);
					sscep_engine_report_error();
					exit (SCEP_PKISTATUS_ERROR);
				}
			}

			if(scep_conf->engine->provider) {
				if(!ENGINE_ctrl(e, 4, 0, scep_conf->engine->provider, 0)) {
					fprintf(stderr, "%s: Could not set %s\n", pname, SCEP_CONFIGURATION_ENGINE_JKSENGINE_PROVIDER);
					sscep_engine_report_error();
					exit (SCEP_PKISTATUS_ERROR);
				}
			}

			if(scep_conf->engine->javapath) {
				if(!ENGINE_ctrl(e, 5, 0, scep_conf->engine->javapath, 0)) {
					fprintf(stderr, "%s: Could not set %s\n", pname, SCEP_CONFIGURATION_ENGINE_JKSENGINE_JAVAPATH);
					sscep_engine_report_error();
					exit (SCEP_PKISTATUS_ERROR);
				}
			}
		}

		//TODO: remove pkcs11 specific part!
		if(strncmp(scep_conf->engine->engine_id, "pkcs11", 6) == 0) {
			if(scep_conf->engine->pin) {
				if(!ENGINE_ctrl(e, (ENGINE_CMD_BASE + 2), 0, scep_conf->engine->pin, NULL)) {
					fprintf(stderr, "%s: Could not define PIN\n", pname);
					sscep_engine_report_error();
					exit (SCEP_PKISTATUS_ERROR);
				}
			}
		}


		return e;
}
Exemple #24
0
static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id,
                                   const char *CAfile, const char *cert,
                                   const char *key, const char *dcert,
                                   const char *dkey, const char *cipher_list,
                                   const char *dh_file,
                                   const char *dh_special, int tmp_rsa,
                                   int ctx_options, int out_state,
                                   int out_verify, int verify_mode,
                                   unsigned int verify_depth)
{
    SSL_CTX *ctx = NULL, *ret = NULL;
    const SSL_METHOD *meth;
    ENGINE *e = NULL;

    OpenSSL_add_ssl_algorithms();
    SSL_load_error_strings();

    meth = (server_mode ? SSLv23_server_method() : SSLv23_client_method());
    if (meth == NULL)
        goto err;
    if (engine_id) {
        ENGINE_load_builtin_engines();
        if ((e = ENGINE_by_id(engine_id)) == NULL) {
            fprintf(stderr, "Error obtaining '%s' engine, openssl "
                    "errors follow\n", engine_id);
            goto err;
        }
        if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
            fprintf(stderr, "Error assigning '%s' engine, openssl "
                    "errors follow\n", engine_id);
            goto err;
        }
        ENGINE_free(e);
    }
    if ((ctx = SSL_CTX_new(meth)) == NULL)
        goto err;
    /* cacert */
    if (CAfile) {
        if (!X509_STORE_load_locations(SSL_CTX_get_cert_store(ctx),
                                       CAfile, NULL)) {
            fprintf(stderr, "Error loading CA cert(s) in '%s'\n", CAfile);
            goto err;
        }
        fprintf(stderr, "Info, operating with CA cert(s) in '%s'\n", CAfile);
    } else
        fprintf(stderr, "Info, operating without a CA cert(-list)\n");
    if (!SSL_CTX_set_default_verify_paths(ctx)) {
        fprintf(stderr, "Error setting default verify paths\n");
        goto err;
    }

    /* cert and key */
    if ((cert || key) && !ctx_set_cert(ctx, cert, key))
        goto err;
    /* dcert and dkey */
    if ((dcert || dkey) && !ctx_set_cert(ctx, dcert, dkey))
        goto err;
    /* temporary RSA key generation */
    if (tmp_rsa)
        SSL_CTX_set_tmp_rsa_callback(ctx, cb_generate_tmp_rsa);

    /* cipher_list */
    if (cipher_list) {
        if (!SSL_CTX_set_cipher_list(ctx, cipher_list)) {
            fprintf(stderr, "Error setting cipher list '%s'\n", cipher_list);
            goto err;
        }
        fprintf(stderr, "Info, set cipher list '%s'\n", cipher_list);
    } else
        fprintf(stderr, "Info, operating with default cipher list\n");

    /* dh_file & dh_special */
    if ((dh_file || dh_special) && !ctx_set_dh(ctx, dh_file, dh_special))
        goto err;

    /* ctx_options */
    SSL_CTX_set_options(ctx, ctx_options);

    /* out_state (output of SSL handshake states to screen). */
    if (out_state)
        cb_ssl_info_set_output(stderr);

    /* out_verify */
    if (out_verify > 0) {
        cb_ssl_verify_set_output(stderr);
        cb_ssl_verify_set_level(out_verify);
    }

    /* verify_depth */
    cb_ssl_verify_set_depth(verify_depth);

    /* Success! (includes setting verify_mode) */
    SSL_CTX_set_info_callback(ctx, cb_ssl_info);
    SSL_CTX_set_verify(ctx, verify_mode, cb_ssl_verify);
    ret = ctx;
 err:
    if (!ret) {
        ERR_print_errors_fp(stderr);
        if (ctx)
            SSL_CTX_free(ctx);
    }
    return ret;
}
Exemple #25
0
ret_t
http2d_init (void)
{
	if (_initialized)
		return ret_ok;

        /* Init OpenSSL
         */
        OPENSSL_config (NULL);
        SSL_library_init();
        SSL_load_error_strings();
        OpenSSL_add_all_algorithms();

        /* Ensure PRNG has been seeded with enough data
         */
        if (RAND_status() == 0) {
                LOG_WARNING_S (HTTP2D_ERROR_SSL_NO_ENTROPY);
        }

        /* Init concurrency related stuff
         */
        if ((CRYPTO_get_id_callback()      == NULL) &&
            (CRYPTO_get_locking_callback() == NULL))
        {
                cuint_t n;

                CRYPTO_set_id_callback (__get_thread_id);
                CRYPTO_set_locking_callback (__lock_thread);

                locks_num = CRYPTO_num_locks();
                locks     = malloc (locks_num * sizeof(*locks));

                for (n = 0; n < locks_num; n++) {
                        HTTP2D_MUTEX_INIT (&locks[n], NULL);
                }
        }

	/* Engines
	 */
        ENGINE_load_builtin_engines();
        OpenSSL_add_all_algorithms();

        ENGINE *e = ENGINE_by_id("pkcs11");
        while (e != NULL) {
                if(! ENGINE_init(e)) {
                        ENGINE_free (e);
                        LOG_CRITICAL_S (HTTP2D_ERROR_SSL_PKCS11);
                        break;
                }

                if(! ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
                        ENGINE_free (e);
                        LOG_CRITICAL_S (HTTP2D_ERROR_SSL_DEFAULTS);
                        break;
                }

                ENGINE_finish(e);
                ENGINE_free(e);
                break;
        }

	return ret_ok;
}
Exemple #26
0
int64_t s2n_public_random(int64_t max)
{
    uint64_t r;

    gt_check(max, 0);

    while(1) {
        struct s2n_blob blob = { .data = (void *) &r, sizeof(r) };
        GUARD(s2n_get_public_random_data(&blob));

        /* Imagine an int was one byte and UINT_MAX was 256. If the
         * caller asked for s2n_random(129, ...) we'd end up in
         * trouble. Each number in the range 0...127 would be twice
         * as likely as 128. That's because r == 0 % 129 -> 0, and
         * r == 129 % 129 -> 0, but only r == 128 returns 128,
         * r == 257 is out of range.
         *
         * To de-bias the dice, we discard values of r that are higher
         * that the highest multiple of 'max' an int can support. If
         * max is a uint, then in the worst case we discard 50% - 1 r's.
         * But since 'max' is an int and INT_MAX is <= UINT_MAX / 2,
         * in the worst case we discard 25% - 1 r's.
         */
        if (r < (UINT64_MAX - (UINT64_MAX % max))) {
            return r % max;
        }
    }

    return -1;
}

#ifndef OPENSSL_IS_BORINGSSL

int s2n_openssl_compat_rand(unsigned char *buf, int num)
{
    struct s2n_blob out = {.data = buf, .size = num};

    if(s2n_get_private_random_data(&out) < 0) {
        return 0;
    }
    return 1;
}

int s2n_openssl_compat_status(void)
{
    return 1;
}

int s2n_openssl_compat_init(ENGINE *unused)
{
    return 1;
}

RAND_METHOD s2n_openssl_rand_method = {
    .seed = NULL,
    .bytes = s2n_openssl_compat_rand,
    .cleanup = NULL,
    .add = NULL,
    .pseudorand = s2n_openssl_compat_rand,
    .status = s2n_openssl_compat_status
};
#endif

int s2n_init(void)
{
    GUARD(s2n_mem_init());

    OPEN:
    entropy_fd = open(ENTROPY_SOURCE, O_RDONLY);
    if (entropy_fd == -1) {
        if (errno == EINTR) {
            goto OPEN;
        }
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }

#if defined(MAP_INHERIT_ZERO)
    if ((zero_if_forked_ptr = mmap(NULL, sizeof(int), PROT_READ|PROT_WRITE,
                                   MAP_ANON|MAP_PRIVATE, -1, 0)) == MAP_FAILED) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }

    if (minherit(zero_if_forked_ptr, sizeof(int), MAP_INHERIT_ZERO) == -1) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }
#else

    if (pthread_atfork(NULL, NULL, s2n_on_fork) != 0) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }
#endif

    GUARD(s2n_check_fork());

#ifndef OPENSSL_IS_BORINGSSL
    /* Create an engine */
    ENGINE *e = ENGINE_new();
    if (e == NULL ||
        ENGINE_set_id(e, "s2n") != 1 ||
        ENGINE_set_name(e, "s2n entropy generator") != 1 ||
        ENGINE_set_flags(e, ENGINE_FLAGS_NO_REGISTER_ALL) != 1 ||
        ENGINE_set_init_function(e, s2n_openssl_compat_init) != 1 ||
        ENGINE_set_RAND(e, &s2n_openssl_rand_method) != 1 ||
        ENGINE_add(e) != 1 ||
        ENGINE_free(e) != 1) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }

    /* Use that engine for rand() */
    e = ENGINE_by_id("s2n");
    if (e == NULL ||
        ENGINE_init(e) != 1 ||
        ENGINE_set_default(e, ENGINE_METHOD_RAND) != 1) {
        S2N_ERROR(S2N_ERR_OPEN_RANDOM);
    }

#endif

    return 0;
}