Пример #1
1
int main(int argc, char *argv[]) {
    if(argc != 2) {
        printf("Usage: ./test_app <file_name>\n");
        return -1;
    }

    ENGINE *e = load_engine(ENGINE_MODULE, "test_engine");
    if(e == 0) {
        printf("Unable to load engine\n");
        return -1;
    }
    ENGINE_ctrl_cmd_string(e, "username", "user", 0);
    ENGINE_ctrl_cmd_string(e, "password", "password", 0);
    ENGINE_init(e);
    
    HMAC_CTX ctx;
    HMAC_CTX_init(&ctx);
    HMAC_Init_ex(&ctx, "test_key\0", 9, EVP_sha1(), e);

    FILE *f = fopen(argv[1], "r");
    char buf[BUF_SIZE];
    while(!feof(f)) {
        size_t ln = fread(buf, sizeof(char), BUF_SIZE, f);
        if(ln == 0) continue;
        HMAC_Update(&ctx, buf, ln);
    }
    fclose(f);
    
    unsigned int siglen;
    unsigned char md[20];
    HMAC_Final(&ctx, md, &siglen);
    ENGINE_finish(e);

    printf("HMAC-SHA1: ");
    for(size_t i = 0; i < siglen; i++) printf("%02x", md[i]);
    printf("\n");

    return 0;
}
Пример #2
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" );
}
Пример #4
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);
	}
}
Пример #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;
}
Пример #6
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
}
Пример #7
0
    void Initialize(const std::string& module,
                    const std::string& pin,
                    bool verbose)
    {
      if (pkcs11Initialized_)
      {
        LOG(ERROR) << "The PKCS#11 engine has already been initialized";
        throw OrthancException(ErrorCode_BadSequenceOfCalls);
      }

      if (module.empty() ||
          !SystemToolbox::IsRegularFile(module))
      {
        LOG(ERROR) << "The PKCS#11 module must be a path to one shared library (DLL or .so)";
        throw OrthancException(ErrorCode_InexistentFile);
      }

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

      if (!ENGINE_ctrl_cmd_string(engine, "MODULE_PATH", module.c_str(), 0))
      {
        LOG(ERROR) << "Cannot configure the OpenSSL dynamic engine for PKCS#11";
        throw OrthancException(ErrorCode_InternalError);
      }

      if (verbose)
      {
        ENGINE_ctrl_cmd_string(engine, "VERBOSE", NULL, 0);
      }

      if (!pin.empty() &&
          !ENGINE_ctrl_cmd_string(engine, "PIN", pin.c_str(), 0)) 
      {
        LOG(ERROR) << "Cannot set the PIN code for PKCS#11";
        throw OrthancException(ErrorCode_InternalError);
      }
  
      if (!ENGINE_init(engine))
      {
        LOG(ERROR) << "Cannot initialize the OpenSSL dynamic engine for PKCS#11";
        throw OrthancException(ErrorCode_InternalError);
      }

      LOG(WARNING) << "The PKCS#11 engine has been successfully initialized";
      pkcs11Initialized_ = true;
    }
Пример #8
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;
}
Пример #9
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);
}
Пример #10
0
static int openssl_engine_ctrl(lua_State*L){
	ENGINE* eng = CHECK_OBJECT(1,ENGINE,"openssl.engine");

	if(lua_isnumber(L, 2)){
		int cmd = luaL_checkint(L, 2);
		if(lua_isnoneornil(L, 3)){
			int ret = ENGINE_cmd_is_executable(eng, cmd);
			lua_pushboolean(L, ret);
		}else{
			long i = (long)luaL_checknumber(L, 3);
			void* p = lua_touserdata(L, 4);
			int ret = ENGINE_ctrl(eng, cmd, i, p, NULL);
			lua_pushboolean(L, ret);
		}
	}else{
		const char* cmd = luaL_checkstring(L, 2);
		if(lua_isnumber(L, 3))
		{
			long i = (long)luaL_checknumber(L, 3);
			void* p = lua_touserdata(L, 4);
			int opt = luaL_optint(L, 5, 0);
			int ret = ENGINE_ctrl_cmd(eng, cmd, i, p, NULL, opt);
			lua_pushboolean(L, ret);
		}else{
			const char* arg  = luaL_optstring(L, 3, NULL);
			int opt = luaL_optint(L, 4, 0);
			int ret = ENGINE_ctrl_cmd_string(eng, cmd, arg, opt);
			lua_pushboolean(L, ret);
		}
	}
	return 1;
}
Пример #11
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);
}
void 
TokenEngine::login( const string & pin )
{
    if ( 1 != ENGINE_ctrl_cmd_string( m_pEngine, "PIN",
                                      pin.c_str(), CMD_MANDATORY ) )
        throw Exception( "token: unable to log in"
                               " with PIN=" + QS( pin ) );
}
Пример #13
0
static void util_do_cmds(ENGINE *e, STACK *cmds, BIO *bio_out, const char *indent)
	{
	int loop, res, num = sk_num(cmds);
	if(num < 0)
		{
		BIO_printf(bio_out, "[Error]: internal stack error\n");
		return;
		}
	for(loop = 0; loop < num; loop++)
		{
		char buf[256];
		const char *cmd, *arg;
		cmd = sk_value(cmds, loop);
		res = 1; /* assume success */
		/* Check if this command has no ":arg" */
		if((arg = strstr(cmd, ":")) == NULL)
			{
			if(!ENGINE_ctrl_cmd_string(e, cmd, NULL, 0))
				res = 0;
			}
		else
			{
			if((int)(arg - cmd) > 254)
				{
				BIO_printf(bio_out,"[Error]: command name too long\n");
				return;
				}
			memcpy(buf, cmd, (int)(arg - cmd));
			buf[arg-cmd] = '\0';
			arg++; /* Move past the ":" */
			/* Call the command with the argument */
			if(!ENGINE_ctrl_cmd_string(e, buf, arg, 0))
				res = 0;
			}
		if(res)
			BIO_printf(bio_out, "[Success]: %s\n", cmd);
		else
			{
			BIO_printf(bio_out, "[Failure]: %s\n", cmd);
			ERR_print_errors(bio_out);
			}
		}
	}
