Example #1
0
File: tor.c Project: postfix/libtor
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);
	}
}
Example #2
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
}
Example #3
0
ENGINE*
dnssec_loadengine(const char* engine_name_const)
{
    ENGINE* engine;
    char* token_pointer = NULL;

    char* engine_name = strdup(engine_name_const);

    char* token = strtok_r(engine_name, ENGINE_COMMAND_DELIMITER, &token_pointer);

    if(token == NULL)
    {
        engine = ENGINE_by_id(engine_name);
    }
    else
    {
        engine = ENGINE_by_id(token);
        token = strtok_r(NULL, ENGINE_COMMAND_DELIMITER, &token_pointer);
    }

    if(engine == NULL)
    {
        log_err("ENGINE %s not available", engine_name);
        DIE(DNSSEC_ERROR_NOENGINE);
    }

    while(token != NULL)
    {
        char* command_pointer;
        char* command = strtok_r(token, "=", &command_pointer);

        if(command == NULL)
        {
            log_err("bad command %s", command);
            DIE(DNSSEC_ERROR_INVALIDENGINE);
        }
        char* command_value = strtok_r(NULL, "=", &command_pointer);
        if(command_value == NULL)
        {
            log_err("bad command value %s", command_value);
            DIE(DNSSEC_ERROR_INVALIDENGINE);
        }
        ENGINE_ctrl_cmd((ENGINE*)engine, command, atoi(command_value), NULL, NULL, 0);

        token = strtok_r(NULL, ENGINE_COMMAND_DELIMITER, &token_pointer);
    }

    if(ENGINE_init((ENGINE*)engine) == 0)
    {
        log_err("ENGINE_init failed");
        ENGINE_free((ENGINE*)engine); /* cfr: http://www.openssl.org/docs/crypto/engine.html */
        DIE(DNSSEC_ERROR_INVALIDENGINE);
    }

    free(engine_name);

    return engine;
}
Example #4
0
int
main(int argc, char **argv)
{
    ENGINE *engine = NULL;
    int idx = 0;

    setprogname(argv[0]);

    if(getarg(args, sizeof(args) / sizeof(args[0]), argc, argv, &idx))
	usage(1);

    if (help_flag)
	usage(0);

    if(version_flag){
	print_version(NULL);
	exit(0);
    }

    argc -= idx;
    argv += idx;

    OpenSSL_add_all_algorithms();
#ifdef OPENSSL
    ENGINE_load_openssl();
#endif
    ENGINE_load_builtin_engines();

    if (id_string) {
	engine = ENGINE_by_id(id_string);
	if (engine == NULL)
	    engine = ENGINE_by_dso(id_string, id_string);
    } else {
	engine = ENGINE_by_id("builtin");
    }
    if (engine == NULL)
	errx(1, "ENGINE_by_dso failed");

    printf("dh %s\n", ENGINE_get_DH(engine)->name);

    {
	struct prime *p = primes;

	for (; p->name; ++p)
	    if (check_prime(engine, p))
		printf("%s: shared secret OK\n", p->name);
	    else
		printf("%s: shared secret FAILURE\n", p->name);

	return 0;
    }

    return 0;
}
Example #5
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;
} 
CryptoDevEngine::CryptoDevEngine( int /* dummy */ )
{
    DEBUG( "cryptodev: ctor: loading and configuring" );
    ENGINE_load_cryptodev();

    ENGINE * cde = ENGINE_by_id( "cryptodev" );
    if ( ! cde )
        throw Exception( "cryptodev: load failed" );

    m_pEngine = cde;

    DEBUG( "cryptodev: ctor: initializing " << m_pEngine );
    if ( 1 != ENGINE_init( cde ) )
        throw Exception( "cryptodev: init failed" );

#if USE_CRYPTODEV_RSA
    DEBUG( "cryptodev: ctor: setting as rsa default" );
    if ( 1 != ENGINE_set_default_RSA( cde ) )
        throw Exception( "cryptodev: could not use for RSA" );
#endif // USE_CRYPTODEV_RSA

#if USE_CRYPTODEV_CIPHERS
    DEBUG( "cryptodev: ctor: setting as cipher default" );
    if ( 1 != ENGINE_set_default_ciphers( cde ) )
        throw Exception( "cryptodev: could not use for ciphers" );
#endif // USE_CRYPTODEV_CIPHERS
        
#if USE_CRYPTODEV_DIGESTS
    DEBUG( "cryptodev: ctor: setting as digest default" );
    if ( 1 != ENGINE_set_default_digests( cde ) )
        throw Exception( "cryptodev: could not use for digests" );
#endif // USE_CRYPTODEV_DIGESTS

    DEBUG( "cryptodev: ctor: done" );
}
Example #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;
}
DynamicEngine::DynamicEngine( const string & id,
                              const StringList & engineLibPaths )
{
    DEBUG( "dynamic: ctor: loading and configuring dynamic engine" );
    ENGINE_load_dynamic();

    ENGINE * dyn = ENGINE_by_id( "dynamic" );
    if ( ! dyn )
        throw Exception( "dynamic: load failed" );

    m_pEngine = dyn;

    const string engineLibPath( findFirstExisting( engineLibPaths ) );
    if ( engineLibPath.empty() )
        throw Exception( "dynamic: unable to find engine lib path" );

    DEBUG( "dynamic: ctor: so_path=" << QS( engineLibPath ) );
    if ( 1 != ENGINE_ctrl_cmd_string( dyn, "SO_PATH", engineLibPath.c_str(), CMD_MANDATORY ) )
        throw Exception( "dynamic: setting so_path <= " + QS( engineLibPath ) );

    DEBUG( "dynamic: ctor: id=" << QS( id ) );
    if ( 1 != ENGINE_ctrl_cmd_string( dyn, "ID", id.c_str(), CMD_MANDATORY ) )
        throw Exception( "dynamic: setting id <= " + QS( id ) );

    DEBUG( "dynamic: ctor: list_add=1" );
    if ( 1 != ENGINE_ctrl_cmd( dyn, "LIST_ADD", 1, NULL, NULL, CMD_MANDATORY ) )
        throw Exception( "dynamic: setting list_add <= 1" );

    DEBUG( "dynamic: ctor: load=1" );
    if ( 1 != ENGINE_ctrl_cmd( dyn, "LOAD", 1, NULL, NULL, CMD_MANDATORY ) )
        throw Exception( "dynamic: setting load <= 1" );

    DEBUG( "dynamic: ctor: done" );
}
Example #9
0
ENGINE *ENGINE_CTGOST_get_ptr(){
	LOGGER_FN();
	ENGINE *e = ENGINE_by_id("ctgostcp");
	if (!e)
		THROW_OPENSSL_EXCEPTION(0, Common, NULL, "ENGINE 'ctgostcp' is not loaded");
	return e;
}
Example #10
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;
	}