Пример #14
0
/*
 * 'name' is the name the engine is known by to the dst library.
 * This may or may not match the name the engine is known by to
 * openssl.  It is the name that is stored in the private key file.
 *
 * 'engine_id' is the openssl engine name.
 *
 * pre_cmds and post_cmds a sequence if command argument pairs
 * pre_num and post_num are a count of those pairs.
 *
 * "SO_PATH", PKCS11_SO_PATH ("/usr/local/lib/engines/engine_pkcs11.so")
 * "LOAD", NULL
 * "MODULE_PATH", PKCS11_MODULE_PATH ("/usr/lib/libpkcs11.so")
 */
static isc_result_t
dst__openssl_load_engine(const char *name, const char *engine_id,
			 const char **pre_cmds, int pre_num,
			 const char **post_cmds, int post_num)
{
	ENGINE *e;

	UNUSED(name);

	if (!strcasecmp(engine_id, "dynamic"))
		ENGINE_load_dynamic();
	e = ENGINE_by_id(engine_id);
	if (e == NULL)
		return (ISC_R_NOTFOUND);
	while (pre_num--) {
		if (!ENGINE_ctrl_cmd_string(e, pre_cmds[0], pre_cmds[1], 0)) {
			ENGINE_free(e);
			return (ISC_R_FAILURE);
		}
		pre_cmds += 2;
	}
	if (!ENGINE_init(e)) {
		ENGINE_free(e);
		return (ISC_R_FAILURE);
	}
	/*
	 * ENGINE_init() returned a functional reference, so free the
	 * structural reference from ENGINE_by_id().
	 */
	ENGINE_free(e);
	while (post_num--) {
		if (!ENGINE_ctrl_cmd_string(e, post_cmds[0], post_cmds[1], 0)) {
			ENGINE_free(e);
			return (ISC_R_FAILURE);
		}
		post_cmds += 2;
	}
	if (he != NULL)
		ENGINE_finish(he);
	he = e;
	return (ISC_R_SUCCESS);
}
Пример #15
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; 
}
Пример #16
0
static VALUE
ossl_engine_ctrl_cmd(int argc, VALUE *argv, VALUE self)
{
    ENGINE *e;
    VALUE cmd, val;
    int ret;

    GetEngine(self, e);
    rb_scan_args(argc, argv, "11", &cmd, &val);
    StringValue(cmd);
    if (!NIL_P(val)) StringValue(val);
    ret = ENGINE_ctrl_cmd_string(e, RSTRING_PTR(cmd),
				 NIL_P(val) ? NULL : RSTRING_PTR(val), 0);
    if (!ret) ossl_raise(eEngineError, NULL);

    return self;
}
TokenEngine::TokenEngine( const StringList & modulePaths )
{
    ENGINE * tok = ENGINE_by_id( "pkcs11" );
    if ( ! tok )
        throw Exception( "token: unable to get engine" );

    m_pEngine = tok;

    const string modulePath( findFirstExisting( modulePaths ) );
    if ( modulePath.empty() )
        throw Exception( "token: unable to find module path" );

    DEBUG( "token: ctor: module_path=" << QS( modulePath ) );
    if ( 1 != ENGINE_ctrl_cmd_string( tok, "MODULE_PATH", modulePath.c_str(), CMD_MANDATORY ) )
        throw Exception( "token: setting module_path <= " + QS( modulePath ) );

    DEBUG( "token: ctor: initializing " << m_pEngine );
    if ( 1 != ENGINE_init( tok ) )
        throw Exception( "token: unable to initialize" );

    DEBUG( "token: ctor: done" );
}
Пример #18
0
static ENGINE *get_pkcs11_engine(GError **error)
{
	static ENGINE *e = NULL;
	unsigned long err;
	const gchar *data;
	const gchar *env;
	int flags;

	g_return_val_if_fail(error == NULL || *error == NULL, NULL);

	ENGINE_load_builtin_engines();

	e = ENGINE_by_id("pkcs11");
	if (e == NULL) {
		err = ERR_get_error_line_data(NULL, NULL, &data, &flags);
		g_set_error(
				error,
				R_SIGNATURE_ERROR,
				R_SIGNATURE_ERROR_LOAD_FAILED,
				"failed to load PKCS11 engine: %s",
				(flags & ERR_TXT_STRING) ? data : ERR_error_string(err, NULL));

		goto out;
	}

	env = g_getenv("RAUC_PKCS11_MODULE");
	if (env != NULL) {
		if (!ENGINE_ctrl_cmd_string(e, "MODULE_PATH", env, 0)) {
			err = ERR_get_error_line_data(NULL, NULL, &data, &flags);
			g_set_error(
					error,
					R_SIGNATURE_ERROR,
					R_SIGNATURE_ERROR_PARSE_ERROR,
					"failed to configure PKCS11 module path: %s",
					(flags & ERR_TXT_STRING) ? data : ERR_error_string(err, NULL));
			goto free;
		}
	}

	if (ENGINE_init(e) == 0) {
		err = ERR_get_error_line_data(NULL, NULL, &data, &flags);
		g_set_error(
				error,
				R_SIGNATURE_ERROR,
				R_SIGNATURE_ERROR_LOAD_FAILED,
				"failed to initialize PKCS11 engine: %s",
				(flags & ERR_TXT_STRING) ? data : ERR_error_string(err, NULL));

		goto free;
	}

	env = g_getenv("RAUC_PKCS11_PIN");
	if (env != NULL) {
		if (!ENGINE_ctrl_cmd_string(e, "PIN", env, 0)) {
			err = ERR_get_error_line_data(NULL, NULL, &data, &flags);
			g_set_error(
					error,
					R_SIGNATURE_ERROR,
					R_SIGNATURE_ERROR_PARSE_ERROR,
					"failed to configure PKCS11 PIN: %s",
					(flags & ERR_TXT_STRING) ? data : ERR_error_string(err, NULL));
			goto finish;
		}
	}

	goto out;

finish:
	ENGINE_finish(e);
free:
	ENGINE_free(e);
	e = NULL;
out:
	return e;
}
Пример #19
0
ENGINE *ENGINE_by_id(const char *id)
{
    ENGINE *iterator;
    char *load_dir = NULL;
    if (id == NULL) {
        ENGINEerr(ENGINE_F_ENGINE_BY_ID, ERR_R_PASSED_NULL_PARAMETER);
        return NULL;
    }
    CRYPTO_w_lock(CRYPTO_LOCK_ENGINE);
    iterator = engine_list_head;
    while (iterator && (strcmp(id, iterator->id) != 0))
        iterator = iterator->next;
    if (iterator != NULL) {
        /*
         * We need to return a structural reference. If this is an ENGINE
         * type that returns copies, make a duplicate - otherwise increment
         * the existing ENGINE's reference count.
         */
        if (iterator->flags & ENGINE_FLAGS_BY_ID_COPY) {
            ENGINE *cp = ENGINE_new();
            if (cp == NULL)
                iterator = NULL;
            else {
                engine_cpy(cp, iterator);
                iterator = cp;
            }
        } else {
            iterator->struct_ref++;
            engine_ref_debug(iterator, 0, 1);
        }
    }
    CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE);
    if (iterator != NULL)
        return iterator;
    /*
     * Prevent infinite recursion if we're looking for the dynamic engine.
     */
    if (strcmp(id, "dynamic")) {
# ifdef OPENSSL_SYS_VMS
        if ((load_dir = getenv("OPENSSL_ENGINES")) == 0)
            load_dir = "SSLROOT:[ENGINES]";
# else
        if ((load_dir = getenv("OPENSSL_ENGINES")) == 0)
            load_dir = ENGINESDIR;
# endif
        iterator = ENGINE_by_id("dynamic");
        if (!iterator || !ENGINE_ctrl_cmd_string(iterator, "ID", id, 0) ||
            !ENGINE_ctrl_cmd_string(iterator, "DIR_LOAD", "2", 0) ||
            !ENGINE_ctrl_cmd_string(iterator, "DIR_ADD",
                                    load_dir, 0) ||
            !ENGINE_ctrl_cmd_string(iterator, "LIST_ADD", "1", 0) ||
            !ENGINE_ctrl_cmd_string(iterator, "LOAD", NULL, 0))
            goto notfound;
        return iterator;
    }
 notfound:
    ENGINE_free(iterator);
    ENGINEerr(ENGINE_F_ENGINE_BY_ID, ENGINE_R_NO_SUCH_ENGINE);
    ERR_add_error_data(2, "id=", id);
    return NULL;
    /* EEK! Experimental code ends */
}
Пример #20
0
int main(int argc, char *argv[])
{
	ENGINE *engine;
	EVP_PKEY *pkey;
	X509 *cert;
	FILE *cert_fp;

	const char *module, *efile, *certfile, *privkey;

	int ret = 0;

	if (argc < 4){
		printf("Too few arguments\n");
		usage(argv);
		return 1;
	}

	certfile = argv[1];
	privkey = argv[2];
	module = argv[3];
	efile = argv[4];

	cert_fp = fopen(certfile, "rb");
	if (!cert_fp) {
		fprintf(stderr, "%s:%d Could not open file %s\n", __FILE__, __LINE__, certfile);
		ret = 1;
		goto end;
	}

	cert = PEM_read_X509(cert_fp, NULL, NULL, NULL);
	if (!cert) {
		fprintf(stderr, "%s:%d Could not read certificate file"
		        "(must be PEM format)\n", __FILE__, __LINE__);
	}

	if (cert_fp) {
		fclose(cert_fp);
	}

	ret = CONF_modules_load_file(efile, "engines", 0);
	if (ret <= 0) {
		fprintf(stderr, "%s:%d cannot load %s\n", __FILE__, __LINE__, efile);
		display_openssl_errors(__LINE__);
		exit(1);
	}

	ENGINE_add_conf_module();
#if OPENSSL_VERSION_NUMBER>=0x10100000
	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \
		| OPENSSL_INIT_ADD_ALL_DIGESTS \
		| OPENSSL_INIT_LOAD_CONFIG, NULL);
#else
	OpenSSL_add_all_algorithms();
	OpenSSL_add_all_digests();
	ERR_load_crypto_strings();
#endif
	ERR_clear_error();

	ENGINE_load_builtin_engines();

	engine = ENGINE_by_id("pkcs11");
	if (engine == NULL) {
		printf("%s:%d Could not get engine\n", __FILE__, __LINE__);
		display_openssl_errors(__LINE__);
		ret = 1;
		goto end;
	}

	if (!ENGINE_ctrl_cmd_string(engine, "VERBOSE", NULL, 0)) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (!ENGINE_ctrl_cmd_string(engine, "MODULE_PATH", module, 0)) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (!ENGINE_init(engine)) {
		printf("Could not initialize engine\n");
		display_openssl_errors(__LINE__);
		ret = 1;
		goto end;
	}

	pkey = ENGINE_load_private_key(engine, privkey, 0, 0);

	if (pkey == NULL) {
		printf("%s:%d Could not load key\n", __FILE__, __LINE__);
		display_openssl_errors(__LINE__);
		ret = 1;
		goto end;
	}



	ret = X509_check_private_key(cert, pkey);
	if (!ret) {
		printf("%s:%d Could not check private key\n", __FILE__, __LINE__);
		display_openssl_errors(__LINE__);
		ret = 1;
		goto end;
	}

	printf("Key and certificate matched\n");
	ret = 0;

	CONF_modules_unload(1);