Example #11
0
/* Selects an OpenSSL crypto engine
 */
CURLcode Curl_ossl_set_engine(struct SessionHandle *data, const char *engine)
{
#if defined(USE_SSLEAY) && defined(HAVE_OPENSSL_ENGINE_H)
  ENGINE *e = ENGINE_by_id(engine);

  if (!e) {
    failf(data, "SSL Engine '%s' not found", engine);
    return (CURLE_SSL_ENGINE_NOTFOUND);
  }

  if (data->state.engine) {
    ENGINE_finish(data->state.engine);
    ENGINE_free(data->state.engine);
  }
  data->state.engine = NULL;
  if (!ENGINE_init(e)) {
    char buf[256];

    ENGINE_free(e);
    failf(data, "Failed to initialise SSL Engine '%s':\n%s",
          engine, SSL_strerror(ERR_get_error(), buf, sizeof(buf)));
    return (CURLE_SSL_ENGINE_INITFAILED);
  }
  data->state.engine = e;
  return (CURLE_OK);
#else
  (void)engine;
  failf(data, "SSL Engine not supported");
  return (CURLE_SSL_ENGINE_NOTFOUND);
#endif
}
Example #12
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);
    }
}
//ignore
unsigned char *HMACRSA(const EVP_MD *evp_md, const void *key, int key_len,const unsigned char *d, size_t n, unsigned char *md,unsigned int *md_len)
{
    HMAC_CTX c;
    static unsigned char m[EVP_MAX_MD_SIZE];
    //TODO: get/set rsa engine struct
    const char *engine_id = "rsa";
    ENGINE_load_builtin_engines();
    ENGINE *e = ENGINE_by_id(engine_id);//ENGINE_;
    if(!e)
      fprintf(stderr,"Engine not available\n");

    ENGINE_init(e);
    if (md == NULL)
        md = m;
    HMAC_CTX_init(&c);

    if (!HMAC_Init_ex(&c, key, key_len, evp_md, NULL))
        goto err;
    if (!HMAC_Update(&c, d, n))
        goto err;
    if (!HMAC_Final(&c, md, md_len))
        goto err;
    HMAC_CTX_cleanup(&c);
    ENGINE_free(e);
    return md;
 err:
    HMAC_CTX_cleanup(&c);
    ENGINE_free(e);
    return NULL;
}
Example #14
0
static ENGINE *
InitEnginePKCS11( const char *pkcs11, const char *pin)
{
	ENGINE *e;
	ENGINE_load_dynamic();
	e = ENGINE_by_id("dynamic");
	if (!e){
		SSL_Error(_d("Engine_by_id:\n %s"), GetSSLErrorString());
		return NULL;
	}

	if(!ENGINE_ctrl_cmd_string(e, "SO_PATH", ENGINE_PKCS11_PATH, 0)||
	   !ENGINE_ctrl_cmd_string(e, "ID", "pkcs11", 0) ||
	   !ENGINE_ctrl_cmd_string(e, "LIST_ADD", "1", 0) ||
	   !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0) ||
	   !ENGINE_ctrl_cmd_string(e, "MODULE_PATH", pkcs11, 0) ||
	   !ENGINE_ctrl_cmd_string(e, "PIN", pin, 0) ){
		SSL_Error(_d("Engine_ctrl_cmd_string failure:\n %s"), GetSSLErrorString());
		ENGINE_free(e);
		return NULL;
	}

	if(!ENGINE_init(e)){
		SSL_Error(_d("Engine_init failure:\n %s"), GetSSLErrorString());
		ENGINE_free(e);
		return NULL;
	}

	return e; 
}
Example #15
0
isc_result_t
dst__opensslgost_init(dst_func_t **funcp) {
	REQUIRE(funcp != NULL);

	/* check if the gost engine works properly */
	e = ENGINE_by_id("gost");
	if (e == NULL)
		return (DST_R_OPENSSLFAILURE);
	if (ENGINE_init(e) <= 0) {
		ENGINE_free(e);
		e = NULL;
		return (DST_R_OPENSSLFAILURE);
	}
	/* better than to rely on digest_gost symbol */
	opensslgost_digest = ENGINE_get_digest(e, NID_id_GostR3411_94);
	/* from openssl.cnf */
	if ((opensslgost_digest == NULL) ||
	    (ENGINE_register_pkey_asn1_meths(e) <= 0) ||
	    (ENGINE_ctrl_cmd_string(e,
				    "CRYPT_PARAMS",
				    "id-Gost28147-89-CryptoPro-A-ParamSet",
				    0) <= 0)) {
		ENGINE_finish(e);
		ENGINE_free(e);
		e = NULL;
		return (DST_R_OPENSSLFAILURE);
	}

	if (*funcp == NULL)
		*funcp = &opensslgost_functions;
	return (ISC_R_SUCCESS);
}
Example #16
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;
}
Example #17
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;
}
Example #18
0
int openssl_engine(lua_State *L)
{
  const ENGINE* eng = NULL;
  if (lua_isstring(L, 1))
  {
    const char* id = luaL_checkstring(L, 1);
    eng = ENGINE_by_id(id);
  }
  else if (lua_isboolean(L, 1))
  {
    int first = lua_toboolean(L, 1);
    if (first)
      eng = ENGINE_get_first();
    else
      eng = ENGINE_get_last();
  }
  else
    luaL_error(L,
               "#1 may be string or boolean\n"
               "\tstring for an engine id to load\n"
               "\ttrue for first engine, false or last engine\n"
               "\tbut we get %s:%s", lua_typename(L, lua_type(L,  1)), lua_tostring(L, 1));
  if (eng)
  {
    PUSH_OBJECT((void*)eng, "openssl.engine");
  }
  else
    lua_pushnil(L);
  return 1;
}
Example #19
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);
}
Example #20
0
ENGINE *load_engine(const char *so_path, const char *id) {
    ENGINE_load_dynamic();
    ENGINE *de = ENGINE_by_id("dynamic");
    if(de == 0) {
        printf("Unable to load dynamic engine\n");
        return 0;
    }

    if(!ENGINE_ctrl_cmd_string(de, "SO_PATH", so_path, 0)) {
        printf("Unable to load desired engine\n");
        return 0;
    }
    ENGINE_ctrl_cmd_string(de, "LIST_ADD", "2", 0);
    ENGINE_ctrl_cmd_string(de, "LOAD", NULL, 0);
    ENGINE_free(de);
    return ENGINE_by_id(id);
}
Example #21
0
int main(int argc, char **argv)
{
#ifdef ANDROID_CHANGES
    int control = android_get_control_and_arguments(&argc, &argv);
    ENGINE *e;
    if (control != -1) {
        pname = "%p";
        monitor_fd(control, NULL);

        ENGINE_load_dynamic();
        e = ENGINE_by_id("keystore");
        if (!e || !ENGINE_init(e)) {
            do_plog(LLV_ERROR, "ipsec-tools: cannot load keystore engine");
            exit(1);
        }
    }
#endif

    do_plog(LLV_INFO, "ipsec-tools 0.7.3 (http://ipsec-tools.sf.net)\n");

    signal(SIGHUP, terminate);
    signal(SIGINT, terminate);
    signal(SIGTERM, terminate);
    signal(SIGPIPE, SIG_IGN);
    atexit(terminated);

    setup(argc, argv);

#ifdef ANDROID_CHANGES
    shutdown(control, SHUT_WR);
    setuid(AID_VPN);
#endif

    while (1) {
        struct timeval *tv = schedular();
        int timeout = tv->tv_sec * 1000 + tv->tv_usec / 1000 + 1;

        if (poll(pollfds, monitors, timeout) > 0) {
            int i;
            for (i = 0; i < monitors; ++i) {
                if (pollfds[i].revents & POLLHUP) {
                    do_plog(LLV_ERROR, "Connection is closed\n", pollfds[i].fd);
                    exit(1);
                }
                if (pollfds[i].revents & POLLIN) {
                    callbacks[i](pollfds[i].fd);
                }
            }
        }
    }
#ifdef ANDROID_CHANGES
    if (e) {
        ENGINE_finish(e);
        ENGINE_free(e);
    }
#endif
    return 0;
}
Example #22
0
static SSL_CTX * ssl_server_init(const char *keypath, const char *certpath)
{
    SSL_CTX *ctx;
    ENGINE *e;

    ENGINE_load_builtin_engines();
    ENGINE_register_all_complete();

    e = ENGINE_by_id("padlock");
    if (e) {
        fprintf(stderr, "[*] Using padlock engine for default ciphers\n");
        ENGINE_set_default_ciphers(ENGINE_by_id("padlock"));
        use_padlock_engine = 1;
    } else {
        fprintf(stderr, "[*] Padlock engine not available\n");
        use_padlock_engine = 0;
    }

    SSL_load_error_strings();
    SSL_library_init();

    if (!RAND_poll())
	return NULL;

    ctx = SSL_CTX_new(SSLv23_server_method());

    if (!SSL_CTX_use_certificate_chain_file(ctx, certpath) ||
	    !SSL_CTX_use_PrivateKey_file(ctx, keypath, SSL_FILETYPE_PEM)) {
	fprintf(stderr, "Could not read %s or %s file\n", keypath, certpath);
	fprintf(stderr, "To generate a key and self-signed certificate, run:\n");
	fprintf(stderr, "\topenssl genrsa -out key.pem 2048\n");
	fprintf(stderr, "\topenssl req -new -key key.pem -out cert.req\n");
	fprintf(stderr, "\topenssl x509 -req -days 365 -in cert.req -signkey key.pem -out cert.pem\n");
	return NULL;
    }

    SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
    if (use_padlock_engine == 1) {
	if (SSL_CTX_set_cipher_list(ctx, "AES+SHA") != 1) {
	    fprintf(stderr, "Error setting client cipher list\n");
	    return NULL;
	}
    }
    return ctx;
}
Example #23
0
static int load_tpm_certificate(struct openconnect_info *vpninfo)
{
	ENGINE *e;
	EVP_PKEY *key;
	UI_METHOD *meth = NULL;
	int ret = 0;

	ENGINE_load_builtin_engines();

	e = ENGINE_by_id("tpm");
	if (!e) {
		vpn_progress(vpninfo, PRG_ERR, _("Can't load TPM engine.\n"));
		openconnect_report_ssl_errors(vpninfo);
		return -EINVAL;
	}
	if (!ENGINE_init(e) || !ENGINE_set_default_RSA(e) ||
	    !ENGINE_set_default_RAND(e)) {
		vpn_progress(vpninfo, PRG_ERR, _("Failed to init TPM engine\n"));
		openconnect_report_ssl_errors(vpninfo);
		ENGINE_free(e);
		return -EINVAL;
	}

	if (vpninfo->cert_password) {
		if (!ENGINE_ctrl_cmd(e, "PIN", strlen(vpninfo->cert_password),
				     vpninfo->cert_password, NULL, 0)) {
			vpn_progress(vpninfo, PRG_ERR,
				     _("Failed to set TPM SRK password\n"));
			openconnect_report_ssl_errors(vpninfo);
		}
		vpninfo->cert_password = NULL;
		free(vpninfo->cert_password);
	} else {
		/* Provide our own UI method to handle the PIN callback. */
		meth = create_openssl_ui(vpninfo);
	}
	key = ENGINE_load_private_key(e, vpninfo->sslkey, meth, NULL);
	if (meth)
		UI_destroy_method(meth);
	if (!key) {
		vpn_progress(vpninfo, PRG_ERR,
			     _("Failed to load TPM private key\n"));
		openconnect_report_ssl_errors(vpninfo);
		ret = -EINVAL;
		goto out;
	}
	if (!SSL_CTX_use_PrivateKey(vpninfo->https_ctx, key)) {
		vpn_progress(vpninfo, PRG_ERR, _("Add key from TPM failed\n"));
		openconnect_report_ssl_errors(vpninfo);
		ret = -EINVAL;
	}
	EVP_PKEY_free(key);
 out:
	ENGINE_finish(e);
	ENGINE_free(e);
	return ret;
}
Example #24
0
    static ENGINE* LoadEngine()
    {
      // This function creates an engine for PKCS#11 and inspired by
      // the "ENGINE_load_dynamic" function from OpenSSL, in file
      // "crypto/engine/eng_dyn.c"

      ENGINE* engine = ENGINE_new();
      if (!engine)
      {
        LOG(ERROR) << "Cannot create an OpenSSL engine for PKCS#11";
        throw OrthancException(ErrorCode_InternalError);
      }

      // Create a PKCS#11 context using libp11
      context_ = pkcs11_new();
      if (!context_)
      {
        LOG(ERROR) << "Cannot create a libp11 context for PKCS#11";
        ENGINE_free(engine);
        throw OrthancException(ErrorCode_InternalError);
      }

      if (!ENGINE_set_id(engine, PKCS11_ENGINE_ID) ||
          !ENGINE_set_name(engine, PKCS11_ENGINE_NAME) ||
          !ENGINE_set_cmd_defns(engine, PKCS11_ENGINE_COMMANDS) ||

          // Register the callback functions
          !ENGINE_set_init_function(engine, EngineInitialize) ||
          !ENGINE_set_finish_function(engine, EngineFinalize) ||
          !ENGINE_set_destroy_function(engine, EngineDestroy) ||
          !ENGINE_set_ctrl_function(engine, EngineControl) ||
          !ENGINE_set_load_pubkey_function(engine, EngineLoadPublicKey) ||
          !ENGINE_set_load_privkey_function(engine, EngineLoadPrivateKey) ||

          !ENGINE_set_RSA(engine, PKCS11_get_rsa_method()) ||
          !ENGINE_set_ECDSA(engine, PKCS11_get_ecdsa_method()) ||
          !ENGINE_set_ECDH(engine, PKCS11_get_ecdh_method()) ||

#if OPENSSL_VERSION_NUMBER  >= 0x10100002L
          !ENGINE_set_EC(engine, PKCS11_get_ec_key_method()) ||
#endif

          // Make OpenSSL know about our PKCS#11 engine
          !ENGINE_add(engine))
      {
        LOG(ERROR) << "Cannot initialize the OpenSSL engine for PKCS#11";
        pkcs11_finish(context_);
        ENGINE_free(engine);
        throw OrthancException(ErrorCode_InternalError);
      }

      // If the "ENGINE_add" worked, it gets a structural
      // reference. We release our just-created reference.
      ENGINE_free(engine);

      return ENGINE_by_id(PKCS11_ENGINE_ID);
    }