end:
	X509_free(cert);
	EVP_PKEY_free(pkey);
	
	ENGINE_finish(engine);

	return ret;
}
Пример #21
0
// Constructor
OSSLCryptoFactory::OSSLCryptoFactory()
{
	// Multi-thread support
	nlocks = CRYPTO_num_locks();
	locks = new Mutex*[nlocks];
	for (unsigned i = 0; i < nlocks; i++)
	{
		locks[i] = MutexFactory::i()->getMutex();
	}
#ifdef HAVE_PTHREAD_H
	CRYPTO_set_id_callback(id_callback);
#endif
	CRYPTO_set_locking_callback(lock_callback);

#ifdef WITH_FIPS
	// Already in FIPS mode on reenter (avoiding selftests)
	if (!FIPS_mode())
	{
		FipsSelfTestStatus = false;
		if (!FIPS_mode_set(1))
		{
			ERROR_MSG("can't enter into FIPS mode");
			return;
		}
	} else {
		// Undo RAND_cleanup()
		RAND_init_fips();
	}
	FipsSelfTestStatus = true;
#endif

	// Initialise OpenSSL
	OpenSSL_add_all_algorithms();

	// Initialise the one-and-only RNG
	rng = new OSSLRNG();

#ifdef WITH_GOST
	// Load engines
	ENGINE_load_builtin_engines();

	// Initialise the GOST engine
	eg = ENGINE_by_id("gost");
	if (eg == NULL)
	{
		ERROR_MSG("can't get the GOST engine");
		return;
	}
	if (ENGINE_init(eg) <= 0)
	{
		ENGINE_free(eg);
		eg = NULL;
		ERROR_MSG("can't initialize the GOST engine");
		return;
	}
	// better than digest_gost
	EVP_GOST_34_11 = ENGINE_get_digest(eg, NID_id_GostR3411_94);
	if (EVP_GOST_34_11 == NULL)
	{
		ERROR_MSG("can't get the GOST digest");
		goto err;
	}
	// from the openssl.cnf
	if (ENGINE_register_pkey_asn1_meths(eg) <= 0)
	{
		ERROR_MSG("can't register ASN.1 for the GOST engine");
		goto err;
	}
	if (ENGINE_ctrl_cmd_string(eg,
				   "CRYPT_PARAMS",
				   "id-Gost28147-89-CryptoPro-A-ParamSet",
				   0) <= 0)
	{
		ERROR_MSG("can't set params of the GOST engine");
		goto err;
	}
	return;

err:
	ENGINE_finish(eg);
	ENGINE_free(eg);
	eg = NULL;
	return;
#endif
}
Пример #22
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;
}
Пример #23
0
ERL_NIF_TERM engine_ctrl_cmd_strings_nif(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{/* (Engine, Commands, Optional) */
#ifdef HAS_ENGINE_SUPPORT
    ERL_NIF_TERM ret;
    unsigned int cmds_len = 0;
    char **cmds = NULL;
    struct engine_ctx *ctx;
    unsigned int i;
    int optional = 0;
    int cmds_loaded = 0;

    // Get Engine
    ASSERT(argc == 3);

    if (!enif_get_resource(env, argv[0], engine_ctx_rtype, (void**)&ctx))
        goto bad_arg;

    PRINTF_ERR1("Engine Id:  %s\r\n", ENGINE_get_id(ctx->engine));
    // Get Command List
    if (!enif_get_list_length(env, argv[1], &cmds_len))
        goto bad_arg;

    if (cmds_len > (UINT_MAX / 2) - 1)
        goto err;
    cmds_len *= 2; // Key-Value list from erlang

    if ((size_t)cmds_len + 1 > SIZE_MAX / sizeof(char*))
        goto err;
    if ((cmds = enif_alloc((cmds_len + 1) * sizeof(char*))) == NULL)
        goto err;
    if (get_engine_load_cmd_list(env, argv[1], cmds, 0))
        goto err;
    cmds_loaded = 1;
    if (!enif_get_int(env, argv[2], &optional))
        goto err;

    for(i = 0; i < cmds_len; i+=2) {
        PRINTF_ERR2("Cmd:  %s:%s\r\n",
                   cmds[i] ? cmds[i] : "(NULL)",
                   cmds[i+1] ? cmds[i+1] : "(NULL)");
        if(!ENGINE_ctrl_cmd_string(ctx->engine, cmds[i], cmds[i+1], optional)) {
            PRINTF_ERR2("Command failed:  %s:%s\r\n",
                        cmds[i] ? cmds[i] : "(NULL)",
                        cmds[i+1] ? cmds[i+1] : "(NULL)");
            goto cmd_failed;
        }
    }
    ret = atom_ok;
    goto done;

 bad_arg:
 err:
    ret = enif_make_badarg(env);
    goto done;

 cmd_failed:
    ret = ERROR_Atom(env, "ctrl_cmd_failed");

 done:
    if (cmds_loaded) {
        for (i = 0; cmds != NULL && cmds[i] != NULL; i++)
            enif_free(cmds[i]);
    }

    if (cmds != NULL)
        enif_free(cmds);

    return ret;

#else
    return atom_notsup;
#endif
}
Пример #24
0
static int int_engine_configure(char *name, char *value, const CONF *cnf)
	{
	int i;
	int ret = 0;
	long do_init = -1;
	STACK_OF(CONF_VALUE) *ecmds;
	CONF_VALUE *ecmd;
	char *ctrlname, *ctrlvalue;
	ENGINE *e = NULL;
	name = skip_dot(name);
#ifdef ENGINE_CONF_DEBUG
	fprintf(stderr, "Configuring engine %s\n", name);
#endif
	/* Value is a section containing ENGINE commands */
	ecmds = NCONF_get_section(cnf, value);

	if (!ecmds)
		{
		ENGINEerr(ENGINE_F_INT_ENGINE_CONFIGURE, ENGINE_R_ENGINE_SECTION_ERROR);
		return 0;
		}

	for (i = 0; i < sk_CONF_VALUE_num(ecmds); i++)
		{
		ecmd = sk_CONF_VALUE_value(ecmds, i);
		ctrlname = skip_dot(ecmd->name);
		ctrlvalue = ecmd->value;
#ifdef ENGINE_CONF_DEBUG
	fprintf(stderr, "ENGINE conf: doing ctrl(%s,%s)\n", ctrlname, ctrlvalue);
#endif

		/* First handle some special pseudo ctrls */

		/* Override engine name to use */
		if (!strcmp(ctrlname, "engine_id"))
			name = ctrlvalue;
		/* Load a dynamic ENGINE */
		else if (!strcmp(ctrlname, "dynamic_path"))
			{
			e = ENGINE_by_id("dynamic");
			if (!e)
				goto err;
			if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", ctrlvalue, 0))
				goto err;
			if (!ENGINE_ctrl_cmd_string(e, "LIST_ADD", "2", 0))
				goto err;
			if (!ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0))
				goto err;
			}
		/* ... add other pseudos here ... */
		else
			{
			/* At this point we need an ENGINE structural reference
			 * if we don't already have one.
			 */
			if (!e)
				{
				e = ENGINE_by_id(name);
				if (!e)
					return 0;
				}
			/* Allow "EMPTY" to mean no value: this allows a valid
			 * "value" to be passed to ctrls of type NO_INPUT
		 	 */
			if (!strcmp(ctrlvalue, "EMPTY"))
				ctrlvalue = NULL;
			if (!strcmp(ctrlname, "init"))
				{
				if (!NCONF_get_number_e(cnf, value, "init", &do_init))
					goto err;
				if (do_init == 1)
					{
					if (!int_engine_init(e))
						goto err;
					}
				else if (do_init != 0)
					{
					ENGINEerr(ENGINE_F_INT_ENGINE_CONFIGURE, ENGINE_R_INVALID_INIT_VALUE);
					goto err;
					}
				}
			else if (!strcmp(ctrlname, "default_algorithms"))
				{
				if (!ENGINE_set_default_string(e, ctrlvalue))
					goto err;
				}
			else if (!ENGINE_ctrl_cmd_string(e,
					ctrlname, ctrlvalue, 0))
				return 0;
			}



		}
	if (e && (do_init == -1) && !int_engine_init(e))
		goto err;
	ret = 1;
	err:
	if (e)
		ENGINE_free(e);
	return ret;
	}