Example #25
0
Engine* Engines::getEngineById(std::string id) throw (EngineException)
{
	ENGINE *eng;
	eng = ENGINE_by_id(id.c_str());
	if (!eng)
	{
		throw EngineException(EngineException::ENGINE_NOT_FOUND, "Engines::getEngineById", true);
	}
	return new Engine(eng);
}
Example #26
0
static void engine_fork_handler(void)
{
    /*Reset engine*/
    ENGINE* e = ENGINE_by_id(engine_qat_id);
    if(e == NULL) {
        return;
    }
    qat_engine_finish(e);

    keep_polling = 1;
}
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());
	}

}
Example #28
0
File: engine.c Project: bjorng/otp
ERL_NIF_TERM engine_by_id_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{/* (EngineId) */
#ifdef HAS_ENGINE_SUPPORT
    ERL_NIF_TERM ret, result;
    ErlNifBinary engine_id_bin;
    char *engine_id = NULL;
    ENGINE *engine;
    struct engine_ctx *ctx = NULL;

    // Get Engine Id
    ASSERT(argc == 1);

    if (!enif_inspect_binary(env, argv[0], &engine_id_bin))
        goto bad_arg;

    if ((engine_id = enif_alloc(engine_id_bin.size+1)) == NULL)
        goto err;
    (void) memcpy(engine_id, engine_id_bin.data, engine_id_bin.size);
    engine_id[engine_id_bin.size] = '\0';

    if ((engine = ENGINE_by_id(engine_id)) == NULL) {
        PRINTF_ERR0("engine_by_id_nif Leaved: {error, bad_engine_id}");
        ret = ERROR_Atom(env, "bad_engine_id");
        goto done;
    }

    if ((ctx = enif_alloc_resource(engine_ctx_rtype, sizeof(struct engine_ctx))) == NULL)
        goto err;
    ctx->engine = engine;
    ctx->id = engine_id;
    /* ctx now owns engine_id */
    engine_id = NULL;

    result = enif_make_resource(env, ctx);
    ret = enif_make_tuple2(env, atom_ok, result);
    goto done;

 bad_arg:
 err:
    ret = enif_make_badarg(env);

 done:
    if (engine_id)
        enif_free(engine_id);
    if (ctx)
        enif_release_resource(ctx);
    return ret;

#else
    return atom_notsup;
#endif
}
Example #29
0
void initEngine(void)
{
    // init
    printf("**** Load engine ****\n");
    qeo_openssl_engine_init();
    qeo_openssl_engine_get_engine_id(&_engine_id); /* to be free()'d */
    _pkcs12_engine = ENGINE_by_id(_engine_id);

    qeo_platform_get_device_storage_path_StubWithCallback(qeo_platform_get_device_storage_path_callback);

    printf("**** Init engine ****\n");
    ck_assert_msg(ENGINE_init(_pkcs12_engine), "Failed to init engine");
}
Example #30
0
/* Try to load an engine in a shareable library */
static ENGINE *
try_load_engine (const char *engine)
{
  ENGINE *e = ENGINE_by_id ("dynamic");
  if (e)
    {
      if (!ENGINE_ctrl_cmd_string (e, "SO_PATH", engine, 0)
	  || !ENGINE_ctrl_cmd_string (e, "LOAD", NULL, 0))
	{
	  ENGINE_free (e);
	  e = NULL;
	}
    }
  return e;
}