Пример #25
0
ENGINE *scep_engine_load_dynamic(ENGINE *e) {
	//it seems OpenSSL did not already have it. In this case we will try to load it dynamically
	e = ENGINE_by_id("dynamic");

	//if we can't even load the dynamic engine, something is seriously wrong. We can't go on from here!
	if(e == NULL) {
		fprintf(stderr, "%s: Engine dynamic could not be loaded, Error message\n", pname);
		sscep_engine_report_error();
		exit (SCEP_PKISTATUS_ERROR);
	} else if(v_flag)
		printf("%s: Engine dynamic was loaded\n", pname);

	//To load dynamically we have to tell openssl where to find it.
	if(scep_conf->engine->dynamic_path) {
		if(ENGINE_ctrl_cmd_string(e, "SO_PATH", scep_conf->engine->dynamic_path, 0) == 0) {
			fprintf(stderr, "%s: Loading %s did not succeed\n", pname, g_char);
			sscep_engine_report_error();
			exit (SCEP_PKISTATUS_ERROR);
		} else if (v_flag)
			printf("%s: %s was found.\n", pname, g_char);
	}

	//engine will be added to the list of available engines. Should be done for complete import.
	if(ENGINE_ctrl_cmd_string(e, "LIST_ADD", "1", 0) == 0) {
		fprintf(stderr, "%s: Executing LIST_ADD did not succeed:\n", pname);
		sscep_engine_report_error();
		exit (SCEP_PKISTATUS_ERROR);
	} else if(v_flag)
		printf("%s: Added %s to list of engines.\n", pname, g_char);

	/*if(!ENGINE_ctrl(e, (ENGINE_CMD_BASE + 12), 0, (void*)"REQUEST", NULL)) {
	} else if(v_flag)
		printf("Altered storename to %s\n", "REQUEST");*/

	//Finally we load the engine.
	if(ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0) == 0) {
		fprintf(stderr, "%s: Executing LOAD did not succeed:\n", pname);
		sscep_engine_report_error();
		exit (SCEP_PKISTATUS_ERROR);
	} else if(v_flag)
		printf("%s: Loading engine %s succeeded\n", pname, g_char);

	// Now issue any dynamic engine init cmds if any are configured
	if(scep_conf->engine->cmds != NULL) {
        int i=0;
        while(scep_conf->engine->cmds[i] != NULL) {
                 NAME_VALUE_PAIR *cmd = scep_conf->engine->cmds[i];
                 if(ENGINE_ctrl_cmd_string(e, cmd->name, cmd->value, 0) == 0) {
                         fprintf(stderr, "%s: Executing %s=%s failed\n", pname, cmd->name, cmd->value);
                         sscep_engine_report_error();
                         exit (SCEP_PKISTATUS_ERROR);
                 } else if(v_flag) {
                         fprintf(stderr, "%s: Engine command %s=%s succeeded\n", pname, cmd->name, cmd->value);
                 }
                 i++;
         }
	}

	//all these functions were only needed if we loaded dynamically. Otherwise we could just skip this step.

	return e;
}
Пример #26
0
int main(int argc, char **argv)
{
	EVP_PKEY *private_key, *public_key;
	EVP_PKEY_CTX *pkey_ctx;
	EVP_MD_CTX *md_ctx;

	const EVP_MD *digest_algo;

	char *private_key_name, *public_key_name;

	unsigned char sig[4096];
	size_t sig_len;

	unsigned char md[128];
	size_t md_len;
	unsigned digest_len;

	char *key_pass = NULL;
	const char *module_path, *efile;

	ENGINE *e;

	int ret;

	if (argc < 5) {
		fprintf(stderr, "usage: %s [PIN] [CONF] [private key URL] [public key URL] [module]\n", argv[0]);
		fprintf(stderr, "\n");
		exit(1);
	}

	key_pass = argv[1];
	efile = argv[2];
	private_key_name = argv[3];
	public_key_name = argv[4];
	module_path = argv[5];

	ret = CONF_modules_load_file(efile, "engines", 0);
	if (ret <= 0) {
		fprintf(stderr, "cannot load %s\n", efile);
		display_openssl_errors(__LINE__);
		exit(1);
	}

	ENGINE_add_conf_module();
#if OPENSSL_VERSION_NUMBER>=0x10100000
	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \
		| OPENSSL_INIT_ADD_ALL_DIGESTS \
		| OPENSSL_INIT_LOAD_CONFIG, NULL);
#else
	OpenSSL_add_all_algorithms();
	OpenSSL_add_all_digests();
	ERR_load_crypto_strings();
#endif
	ERR_clear_error();

	ENGINE_load_builtin_engines();
	e = ENGINE_by_id("pkcs11");
	if (e == NULL) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (!ENGINE_ctrl_cmd_string(e, "VERBOSE", NULL, 0)) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (!ENGINE_ctrl_cmd_string(e, "MODULE_PATH", module_path, 0)) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (!ENGINE_init(e)) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (key_pass && !ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0)) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	private_key = ENGINE_load_private_key(e, private_key_name, NULL, NULL);
	if (private_key == NULL) {
		fprintf(stderr, "cannot load: %s\n", private_key_name);
		display_openssl_errors(__LINE__);
		exit(1);
	}

	public_key = ENGINE_load_public_key(e, public_key_name, NULL, NULL);
	if (public_key == NULL) {
		fprintf(stderr, "cannot load: %s\n", public_key_name);
		display_openssl_errors(__LINE__);
		exit(1);
	}

	digest_algo = EVP_get_digestbyname("sha256");

#define TEST_DATA "test data"

	md_ctx = EVP_MD_CTX_create();
	if (EVP_DigestInit(md_ctx, digest_algo) <= 0) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (EVP_DigestUpdate(md_ctx, TEST_DATA, sizeof(TEST_DATA)) <= 0) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	digest_len = sizeof(md);
	if (EVP_DigestFinal(md_ctx, md, &digest_len) <= 0) {
		display_openssl_errors(__LINE__);
		exit(1);
	}
	md_len = digest_len;

	EVP_MD_CTX_destroy(md_ctx);

	/* Sign the hash */
	pkey_ctx = EVP_PKEY_CTX_new(private_key, e);

	if (pkey_ctx == NULL) {
		fprintf(stderr, "Could not create context\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (EVP_PKEY_sign_init(pkey_ctx) <= 0) {
		fprintf(stderr, "Could not init signature\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
		fprintf(stderr, "Could not set padding\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (EVP_PKEY_CTX_set_signature_md(pkey_ctx, digest_algo) <= 0) {
		fprintf(stderr, "Could not set message digest algorithm\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

	sig_len = sizeof(sig);
	if (EVP_PKEY_sign(pkey_ctx, sig, &sig_len, md,
			EVP_MD_size(digest_algo)) <= 0) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	EVP_PKEY_CTX_free(pkey_ctx);

	printf("Signature created\n");

#if OPENSSL_VERSION_NUMBER >= 0x1000000fL

	pkey_ctx = EVP_PKEY_CTX_new(public_key, e);

	if (pkey_ctx == NULL) {
		fprintf(stderr, "Could not create context\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (EVP_PKEY_verify_init(pkey_ctx) <= 0) {
		fprintf(stderr, "Could not init verify\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING) <= 0) {
		fprintf(stderr, "Could not set padding\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (EVP_PKEY_CTX_set_signature_md(pkey_ctx, digest_algo) <= 0) {
		fprintf(stderr, "Could not set message digest algorithm\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

	ret = EVP_PKEY_verify(pkey_ctx, sig, sig_len, md, md_len);
	if (ret < 0) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	EVP_PKEY_CTX_free(pkey_ctx);

	if (ret == 1) {
		printf("Signature verified\n");
	}
	else {
		printf("Verification failed\n");
		display_openssl_errors(__LINE__);
		exit(1);
	}

#else /* OPENSSL_VERSION_NUMBER >= 0x1000000fL */

	printf("Unable to verify signature with %s\n", OPENSSL_VERSION_TEXT);

#endif /* OPENSSL_VERSION_NUMBER >= 0x1000000fL */

	ENGINE_finish(e);
	CONF_modules_unload(1);
	return 0;
}
Пример #27
0
int main(int argc, char *argv[])
{
  int err=0;
  int v;
  RSA *key;
  unsigned char ptext[256];
  unsigned char ctext[256];
  static unsigned char ptext_ex[] = "\x54\x85\x9b\x34\x2c\x49\xea\x2a";
  unsigned char ctext_ex[256];
  int plen;
  int clen = 0;
  int num;
  int n;

  ENGINE *e;
  const char *engine_id = "remote";
  ENGINE_load_builtin_engines();
  e = ENGINE_by_id(engine_id);
  if(!e)
    /* the engine isn't available */
    return 1;
  if(!ENGINE_init(e)) {
    /* the engine couldn't initialise, release 'e' */
    ERR_print_errors_fp(stderr);
    ENGINE_free(e);
    return 1;
  }
  if(!ENGINE_set_default_RSA(e))
    /* This should only happen when 'e' can't initialise, but the previous
     * statement suggests it did. */
    abort();

  ENGINE_ctrl_cmd_string(e, "ADD_WORKER", "local1,127.0.0.1:1234", 0);

  CRYPTO_malloc_debug_init();
  CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
  CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

  RAND_seed(rnd_seed, sizeof rnd_seed); /* or OAEP may fail */

  plen = sizeof(ptext_ex) - 1;

  for (v = 0; v < 6; v++)
  {
    key = RSA_new();
    switch (v%3) {
      case 0:
        clen = key1(key, ctext_ex);
        break;
      case 1:
        clen = key2(key, ctext_ex);
        break;
      case 2:
        clen = key3(key, ctext_ex);
        break;
    }
    if (v/3 >= 1) key->flags |= RSA_FLAG_NO_CONSTTIME;

    num = RSA_public_encrypt(plen, ptext_ex, ctext, key,
        RSA_PKCS1_PADDING);
    if (num != clen)
    {
      printf("PKCS#1 v1.5 encryption failed!\n");
      err=1;
      goto oaep;
    }

    num = RSA_private_decrypt(num, ctext, ptext, key,
        RSA_PKCS1_PADDING);
    if (num != plen || memcmp(ptext, ptext_ex, num) != 0)
    {
      printf("PKCS#1 v1.5 decryption failed!\n");
      err=1;
    }
    else
      printf("PKCS #1 v1.5 encryption/decryption ok\n");

oaep:
    ERR_clear_error();
    num = RSA_public_encrypt(plen, ptext_ex, ctext, key,
        RSA_PKCS1_OAEP_PADDING);
    if (num == -1 && pad_unknown())
    {
      printf("No OAEP support\n");
      goto next;
    }
    if (num != clen)
    {
      printf("OAEP encryption failed!\n");
      err=1;
      goto next;
    }

    num = RSA_private_decrypt(num, ctext, ptext, key,
        RSA_PKCS1_OAEP_PADDING);
    if (num != plen || memcmp(ptext, ptext_ex, num) != 0)
    {
      printf("OAEP decryption (encrypted data) failed!\n");
      err=1;
    }
    else if (memcmp(ctext, ctext_ex, num) == 0)
      printf("OAEP test vector %d passed!\n", v);

    /* Different ciphertexts (rsa_oaep.c without -DPKCS_TESTVECT).
       Try decrypting ctext_ex */

    num = RSA_private_decrypt(clen, ctext_ex, ptext, key,
        RSA_PKCS1_OAEP_PADDING);

    if (num != plen || memcmp(ptext, ptext_ex, num) != 0)
    {
      printf("OAEP decryption (test vector data) failed!\n");
      err=1;
    }
    else
      printf("OAEP encryption/decryption ok\n");

    /* Try decrypting corrupted ciphertexts */
    for(n = 0 ; n < clen ; ++n)
    {
      int b;
      unsigned char saved = ctext[n];
      for(b = 0 ; b < 256 ; ++b)
      {
        if(b == saved)
          continue;
        ctext[n] = b;
        num = RSA_private_decrypt(num, ctext, ptext, key,
            RSA_PKCS1_OAEP_PADDING);
        if(num > 0)
        {
          printf("Corrupt data decrypted!\n");
          err = 1;
        }
      }
    }
next:
    RSA_free(key);
  }

  ENGINE_finish(e);
  ENGINE_free(e);

  CRYPTO_cleanup_all_ex_data();
  ERR_remove_state(0);

  CRYPTO_mem_leaks_fp(stderr);

#ifdef OPENSSL_SYS_NETWARE
  if (err) printf("ERROR: %d\n", err);
#endif
  return err;
}
Пример #28
0
int
main(int argc, char *argv[])
{
    ENGINE *e;
    EVP_PKEY *pub_key;
    FILE *fp;
    char *engine = NULL;
    char *pin = NULL;
    char *keyname = NULL;
    char *filename = NULL;
    int c, errflg = 0;
    extern char *optarg;
    extern int optopt;
       
    while ((c = getopt(argc, argv, ":e:p:k:f:")) != -1) {
        switch (c) {
        case 'e':
            engine = optarg;
            break;
	case 'p':
	    pin = optarg;
	    break;
        case 'k':
            keyname = optarg;
            break;
        case 'f':
            filename = optarg;
            break;
        case ':':
            fprintf(stderr, "Option -%c requires an operand\n", optopt);
            errflg++;
            break;
        case '?':
	default:
            fprintf(stderr, "Unrecognised option: -%c\n", optopt);
            errflg++;
        }
    }
    if ((errflg) || (!engine) || (!filename) || (!keyname)) {
        fprintf(stderr,
		"usage: PEM_write_pubkey -e engine [-p pin] "
		"-k keyname -f filename\n");
        exit(1);
    }
    
    /* Load the config file */
    OPENSSL_config(NULL);

    /* Register engine */
    e = ENGINE_by_id(engine);
    if (!e) {
        /* the engine isn't available */
        printf("The engine isn't available\n");
	ERR_print_errors_fp(stderr);
        exit(1);
    }
    
    /* Send PIN to engine */
    if (pin && !ENGINE_ctrl_cmd_string(e, "PIN", pin, 0)){
        printf("Error sending PIN to engine\n");
	ERR_print_errors_fp(stderr);
        ENGINE_free(e);
        exit(1);
    }
    
    if (!ENGINE_init(e)) {
        /* the engine couldn't initialise, release 'e' */
        printf("The engine couldn't initialise\n");
	ERR_print_errors_fp(stderr);
        ENGINE_free(e);
        exit(1);
    }

    if (!ENGINE_register_RSA(e)){
        /* This should only happen when 'e' can't initialise, but the previous
	 * statement suggests it did. */
        printf("This should not happen\n");
	ERR_print_errors_fp(stderr);
        exit(1);
    }
    
    /* Load public key */
    pub_key = ENGINE_load_public_key(e, keyname, NULL, NULL);
    if (pub_key == NULL) {
        /* No public key */
        printf("Error loading public key\n");
	ERR_print_errors_fp(stderr);
        ENGINE_free(e);
        exit(1);
    }

    /* write public key to file in PEM format */
    fp = fopen(filename, "w");
    if (fp == NULL) {
        printf("Error opening output file.\n");
	ENGINE_free(e);
        exit(1);
    }
     
    if (!PEM_write_PUBKEY(fp, pub_key)) {
        /* Error writing public key */
        printf("Error writing public key");
	ERR_print_errors_fp(stderr);
        ENGINE_free(e);
        exit(1);
    }
    
    fclose(fp);
    exit(0);
}
Пример #29
0
int main(int argc, char **argv)
{
	char *cert_src;

	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();
	ERR_clear_error();

	kbuild_verbose = atoi(getenv("KBUILD_VERBOSE")?:"0");

        key_pass = getenv("KBUILD_SIGN_PIN");

	if (argc != 3)
		format();

	cert_src = argv[1];
	cert_dst = argv[2];

	if (!cert_src[0]) {
		/* Invoked with no input; create empty file */
		FILE *f = fopen(cert_dst, "wb");
		ERR(!f, "%s", cert_dst);
		fclose(f);
		exit(0);
	} else if (!strncmp(cert_src, "pkcs11:", 7)) {
		ENGINE *e;
		struct {
			const char *cert_id;
			X509 *cert;
		} parms;

		parms.cert_id = cert_src;
		parms.cert = NULL;

		ENGINE_load_builtin_engines();
		drain_openssl_errors();
		e = ENGINE_by_id("pkcs11");
		ERR(!e, "Load PKCS#11 ENGINE");
		if (ENGINE_init(e))
			drain_openssl_errors();
		else
			ERR(1, "ENGINE_init");
		if (key_pass)
			ERR(!ENGINE_ctrl_cmd_string(e, "PIN", key_pass, 0), "Set PKCS#11 PIN");
		ENGINE_ctrl_cmd(e, "LOAD_CERT_CTRL", 0, &parms, NULL, 1);
		ERR(!parms.cert, "Get X.509 from PKCS#11");
		write_cert(parms.cert);
	} else {
		BIO *b;
		X509 *x509;

		b = BIO_new_file(cert_src, "rb");
		ERR(!b, "%s", cert_src);

		while (1) {
			x509 = PEM_read_bio_X509(b, NULL, NULL, NULL);
			if (wb && !x509) {
				unsigned long err = ERR_peek_last_error();
				if (ERR_GET_LIB(err) == ERR_LIB_PEM &&
				    ERR_GET_REASON(err) == PEM_R_NO_START_LINE) {
					ERR_clear_error();
					break;
				}
			}
			ERR(!x509, "%s", cert_src);
			write_cert(x509);
		}
	}

	BIO_free(wb);

	return 0;
}