Beispiel #1
0
bool
SSLContext::Init(X509 *pCert, EVP_PKEY *pPrivatekey){
	int nLockCt = CRYPTO_num_locks();
	InitializeCryptoLocks(nLockCt);

#ifdef _DEBUG
    CRYPTO_malloc_debug_init();
    CRYPTO_dbg_set_options	(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl			(CRYPTO_MEM_CHECK_ON);
#endif
	
	CRYPTO_set_locking_callback			(&ssl_lock_callback);
    CRYPTO_set_dynlock_create_callback	(&ssl_lock_dyn_create_callback);
	CRYPTO_set_dynlock_lock_callback	(&ssl_lock_dyn_callback);
    CRYPTO_set_dynlock_destroy_callback	(&ssl_lock_dyn_destroy_callback);

    SSL_load_error_strings	();
    SSL_library_init		();

	// Initialize and verify SSL context. {{
	const SSL_METHOD* meth = SSLv23_method();
	m_pssl_ctx = SSL_CTX_new(meth);
	SSL_CTX_set_verify(m_pssl_ctx, SSL_VERIFY_NONE, nullptr);
	// }}

#ifdef _SERVER
	SSL_CTX_set_options(m_pssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); 
#endif

	if( pCert )
		SSL_CTX_use_certificate	(m_pssl_ctx, pCert);
	if( pPrivatekey )
		SSL_CTX_use_PrivateKey	(m_pssl_ctx, pPrivatekey);
	return true;
	}
bool
SSLSocketServer::SSL_Init(){
	int nLockCt = CRYPTO_num_locks();
	InitializeCryptoLocks(nLockCt);

#ifdef _DEBUG
    CRYPTO_malloc_debug_init();
    CRYPTO_dbg_set_options	(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl			(CRYPTO_MEM_CHECK_ON);
#endif
	
	CRYPTO_set_locking_callback			(&ssl_lock_callback);
    CRYPTO_set_dynlock_create_callback	(&ssl_lock_dyn_create_callback);
	CRYPTO_set_dynlock_lock_callback	(&ssl_lock_dyn_callback);
    CRYPTO_set_dynlock_destroy_callback	(&ssl_lock_dyn_destroy_callback);

    SSL_load_error_strings	();
    SSL_library_init		();

	// Initialize and verify SSL context. {{
	const SSL_METHOD* meth = SSLv23_method();
	m_pssl_ctx = SSL_CTX_new(meth);
	SSL_CTX_set_verify(m_pssl_ctx, SSL_VERIFY_NONE, nullptr);
	// }}

	::InitializeCriticalSection(&m_lock_connect_ex);
	return true;
	}
Beispiel #3
0
CSSLApplication::CSSLApplication()
{
	if (SSLInited) return;
	SSLInited = 1;
	NeedDataOp = 0;

#ifdef _DEBUG
	// OpenSSL internal memory-leak checkers
	CRYPTO_malloc_debug_init();
	CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
#endif

	openssl_locks = new Synchronizer[CRYPTO_num_locks()];

	// callbacks for static lock
	CRYPTO_set_locking_callback(funcOpenSSLLockingCallback);
	CRYPTO_set_id_callback(funcOpenSSLIDCallback);

	// callbacks for dynamic lock
	CRYPTO_set_dynlock_create_callback(funcOpenSSLDynCreateCallback);
	CRYPTO_set_dynlock_destroy_callback(funcOpenSSLDynDestroyCallback);
	CRYPTO_set_dynlock_lock_callback(funcOpenSSLDynLockCallback);

	// Load algorithms and error strings.
	SSL_load_error_strings();
	SSL_library_init();
};
Beispiel #4
0
static int
crypto( const char     *key,
        bool           decrypt,
        const bytes_t  &bytes,
        bytes_t        &crypt )
{
    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 */

	RSA *rsa = NULL;

	int rval = loadKey(key, decrypt, &rsa);
	if ( rval == 0 )
		rval = crypto(rsa, decrypt, bytes, crypt);

	RSA_free(rsa);
	ERR_print_errors_fp(stdout);

    CRYPTO_cleanup_all_ex_data();
	EVP_cleanup();
	ERR_remove_state(0);
    CRYPTO_mem_leaks_fp(stderr);

	return ( rval );
}
Beispiel #5
0
int main(int argc, char **argv)
{
    int i;
    testdata *test = test_cases;

    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    OpenSSL_add_all_digests();
# ifndef OPENSSL_NO_ENGINE
    ENGINE_load_builtin_engines();
    ENGINE_register_all_digests();
# endif

    printf("PKCS5_PBKDF2_HMAC() tests ");
    for (i = 0; test->pass != NULL; i++, test++) {
        test_p5_pbkdf2(i, "sha1", test, sha1_results[i]);
        test_p5_pbkdf2(i, "sha256", test, sha256_results[i]);
        test_p5_pbkdf2(i, "sha512", test, sha512_results[i]);
        printf(".");
    }
    printf(" done\n");

# ifndef OPENSSL_NO_ENGINE
    ENGINE_cleanup();
# endif
    EVP_cleanup();
    CRYPTO_cleanup_all_ex_data();
    ERR_remove_thread_state(NULL);
    ERR_free_strings();
    CRYPTO_mem_leaks_fp(stderr);
    return 0;
}
Beispiel #6
0
int main(int argc, char **argv)
	{
	BIO *bio_err;
	bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);

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

	ERR_load_crypto_strings();

	/* "Negative" test, expect a mismatch */
	if(run_srp("alice", "password1", "password2") == 0)
		{
		fprintf(stderr, "Mismatched SRP run failed\n");
		return 1;
		}

	/* "Positive" test, should pass */
	if(run_srp("alice", "password", "password") != 0)
		{
		fprintf(stderr, "Plain SRP run failed\n");
		return 1;
		}

	CRYPTO_cleanup_all_ex_data();
	ERR_remove_thread_state(NULL);
	ERR_free_strings();
	CRYPTO_mem_leaks(bio_err);

	return 0;
	}
int main(int argc, char *argv[])
	{	
	
	/* enable memory leak checking unless explicitly disabled */
	if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL) && (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off"))))
		{
		CRYPTO_malloc_debug_init();
		CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
		}
	else
		{
		/* OPENSSL_DEBUG_MEMORY=off */
		CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
		}
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
	ERR_load_crypto_strings();

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

	prime_field_tests();
	puts("");
	char2_field_tests();
	/* test the internal curves */
	internal_curve_test();

#ifndef OPENSSL_NO_ENGINE
	ENGINE_cleanup();
#endif
	CRYPTO_cleanup_all_ex_data();
	ERR_free_strings();
	ERR_remove_state(0);
	CRYPTO_mem_leaks_fp(stderr);
	
	return 0;
	}
Beispiel #8
0
/* Notice the program will be memory leak, as Mem_lhas is not free, 
** and record the user malloc informations. */
int main()
{
	char *p = NULL;
	int i;
	BIO *b = NULL;
	// There are two methods calls debug functions.
	// 1, build with -DCRYPTO_MDEBUG
	// 2, CRYPTO_malloc_debug_init(), CRYPTO_set_mem_debug_options()
	CRYPTO_malloc_debug_init();
	CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
	MemCheck_start();
	//p = OPENSSL_malloc(4);
	//p = OPENSSL_remalloc(p, 40);
	p = OPENSSL_malloc(1024);
	for(i = 0; i < 1024; i++)
		memset(&p[i], i, 1);
	
	OPENSSL_free(p);

	b = BIO_new_file("leak.log", "w");

	CRYPTO_mem_leaks(b);

	
	BIO_free(b);
	
	return 0;
}
Beispiel #9
0
/**
   \ingroup Core_Crypto
   \brief initialises openssl
   \note Would usually call ops_init() instead
   \sa ops_init()
*/
void ops_crypto_init()
    {
#ifdef DMALLOC
    CRYPTO_malloc_debug_init();
    CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
#endif
    }
Beispiel #10
0
void
Application::initSSL()
{
    CRYPTO_malloc_debug_init();
    CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
    RAND_seed(kRandSeed, sizeof(kRandSeed));
}
int ssl_test_ecdh(int argc, char *argv[])
	{
	BN_CTX *ctx=NULL;
	int ret=1;
	BIO *out;

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

#ifdef OPENSSL_SYS_WIN32
	CRYPTO_malloc_init();
#endif

	RAND_seed(rnd_seed, sizeof rnd_seed);

#ifndef OPENSSL_SYS_WINDOWS
	out = BIO_new(BIO_s_mem());
	if (out == NULL) return(1);

#else
	out=BIO_new(BIO_s_file());
	if (out == NULL) return(1);
	BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE);
#endif	

	if ((ctx=BN_CTX_new()) == NULL) goto err;

	/* NIST PRIME CURVES TESTS */
	if (!test_ecdh_curve(NID_X9_62_prime192v1, "NIST Prime-Curve P-192", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_secp224r1, "NIST Prime-Curve P-224", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_X9_62_prime256v1, "NIST Prime-Curve P-256", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_secp384r1, "NIST Prime-Curve P-384", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_secp521r1, "NIST Prime-Curve P-521", ctx, out)) goto err;
	/* NIST BINARY CURVES TESTS */
	if (!test_ecdh_curve(NID_sect163k1, "NIST Binary-Curve K-163", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect163r2, "NIST Binary-Curve B-163", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect233k1, "NIST Binary-Curve K-233", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect233r1, "NIST Binary-Curve B-233", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect283k1, "NIST Binary-Curve K-283", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect283r1, "NIST Binary-Curve B-283", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect409k1, "NIST Binary-Curve K-409", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect409r1, "NIST Binary-Curve B-409", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect571k1, "NIST Binary-Curve K-571", ctx, out)) goto err;
	if (!test_ecdh_curve(NID_sect571r1, "NIST Binary-Curve B-571", ctx, out)) goto err;

	ret = 0;

err:
	ERR_print_errors_fp(OPENSSL_TYPE__FILE_STDERR);
	if (ctx) BN_CTX_free(ctx);
	BIO_free(out);
	CRYPTO_cleanup_all_ex_data();
	ERR_remove_thread_state(NULL);
	CRYPTO_mem_leaks_fp(OPENSSL_TYPE__FILE_STDERR);
	return(ret);
	}
Beispiel #12
0
isc_result_t
dst__openssl_init() {
	isc_result_t result;

#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
	e = ENGINE_new();
	if (e == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup_rm;
	}
	ENGINE_set_RAND(e, rm);
	RAND_set_rand_method(rm);
#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);
}
Beispiel #13
0
int main(void)
{
    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    ERR_load_crypto_strings();
    /* Load up the software EVP_CIPHER and EVP_MD definitions */
    OpenSSL_add_all_ciphers();
    OpenSSL_add_all_digests();

    if (!test_EVP_DigestSignInit()) {
        fprintf(stderr, "EVP_DigestSignInit failed\n");
        return 1;
    }

    if (!test_EVP_DigestVerifyInit()) {
        fprintf(stderr, "EVP_DigestVerifyInit failed\n");
        return 1;
    }

    if (!test_d2i_AutoPrivateKey(kExampleRSAKeyDER, sizeof(kExampleRSAKeyDER),
                                 EVP_PKEY_RSA)) {
        fprintf(stderr, "d2i_AutoPrivateKey(kExampleRSAKeyDER) failed\n");
        return 1;
    }

    if (!test_d2i_AutoPrivateKey
        (kExampleRSAKeyPKCS8, sizeof(kExampleRSAKeyPKCS8), EVP_PKEY_RSA)) {
        fprintf(stderr, "d2i_AutoPrivateKey(kExampleRSAKeyPKCS8) failed\n");
        return 1;
    }

#ifndef OPENSSL_NO_EC
    if (!test_d2i_AutoPrivateKey(kExampleECKeyDER, sizeof(kExampleECKeyDER),
                                 EVP_PKEY_EC)) {
        fprintf(stderr, "d2i_AutoPrivateKey(kExampleECKeyDER) failed\n");
        return 1;
    }

    if (!test_EVP_PKCS82PKEY()) {
        fprintf(stderr, "test_EVP_PKCS82PKEY failed\n");
        return 1;
    }
#endif

    EVP_cleanup();
    CRYPTO_cleanup_all_ex_data();
    ERR_remove_thread_state(NULL);
    ERR_free_strings();
    CRYPTO_mem_leaks_fp(stderr);

    printf("PASS\n");
    return 0;
}
Beispiel #14
0
int main(int argc, char *argv[]) {
  int ret = 1;
  BIO *out;

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

#ifdef OPENSSL_SYS_WIN32
  CRYPTO_malloc_init();
#endif

  RAND_seed(rnd_seed, sizeof rnd_seed);

  out = BIO_new(BIO_s_file());
  if (out == NULL) EXIT(1);
  BIO_set_fp(out, stdout, BIO_NOCLOSE);

  if (argc == 1) {
    if (!test_lwekex(out, 1)) goto err;
  } else if (argc == 2 && !strcmp((const char *)argv[1], "cont")) {
    BIO_printf(out, "Running continuous test. ^C to quit.\n\n");
    int iterations = 0;
    int failures = 0;
    time_t starttime = time(NULL);
    while (1) {
      iterations++;
      if (test_lwekex(out, 0) == 1) {
      } else {
        failures++;
      }
      if ((iterations % 100) == 0) {
        BIO_printf(out, "Iterations: %d, failures: %d, elapsed time: %ld\n",
                   iterations, failures, time(NULL) - starttime);
        if (iterations > (1 << 20)) break;
      }
    }
  } else {
    BIO_printf(out,
               "Error: argument must be \"cont\" for invoking \
continuously run test.\n");
  }

  ret = 0;

err:
  ERR_print_errors_fp(stderr);
  BIO_free(out);
  CRYPTO_cleanup_all_ex_data();
  ERR_remove_thread_state(NULL);
  CRYPTO_mem_leaks_fp(stderr);
  EXIT(ret);
  return (ret);
}
Beispiel #15
0
int main(void)
{
    int 	ret = 1;
    BIO	*out;

    out = BIO_new_fp(stdout, BIO_NOCLOSE);

    /* enable memory leak checking unless explicitly disabled */
    if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL) &&
            (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off"))))
    {
        CRYPTO_malloc_debug_init();
        CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    }
    else
    {
        /* OPENSSL_DEBUG_MEMORY=off */
        CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
    }
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    ERR_load_crypto_strings();

    /* initialize the prng */
    RAND_seed(rnd_seed, sizeof(rnd_seed));

    /* the tests */
    if (!x9_62_tests(out))  goto err;
    if (!test_builtin(out)) goto err;

    ret = 0;
err:
    if (ret)
        BIO_printf(out, "\nECDSA test failed\n");
    else
        BIO_printf(out, "\nECDSA test passed\n");
    if (ret)
        ERR_print_errors(out);
    CRYPTO_cleanup_all_ex_data();
    ERR_remove_state(0);
    ERR_free_strings();
    CRYPTO_mem_leaks(out);
    if (out != NULL)
        BIO_free(out);
    return ret;
}
Beispiel #16
0
void OPENSSL_init(void)
{
#ifdef OPENSSL_FIPS
    static int done = 0;
    if (!done) {
        int_ERR_lib_init();
# ifdef CRYPTO_MDEBUG
        CRYPTO_malloc_debug_init();
# endif
# ifndef OPENSSL_NO_ENGINE
        int_EVP_MD_init_engine_callbacks();
        int_EVP_CIPHER_init_engine_callbacks();
        int_RAND_init_engine_callbacks();
# endif
        done = 1;
    }
#endif
}
Beispiel #17
0
int main(int argc, char **argv)
{

#ifdef ASYNC_NULL
    fprintf(stderr, "NULL implementation - skipping async tests\n");
#else
    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    if (       !test_ASYNC_init()
            || !test_ASYNC_start_job()
            || !test_ASYNC_get_current_job()
            || !test_ASYNC_get_wait_fd()
            || !test_ASYNC_block_pause()) {
        return 1;
    }
#endif
    printf("PASS\n");
    return 0;
}
Beispiel #18
0
int main(int argc, char *argv[])
{
    BN_CTX *ctx = NULL;
    int ret = 1;
    BIO *out;

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

# ifdef OPENSSL_SYS_WIN32
    CRYPTO_malloc_init();
# endif

    RAND_seed(rnd_seed, sizeof(rnd_seed));

    out = BIO_new(BIO_s_file());
    if (out == NULL)
        EXIT(1);
    BIO_set_fp(out, stdout, BIO_NOCLOSE);

    if ((ctx = BN_CTX_new()) == NULL)
        goto err;

    /* NIST PRIME CURVES TESTS */
    if (!test_ecdh_curve
        (NID_X9_62_prime192v1, "NIST Prime-Curve P-192", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_secp224r1, "NIST Prime-Curve P-224", ctx, out))
        goto err;
    if (!test_ecdh_curve
        (NID_X9_62_prime256v1, "NIST Prime-Curve P-256", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_secp384r1, "NIST Prime-Curve P-384", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_secp521r1, "NIST Prime-Curve P-521", ctx, out))
        goto err;
# ifndef OPENSSL_NO_EC2M
    /* NIST BINARY CURVES TESTS */
    if (!test_ecdh_curve(NID_sect163k1, "NIST Binary-Curve K-163", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect163r2, "NIST Binary-Curve B-163", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect233k1, "NIST Binary-Curve K-233", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect233r1, "NIST Binary-Curve B-233", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect283k1, "NIST Binary-Curve K-283", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect283r1, "NIST Binary-Curve B-283", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect409k1, "NIST Binary-Curve K-409", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect409r1, "NIST Binary-Curve B-409", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect571k1, "NIST Binary-Curve K-571", ctx, out))
        goto err;
    if (!test_ecdh_curve(NID_sect571r1, "NIST Binary-Curve B-571", ctx, out))
        goto err;
# endif
    if (!test_ecdh_kat(out, "Brainpool Prime-Curve brainpoolP256r1", 256))
        goto err;
    if (!test_ecdh_kat(out, "Brainpool Prime-Curve brainpoolP384r1", 384))
        goto err;
    if (!test_ecdh_kat(out, "Brainpool Prime-Curve brainpoolP512r1", 512))
        goto err;

    ret = 0;

 err:
    ERR_print_errors_fp(stderr);
    if (ctx)
        BN_CTX_free(ctx);
    BIO_free(out);
    CRYPTO_cleanup_all_ex_data();
    ERR_remove_thread_state(NULL);
    CRYPTO_mem_leaks_fp(stderr);
    EXIT(ret);
    return (ret);
}
Beispiel #19
0
int main (int argc, char **argv)
{
    signed char c;
    int set_fips_return = 0;
    char file_name[MAX_FILENAME_LEN];
    BIO *keyin;
    BIO *certin;
    static struct option long_options[] = {
        { "trustanchor",  1, 0,    0 },
        { "srp",          0, 0,    0 },
        { "srp-user",     1, 0,    0 },
        { "srp-password", 1, 0,    0 },
        { "auth-token",   1, 0,    0 },
        { "common-name",  1, 0,    0 },
        { "pem-output",   0, 0,    0 },
        { NULL,           0, NULL, 0 }
    };
    int option_index = 0;
    int trustanchor = 1; /* default to require a trust anchor */
    char *trustanchor_file = NULL;

    est_http_uid[0] = 0x0;
    est_http_pwd[0] = 0x0;

    /*
     * Set the default common name to put into the Subject field
     */
    strncpy(subj_cn, "127.0.0.1", MAX_CN);

    memset(csr_file, 0, 1);
    memset(priv_key_file, 0, 1);
    memset(client_key_file, 0, 1);
    memset(client_cert_file, 0, 1);
    memset(out_dir, 0, 1);

    while ((c = getopt_long(argc, argv, "?zfvagerx:y:k:s:p:o:c:w:u:h:", long_options, &option_index)) != -1) {
        switch (c) {
        case 0:
#if 0
            printf("option %s", long_options[option_index].name);
            if (optarg) {
                printf(" with arg %s", optarg);
            }
            printf("\n");
#endif
            if (!strncmp(long_options[option_index].name, "trustanchor", strlen("trustanchor"))) {
                if (!strncmp(optarg, "no", strlen("no"))) {
                    trustanchor = 0;
                } else {
                    trustanchor_file = optarg;
                }
            }
            if (!strncmp(long_options[option_index].name, "srp", strlen("srp"))) {
                srp = 1;
            }
            if (!strncmp(long_options[option_index].name, "srp-user", strlen("srp-user"))) {
                strncpy(est_srp_uid, optarg, MAX_UID_LEN);
            }
            if (!strncmp(long_options[option_index].name, "srp-password", strlen("srp-password"))) {
                strncpy(est_srp_pwd, optarg, MAX_PWD_LEN);
            }
	    if (!strncmp(long_options[option_index].name,"auth-token", strlen("auth-token"))) {
		strncpy(est_auth_token, optarg, MAX_AUTH_TOKEN_LEN);
                token_auth_mode = 1;
	    }
            if (!strncmp(long_options[option_index].name, "common-name", strlen("common-name"))) {
                strncpy(subj_cn, optarg, MAX_CN);
            }
            if (!strncmp(long_options[option_index].name, "pem-output", strlen("pem-output"))) {
                pem_out = 1;
            }
            break;
        case 'v':
            verbose = 1;
            break;
        case 'z':
            force_pop = 1;
            break;
        case 'a':
            getcsr = 1;
            break;
        case 'g':
            getcert = 1;
            break;
        case 'e':
            enroll = 1;
            break;
        case 'r':
            reenroll = 1;
            break;
        case 'u':
            strncpy(est_http_uid, optarg, MAX_UID_LEN);
            break;
        case 'h':
            strncpy(est_http_pwd, optarg, MAX_PWD_LEN);
            break;
        case 's':
            strncpy(est_server, optarg, MAX_SERVER_LEN);
            break;
        case 'x':
            strncpy(priv_key_file, optarg, MAX_FILENAME_LEN);
            break;
        case 'y':
            strncpy(csr_file, optarg, MAX_FILENAME_LEN);
            break;
        case 'k':
            strncpy(client_key_file, optarg, MAX_FILENAME_LEN);
            break;
        case 'c':
            strncpy(client_cert_file, optarg, MAX_FILENAME_LEN);
            break;
        case 'o':
            strncpy(out_dir, optarg, MAX_FILENAME_LEN);
            break;
        case 'p':
            est_port = atoi(optarg);
            break;
        case 'f':
            /* Turn FIPS on if requested and exit if failure */
            set_fips_return = FIPS_mode_set(1);
            if (!set_fips_return) {
                printf("\nERROR setting FIPS MODE ON ...\n");
                ERR_load_crypto_strings();
                ERR_print_errors(BIO_new_fp(stderr, BIO_NOCLOSE));
                exit(1);
            } else {
                printf("\nRunning EST Sample Client with FIPS MODE = ON\n");
            };
            break;
        case 'w':
            read_timeout = atoi(optarg);
            if (read_timeout > EST_SSL_READ_TIMEOUT_MAX) {
                printf("\nMaxium number of seconds to wait is %d, ", EST_SSL_READ_TIMEOUT_MAX);
                printf("please use a lower value with the -w option\n");
                exit(1);
            }
            break;
        default:
            show_usage_and_exit();
            break;
        }
    }
    if (optind < argc) {
        printf("non-option ARGV-elements: ");
        while (optind < argc) {
            printf("%s ", argv[optind++]);
        }
        printf("\n");
    }
    argc -= optind;
    argv += optind;

    if (est_http_uid[0] && !est_http_pwd[0]) {
        printf("Error: The password for HTTP authentication must be specified when the HTTP user name is set.\n");
        exit(1);
    }

    if (csr_file[0] && getcsr) {
        printf("\nError: The -a option (CSR attributes) does not make sense with a pre-defined CSR\n");
        exit(1);
    }
    if (csr_file[0] && priv_key_file[0]) {
        printf("\nError: The -x option (private key for CSR) does not make sense with a pre-defined CSR\n");
        exit(1);
    }
    if (csr_file[0] && force_pop) {
        printf("\nError: The -z option (PoP) does not make sense with a pre-defined CSR\n");
        exit(1);
    }
    if (reenroll & csr_file[0]) {
        printf("\nError: The -y option (predefined CSRs) does not make sense for re-enrollment\n");
        exit(1);
    }

    if (verbose) {
        print_version();
        printf("\nUsing EST server %s:%d", est_server, est_port);
        if (csr_file        [0]) {
            printf("\nUsing CSR file %s", csr_file);
        }
        if (priv_key_file   [0]) {
            printf("\nUsing identity private key file %s", priv_key_file);
        }
        if (client_cert_file[0]) {
            printf("\nUsing identity client cert file %s", client_cert_file);
        }
        if (client_key_file [0]) {
            printf("\nUsing identity private key file %s", client_key_file);
        }
    }

    if (enroll && reenroll) {
        printf("\nThe enroll and reenroll operations can not be used together\n");
        exit(1);
    }

    if (!out_dir[0]) {
        printf("\nOutput directory must be specified with -o option\n");
        exit(1);
    }

    if (trustanchor) {
        if (!trustanchor_file) {
            /*
             * Get the trust anchor filename from the environment var
             */
            if (!getenv("EST_OPENSSL_CACERT")) {
                printf("\nCACERT file not set, set EST_OPENSSL_CACERT to resolve");
                exit(1);
            }
            trustanchor_file = getenv("EST_OPENSSL_CACERT");
        }

        /*
         * Read in the CA certificates
         */
        cacerts_len = read_binary_file(trustanchor_file, &cacerts);
        if (cacerts_len <= 0) {
            printf("\nCACERT file could not be read\n");
            exit(1);
        }
    }

    /*
     * Read in the current client certificate
     */
    if (client_cert_file[0]) {
        certin = BIO_new(BIO_s_file_internal());
        if (BIO_read_filename(certin, client_cert_file) <= 0) {
            printf("\nUnable to read client certificate file %s\n", client_cert_file);
            exit(1);
        }
        /*
         * This reads the file, which is expected to be PEM encoded.  If you're using
         * DER encoded certs, you would invoke d2i_X509_bio() instead.
         */
        client_cert = PEM_read_bio_X509(certin, NULL, NULL, NULL);
        if (client_cert == NULL) {
            printf("\nError while reading PEM encoded client certificate file %s\n", client_cert_file);
            exit(1);
        }
        BIO_free(certin);
    }

    /*
     * Read in the client's private key
     */
    if (client_key_file[0]) {
        keyin = BIO_new(BIO_s_file_internal());
        if (BIO_read_filename(keyin, client_key_file) <= 0) {
            printf("\nUnable to read client private key file %s\n", client_key_file);
            exit(1);
        }
        /*
         * This reads in the private key file, which is expected to be a PEM
         * encoded private key.  If using DER encoding, you would invoke
         * d2i_PrivateKey_bio() instead.
         */
        client_priv_key = PEM_read_bio_PrivateKey(keyin, NULL, NULL, NULL);
        if (client_priv_key == NULL) {
            printf("\nError while reading PEM encoded private key file %s\n", client_key_file);
            ERR_print_errors_fp(stderr);
            exit(1);
        }
        BIO_free(keyin);
    }

    est_apps_startup();

#if DEBUG_OSSL_LEAKS
    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
#endif

    if (verbose) {
        est_init_logger(EST_LOG_LVL_INFO, &test_logger_stdout);
        est_enable_backtrace(1);
    } else {
        est_init_logger(EST_LOG_LVL_ERR, &test_logger_stdout);
    }

    if (!priv_key_file[0] && enroll && !csr_file[0]) {
	printf("\nA private key is required for enrolling.  Creating a new RSA key pair since you didn't provide a key using the -x option.");
        /*
         * Create a private key that will be used for the
         * enroll operation.
         */
        new_pkey = generate_private_key(&new_pkey_len);
        snprintf(file_name, MAX_FILENAME_LEN, "%s/newkey.pem", out_dir);
        write_binary_file(file_name, new_pkey, new_pkey_len);
        free(new_pkey);

        /*
         * prepare to read it back in to an EVP_PKEY struct
         */
        strncpy(priv_key_file, file_name, MAX_FILENAME_LEN);

    }

    if (enroll && !csr_file[0]) {
	/* Read in the private key file */
	priv_key = read_private_key(priv_key_file);
    }


    do_operation();

    if (priv_key) {
        EVP_PKEY_free(priv_key);
    }
    if (client_priv_key) {
        EVP_PKEY_free(client_priv_key);
    }
    if (client_cert) {
        X509_free(client_cert);
    }

    free(cacerts);
    if (c_cert_len) {
        free(c_cert);
    }
    if (c_key_len) {
        free(c_key);
    }

    est_apps_shutdown();

#if DEBUG_OSSL_LEAKS
    BIO *bio_err;
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
    CRYPTO_mem_leaks(bio_err);
    BIO_free(bio_err);
#endif

    printf("\n");
    return 0;
}
Beispiel #20
0
int openssl_main(int Argc, char *Argv[])
#endif
	{
	ARGS arg;
#define PROG_NAME_SIZE	39
	char pname[PROG_NAME_SIZE+1];
	FUNCTION f,*fp;
	MS_STATIC const char *prompt;
	MS_STATIC char buf[1024];
	char *to_free=NULL;
	int n,i,ret=0;
	int argc;
	char **argv,*p;
	LHASH *prog=NULL;
	long errline;

	arg.data=NULL;
	arg.count=0;

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
#ifdef SYMBIAN
        BIO_set_fp(bio_err,fp_stderr,BIO_NOCLOSE|BIO_FP_TEXT);
#else
        BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
#endif
	if (getenv("OPENSSL_DEBUG_MEMORY") != NULL) /* if not defined, use compiled-in library defaults */
		{
		if (!(0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))
			{
			CRYPTO_malloc_debug_init();
			CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
			}
		else
			{
			/* OPENSSL_DEBUG_MEMORY=off */
			CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
			}
		}
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

#if 0
	if (getenv("OPENSSL_DEBUG_LOCKING") != NULL)
#endif
		{
		CRYPTO_set_locking_callback(lock_dbg_cb);
		}

	apps_startup();

	/* Lets load up our environment a little */
	p=getenv("OPENSSL_CONF");
	if (p == NULL)
		p=getenv("SSLEAY_CONF");
	if (p == NULL)
		p=to_free=make_config_name();

	default_config_file=p;

	config=NCONF_new(NULL);
	i=NCONF_load(config,p,&errline);
	if (i == 0)
		{
		NCONF_free(config);
		config = NULL;
		ERR_clear_error();
		}

	prog=prog_init();

	/* first check the program name */
	program_name(Argv[0],pname,sizeof pname);

	f.name=pname;
	fp=(FUNCTION *)lh_retrieve(prog,&f);
	if (fp != NULL)
		{
		Argv[0]=pname;
		ret=fp->func(Argc,Argv);
		goto end;
		}

	/* ok, now check that there are not arguments, if there are,
	 * run with them, shifting the ssleay off the front */
	if (Argc != 1)
		{
		Argc--;
		Argv++;
		ret=do_cmd(prog,Argc,Argv);
		if (ret < 0) ret=0;
		goto end;
		}

	/* ok, lets enter the old 'OpenSSL>' mode */

	for (;;)
		{
		ret=0;
		p=buf;
		n=sizeof buf;
		i=0;
		for (;;)
			{
			p[0]='\0';
			if (i++)
				prompt=">";
			else	prompt="OpenSSL> ";
#ifndef SYMBIAN
			fputs(prompt,stdout);
			fflush(stdout);
			fgets(p,n,stdin);
#else
            fputs(prompt,stdout);
			fflush(stdout);
			fgets(p,n,stdin);

#endif
			if (p[0] == '\0') goto end;
			i=strlen(p);
			if (i <= 1) break;
			if (p[i-2] != '\\') break;
			i-=2;
			p+=i;
			n-=i;
			}
		if (!chopup_args(&arg,buf,&argc,&argv)) break;

		ret=do_cmd(prog,argc,argv);
		if (ret < 0)
			{
			ret=0;
			goto end;
			}
		if (ret != 0)
			BIO_printf(bio_err,"error in %s\n",argv[0]);
		(void)BIO_flush(bio_err);
		}
	BIO_printf(bio_err,"bad exit\n");
	ret=1;
end:
	if (to_free)
		OPENSSL_free(to_free);
	if (config != NULL)
		{
		NCONF_free(config);
		config=NULL;
		}
	if (prog != NULL) lh_free(prog);
	if (arg.data != NULL) OPENSSL_free(arg.data);

	apps_shutdown();

	CRYPTO_mem_leaks(bio_err);
	if (bio_err != NULL)
		{
		BIO_free(bio_err);
		bio_err=NULL;
		}

	return ret;
//	OPENSSL_EXIT(ret);
	}
int main(int Argc, char *Argv[])
	{
	ARGS arg;
#define PROG_NAME_SIZE	39
	char pname[PROG_NAME_SIZE+1];
	FUNCTION f,*fp;
	MS_STATIC const char *prompt;
	MS_STATIC char buf[1024];
	char *to_free=NULL;
	int n,i,ret=0;
	int argc;
	char **argv,*p;
	LHASH_OF(FUNCTION) *prog=NULL;
	long errline;
 
	arg.data=NULL;
	arg.count=0;

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE|BIO_FP_TEXT);

	if (TINYCLR_SSL_GETENV("OPENSSL_DEBUG_MEMORY") != NULL) /* if not defined, use compiled-in library defaults */
		{
		if (!(0 == TINYCLR_SSL_STRCMP(TINYCLR_SSL_GETENV("OPENSSL_DEBUG_MEMORY"), "off")))
			{
			CRYPTO_malloc_debug_init();
			CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
			}
		else
			{
			/* OPENSSL_DEBUG_MEMORY=off */
			CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
			}
		}
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

#if 0
	if (TINYCLR_SSL_GETENV("OPENSSL_DEBUG_LOCKING") != NULL)
#endif
		{
		CRYPTO_set_locking_callback(lock_dbg_cb);
		}

	apps_startup();

	/* Lets load up our environment a little */
	p=TINYCLR_SSL_GETENV("OPENSSL_CONF");
	if (p == NULL)
		p=TINYCLR_SSL_GETENV("SSLEAY_CONF");
	if (p == NULL)
		p=to_free=make_config_name();

	default_config_file=p;

	config=NCONF_new(NULL);
	i=NCONF_load(config,p,&errline);
	if (i == 0)
		{
		if (ERR_GET_REASON(ERR_peek_last_error())
		    == CONF_R_NO_SUCH_FILE)
			{
			BIO_printf(bio_err,
				   "WARNING: can't open config file: %s\n",p);
			ERR_clear_error();
			NCONF_free(config);
			config = NULL;
			}
		else
			{
			ERR_print_errors(bio_err);
			NCONF_free(config);
			TINYCLR_SSL_EXIT(1);
			}
		}

	prog=prog_init();

	/* first check the program name */
	program_name(Argv[0],pname,sizeof pname);

	f.name=pname;
	fp=lh_FUNCTION_retrieve(prog,&f);
	if (fp != NULL)
		{
		Argv[0]=pname;
		ret=fp->func(Argc,Argv);
		goto end;
		}

	/* ok, now check that there are not arguments, if there are,
	 * run with them, shifting the ssleay off the front */
	if (Argc != 1)
		{
		Argc--;
		Argv++;
		ret=do_cmd(prog,Argc,Argv);
		if (ret < 0) ret=0;
		goto end;
		}

	/* ok, lets enter the old 'OpenSSL>' mode */
	
	for (;;)
		{
		ret=0;
		p=buf;
		n=sizeof buf;
		i=0;
		for (;;)
			{
			p[0]='\0';
			if (i++)
				prompt=">";
			else	prompt="OpenSSL> ";
			TINYCLR_SSL_FPUTS(prompt,OPENSSL_TYPE__FILE_STDOUT);
			TINYCLR_SSL_FFLUSH(OPENSSL_TYPE__FILE_STDOUT);
			if (!TINYCLR_SSL_FGETS(p,n,OPENSSL_TYPE__FILE_STDIN))
				goto end;
			if (p[0] == '\0') goto end;
			i=TINYCLR_SSL_STRLEN(p);
			if (i <= 1) break;
			if (p[i-2] != '\\') break;
			i-=2;
			p+=i;
			n-=i;
			}
		if (!chopup_args(&arg,buf,&argc,&argv)) break;

		ret=do_cmd(prog,argc,argv);
		if (ret < 0)
			{
			ret=0;
			goto end;
			}
		if (ret != 0)
			BIO_printf(bio_err,"error in %s\n",argv[0]);
		(void)BIO_flush(bio_err);
		}
	BIO_printf(bio_err,"bad exit\n");
	ret=1;
end:
	if (to_free)
		OPENSSL_free(to_free);
	if (config != NULL)
		{
		NCONF_free(config);
		config=NULL;
		}
	if (prog != NULL) lh_FUNCTION_free(prog);
	if (arg.data != NULL) OPENSSL_free(arg.data);

	apps_shutdown();

	CRYPTO_mem_leaks(bio_err);
	if (bio_err != NULL)
		{
		BIO_free(bio_err);
		bio_err=NULL;
		}
	OPENSSL_EXIT(ret);
	}
Beispiel #22
0
int main(int argc, char *argv[])
{
    FUNCTION f, *fp;
    LHASH_OF(FUNCTION) *prog = NULL;
    char **copied_argv = NULL;
    char *p, *pname;
    char buf[1024];
    const char *prompt;
    ARGS arg;
    int first, n, i, ret = 0;

    arg.argv = NULL;
    arg.size = 0;

    /* Set up some of the environment. */
    default_config_file = make_config_name();
    bio_in = dup_bio_in(FORMAT_TEXT);
    bio_out = dup_bio_out(FORMAT_TEXT);
    bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);

#if defined( OPENSSL_SYS_VMS)
    copied_argv = argv = copy_argv(&argc, argv);
#endif

    p = getenv("OPENSSL_DEBUG_MEMORY");
    if (p == NULL)
        /* if not set, use compiled-in default */
        ;
    else if (strcmp(p, "off") != 0) {
        CRYPTO_malloc_debug_init();
        CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    } else {
        CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
    }
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
    CRYPTO_set_locking_callback(lock_dbg_cb);

    if (getenv("OPENSSL_FIPS")) {
#ifdef OPENSSL_FIPS
        if (!FIPS_mode_set(1)) {
            ERR_load_crypto_strings();
            ERR_print_errors(bio_err);
            return 1;
        }
#else
        BIO_printf(bio_err, "FIPS mode not supported.\n");
        return 1;
#endif
    }

    if (!apps_startup())
        goto end;

    prog = prog_init();
    pname = opt_progname(argv[0]);

    /* first check the program name */
    f.name = pname;
    fp = lh_FUNCTION_retrieve(prog, &f);
    if (fp != NULL) {
        argv[0] = pname;
        ret = fp->func(argc, argv);
        goto end;
    }

    /* If there is stuff on the command line, run with that. */
    if (argc != 1) {
        argc--;
        argv++;
        ret = do_cmd(prog, argc, argv);
        if (ret < 0)
            ret = 0;
        goto end;
    }

    /* ok, lets enter interactive mode */
    for (;;) {
        ret = 0;
        /* Read a line, continue reading if line ends with \ */
        for (p = buf, n = sizeof buf, i = 0, first = 1; n > 0; first = 0) {
            prompt = first ? "OpenSSL> " : "> ";
            p[0] = '\0';
#ifndef READLINE
            fputs(prompt, stdout);
            fflush(stdout);
            if (!fgets(p, n, stdin))
                goto end;
            if (p[0] == '\0')
                goto end;
            i = strlen(p);
            if (i <= 1)
                break;
            if (p[i - 2] != '\\')
                break;
            i -= 2;
            p += i;
            n -= i;
#else
            {
                extern char *readline(const char *);
                extern void add_history(const char *cp);
                char *text;

                char *text = readline(prompt);
                if (text == NULL)
                    goto end;
                i = strlen(text);
                if (i == 0 || i > n)
                    break;
                if (text[i - 1] != '\\') {
                    p += strlen(strcpy(p, text));
                    free(text);
                    add_history(buf);
                    break;
                }

                text[i - 1] = '\0';
                p += strlen(strcpy(p, text));
                free(text);
                n -= i;
            }
#endif
        }

        if (!chopup_args(&arg, buf)) {
            BIO_printf(bio_err, "Can't parse (no memory?)\n");
            break;
        }

        ret = do_cmd(prog, arg.argc, arg.argv);
        if (ret == EXIT_THE_PROGRAM) {
            ret = 0;
            goto end;
        }
        if (ret != 0)
            BIO_printf(bio_err, "error in %s\n", arg.argv[0]);
        (void)BIO_flush(bio_out);
        (void)BIO_flush(bio_err);
    }
    ret = 1;
 end:
    OPENSSL_free(copied_argv);
    OPENSSL_free(default_config_file);
    NCONF_free(config);
    config = NULL;
    lh_FUNCTION_free(prog);
    OPENSSL_free(arg.argv);

    BIO_free(bio_in);
    BIO_free_all(bio_out);
    apps_shutdown();
    CRYPTO_mem_leaks(bio_err);
    BIO_free(bio_err);
    return (ret);
}
Beispiel #23
0
int main(int Argc, char *ARGV[])
{
    ARGS arg;
#define PROG_NAME_SIZE	39
    char pname[PROG_NAME_SIZE+1];
    FUNCTION f,*fp;
    MS_STATIC const char *prompt;
    MS_STATIC char buf[1024];
    char *to_free=NULL;
    int n,i,ret=0;
    int argc;
    char **argv,*p;
    LHASH_OF(FUNCTION) *prog=NULL;
    long errline;

#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
    /* 2011-03-22 SMS.
     * If we have 32-bit pointers everywhere, then we're safe, and
     * we bypass this mess, as on non-VMS systems.  (See ARGV,
     * above.)
     * Problem 1: Compaq/HP C before V7.3 always used 32-bit
     * pointers for argv[].
     * Fix 1: For a 32-bit argv[], when we're using 64-bit pointers
     * everywhere else, we always allocate and use a 64-bit
     * duplicate of argv[].
     * Problem 2: Compaq/HP C V7.3 (Alpha, IA64) before ECO1 failed
     * to NULL-terminate a 64-bit argv[].  (As this was written, the
     * compiler ECO was available only on IA64.)
     * Fix 2: Unless advised not to (VMS_TRUST_ARGV), we test a
     * 64-bit argv[argc] for NULL, and, if necessary, use a
     * (properly) NULL-terminated (64-bit) duplicate of argv[].
     * The same code is used in either case to duplicate argv[].
     * Some of these decisions could be handled in preprocessing,
     * but the code tends to get even uglier, and the penalty for
     * deciding at compile- or run-time is tiny.
     */
    char **Argv = NULL;
    int free_Argv = 0;

    if ((sizeof( _Argv) < 8)        /* 32-bit argv[]. */
# if !defined( VMS_TRUST_ARGV)
            || (_Argv[ Argc] != NULL)      /* Untrusted argv[argc] not NULL. */
# endif
       )
    {
        int i;
        Argv = OPENSSL_malloc( (Argc+ 1)* sizeof( char *));
        if (Argv == NULL)
        {
            ret = -1;
            goto end;
        }
        for(i = 0; i < Argc; i++)
            Argv[i] = _Argv[i];
        Argv[ Argc] = NULL;     /* Certain NULL termination. */
        free_Argv = 1;
    }
    else
    {
        /* Use the known-good 32-bit argv[] (which needs the
         * type cast to satisfy the compiler), or the trusted or
         * tested-good 64-bit argv[] as-is. */
        Argv = (char **)_Argv;
    }
#endif /* defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64) */

    arg.data=NULL;
    arg.count=0;

    if (bio_err == NULL)
        if ((bio_err=BIO_new(BIO_s_file())) != NULL)
            BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

    if (getenv("OPENSSL_DEBUG_MEMORY") != NULL) /* if not defined, use compiled-in library defaults */
    {
        if (!(0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off")))
        {
            CRYPTO_malloc_debug_init();
            CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
        }
        else
        {
            /* OPENSSL_DEBUG_MEMORY=off */
            CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
        }
    }
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

#if 0
    if (getenv("OPENSSL_DEBUG_LOCKING") != NULL)
#endif
    {
        CRYPTO_set_locking_callback(lock_dbg_cb);
    }

    apps_startup();

    /* Lets load up our environment a little */
    p=getenv("OPENSSL_CONF");
    if (p == NULL)
        p=getenv("SSLEAY_CONF");
    if (p == NULL)
        p=to_free=make_config_name();

    default_config_file=p;

    config=NCONF_new(NULL);
    i=NCONF_load(config,p,&errline);
    if (i == 0)
    {
        if (ERR_GET_REASON(ERR_peek_last_error())
                == CONF_R_NO_SUCH_FILE)
        {
            BIO_printf(bio_err,
                       "WARNING: can't open config file: %s\n",p);
            ERR_clear_error();
            NCONF_free(config);
            config = NULL;
        }
        else
        {
            ERR_print_errors(bio_err);
            NCONF_free(config);
            exit(1);
        }
    }

    prog=prog_init();

    /* first check the program name */
    program_name(Argv[0],pname,sizeof pname);

    f.name=pname;
    fp=lh_FUNCTION_retrieve(prog,&f);
    if (fp != NULL)
    {
        Argv[0]=pname;
        ret=fp->func(Argc,Argv);
        goto end;
    }

    /* ok, now check that there are not arguments, if there are,
     * run with them, shifting the ssleay off the front */
    if (Argc != 1)
    {
        Argc--;
        Argv++;
        ret=do_cmd(prog,Argc,Argv);
        if (ret < 0) ret=0;
        goto end;
    }

    /* ok, lets enter the old 'OpenSSL>' mode */

    for (;;)
    {
        ret=0;
        p=buf;
        n=sizeof buf;
        i=0;
        for (;;)
        {
            p[0]='\0';
            if (i++)
                prompt=">";
            else	prompt="OpenSSL> ";
            fputs(prompt,stdout);
            fflush(stdout);
            if (!fgets(p,n,stdin))
                goto end;
            if (p[0] == '\0') goto end;
            i=strlen(p);
            if (i <= 1) break;
            if (p[i-2] != '\\') break;
            i-=2;
            p+=i;
            n-=i;
        }
        if (!chopup_args(&arg,buf,&argc,&argv)) break;

        ret=do_cmd(prog,argc,argv);
        if (ret < 0)
        {
            ret=0;
            goto end;
        }
        if (ret != 0)
            BIO_printf(bio_err,"error in %s\n",argv[0]);
        (void)BIO_flush(bio_err);
    }
    BIO_printf(bio_err,"bad exit\n");
    ret=1;
end:
    if (to_free)
        OPENSSL_free(to_free);
    if (config != NULL)
    {
        NCONF_free(config);
        config=NULL;
    }
    if (prog != NULL) lh_FUNCTION_free(prog);
    if (arg.data != NULL) OPENSSL_free(arg.data);

    apps_shutdown();

    CRYPTO_mem_leaks(bio_err);
    if (bio_err != NULL)
    {
        BIO_free(bio_err);
        bio_err=NULL;
    }
#if defined( OPENSSL_SYS_VMS) && (__INITIAL_POINTER_SIZE == 64)
    /* Free any duplicate Argv[] storage. */
    if (free_Argv)
    {
        OPENSSL_free(Argv);
    }
#endif
    OPENSSL_EXIT(ret);
}
Beispiel #24
0
/*
 * OpenSSL provides SSL, TLS and general purpose cryptography.  It wraps the
 * OpenSSL[https://www.openssl.org/] library.
 *
 * = Examples
 *
 * All examples assume you have loaded OpenSSL with:
 *
 *   require 'openssl'
 *
 * These examples build atop each other.  For example the key created in the
 * next is used in throughout these examples.
 *
 * == Keys
 *
 * === Creating a Key
 *
 * This example creates a 2048 bit RSA keypair and writes it to the current
 * directory.
 *
 *   key = OpenSSL::PKey::RSA.new 2048
 *
 *   open 'private_key.pem', 'w' do |io| io.write key.to_pem end
 *   open 'public_key.pem', 'w' do |io| io.write key.public_key.to_pem end
 *
 * === Exporting a Key
 *
 * Keys saved to disk without encryption are not secure as anyone who gets
 * ahold of the key may use it unless it is encrypted.  In order to securely
 * export a key you may export it with a pass phrase.
 *
 *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
 *   pass_phrase = 'my secure pass phrase goes here'
 *
 *   key_secure = key.export cipher, pass_phrase
 *
 *   open 'private.secure.pem', 'w' do |io|
 *     io.write key_secure
 *   end
 *
 * OpenSSL::Cipher.ciphers returns a list of available ciphers.
 *
 * === Loading a Key
 *
 * A key can also be loaded from a file.
 *
 *   key2 = OpenSSL::PKey::RSA.new File.read 'private_key.pem'
 *   key2.public? # => true
 *   key2.private? # => true
 *
 * or
 *
 *   key3 = OpenSSL::PKey::RSA.new File.read 'public_key.pem'
 *   key3.public? # => true
 *   key3.private? # => false
 *
 * === Loading an Encrypted Key
 *
 * OpenSSL will prompt you for your pass phrase when loading an encrypted key.
 * If you will not be able to type in the pass phrase you may provide it when
 * loading the key:
 *
 *   key4_pem = File.read 'private.secure.pem'
 *   pass_phrase = 'my secure pass phrase goes here'
 *   key4 = OpenSSL::PKey::RSA.new key4_pem, pass_phrase
 *
 * == RSA Encryption
 *
 * RSA provides encryption and decryption using the public and private keys.
 * You can use a variety of padding methods depending upon the intended use of
 * encrypted data.
 *
 * === Encryption & Decryption
 *
 * Asymmetric public/private key encryption is slow and victim to attack in
 * cases where it is used without padding or directly to encrypt larger chunks
 * of data. Typical use cases for RSA encryption involve "wrapping" a symmetric
 * key with the public key of the recipient who would "unwrap" that symmetric
 * key again using their private key.
 * The following illustrates a simplified example of such a key transport
 * scheme. It shouldn't be used in practice, though, standardized protocols
 * should always be preferred.
 *
 *   wrapped_key = key.public_encrypt key
 *
 * A symmetric key encrypted with the public key can only be decrypted with
 * the corresponding private key of the recipient.
 *
 *   original_key = key.private_decrypt wrapped_key
 *
 * By default PKCS#1 padding will be used, but it is also possible to use
 * other forms of padding, see PKey::RSA for further details.
 *
 * === Signatures
 *
 * Using "private_encrypt" to encrypt some data with the private key is
 * equivalent to applying a digital signature to the data. A verifying
 * party may validate the signature by comparing the result of decrypting
 * the signature with "public_decrypt" to the original data. However,
 * OpenSSL::PKey already has methods "sign" and "verify" that handle
 * digital signatures in a standardized way - "private_encrypt" and
 * "public_decrypt" shouldn't be used in practice.
 *
 * To sign a document, a cryptographically secure hash of the document is
 * computed first, which is then signed using the private key.
 *
 *   digest = OpenSSL::Digest::SHA256.new
 *   signature = key.sign digest, document
 *
 * To validate the signature, again a hash of the document is computed and
 * the signature is decrypted using the public key. The result is then
 * compared to the hash just computed, if they are equal the signature was
 * valid.
 *
 *   digest = OpenSSL::Digest::SHA256.new
 *   if key.verify digest, signature, document
 *     puts 'Valid'
 *   else
 *     puts 'Invalid'
 *   end
 *
 * == PBKDF2 Password-based Encryption
 *
 * If supported by the underlying OpenSSL version used, Password-based
 * Encryption should use the features of PKCS5. If not supported or if
 * required by legacy applications, the older, less secure methods specified
 * in RFC 2898 are also supported (see below).
 *
 * PKCS5 supports PBKDF2 as it was specified in PKCS#5
 * v2.0[http://www.rsa.com/rsalabs/node.asp?id=2127]. It still uses a
 * password, a salt, and additionally a number of iterations that will
 * slow the key derivation process down. The slower this is, the more work
 * it requires being able to brute-force the resulting key.
 *
 * === Encryption
 *
 * The strategy is to first instantiate a Cipher for encryption, and
 * then to generate a random IV plus a key derived from the password
 * using PBKDF2. PKCS #5 v2.0 recommends at least 8 bytes for the salt,
 * the number of iterations largely depends on the hardware being used.
 *
 *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
 *   cipher.encrypt
 *   iv = cipher.random_iv
 *
 *   pwd = 'some hopefully not to easily guessable password'
 *   salt = OpenSSL::Random.random_bytes 16
 *   iter = 20000
 *   key_len = cipher.key_len
 *   digest = OpenSSL::Digest::SHA256.new
 *
 *   key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
 *   cipher.key = key
 *
 *   Now encrypt the data:
 *
 *   encrypted = cipher.update document
 *   encrypted << cipher.final
 *
 * === Decryption
 *
 * Use the same steps as before to derive the symmetric AES key, this time
 * setting the Cipher up for decryption.
 *
 *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
 *   cipher.decrypt
 *   cipher.iv = iv # the one generated with #random_iv
 *
 *   pwd = 'some hopefully not to easily guessable password'
 *   salt = ... # the one generated above
 *   iter = 20000
 *   key_len = cipher.key_len
 *   digest = OpenSSL::Digest::SHA256.new
 *
 *   key = OpenSSL::PKCS5.pbkdf2_hmac(pwd, salt, iter, key_len, digest)
 *   cipher.key = key
 *
 *   Now decrypt the data:
 *
 *   decrypted = cipher.update encrypted
 *   decrypted << cipher.final
 *
 * == PKCS #5 Password-based Encryption
 *
 * PKCS #5 is a password-based encryption standard documented at
 * RFC2898[http://www.ietf.org/rfc/rfc2898.txt].  It allows a short password or
 * passphrase to be used to create a secure encryption key. If possible, PBKDF2
 * as described above should be used if the circumstances allow it.
 *
 * PKCS #5 uses a Cipher, a pass phrase and a salt to generate an encryption
 * key.
 *
 *   pass_phrase = 'my secure pass phrase goes here'
 *   salt = '8 octets'
 *
 * === Encryption
 *
 * First set up the cipher for encryption
 *
 *   encryptor = OpenSSL::Cipher.new 'AES-128-CBC'
 *   encryptor.encrypt
 *   encryptor.pkcs5_keyivgen pass_phrase, salt
 *
 * Then pass the data you want to encrypt through
 *
 *   encrypted = encryptor.update 'top secret document'
 *   encrypted << encryptor.final
 *
 * === Decryption
 *
 * Use a new Cipher instance set up for decryption
 *
 *   decryptor = OpenSSL::Cipher.new 'AES-128-CBC'
 *   decryptor.decrypt
 *   decryptor.pkcs5_keyivgen pass_phrase, salt
 *
 * Then pass the data you want to decrypt through
 *
 *   plain = decryptor.update encrypted
 *   plain << decryptor.final
 *
 * == X509 Certificates
 *
 * === Creating a Certificate
 *
 * This example creates a self-signed certificate using an RSA key and a SHA1
 * signature.
 *
 *   key = OpenSSL::PKey::RSA.new 2048
 *   name = OpenSSL::X509::Name.parse 'CN=nobody/DC=example'
 *
 *   cert = OpenSSL::X509::Certificate.new
 *   cert.version = 2
 *   cert.serial = 0
 *   cert.not_before = Time.now
 *   cert.not_after = Time.now + 3600
 *
 *   cert.public_key = key.public_key
 *   cert.subject = name
 *
 * === Certificate Extensions
 *
 * You can add extensions to the certificate with
 * OpenSSL::SSL::ExtensionFactory to indicate the purpose of the certificate.
 *
 *   extension_factory = OpenSSL::X509::ExtensionFactory.new nil, cert
 *
 *   cert.add_extension \
 *     extension_factory.create_extension('basicConstraints', 'CA:FALSE', true)
 *
 *   cert.add_extension \
 *     extension_factory.create_extension(
 *       'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
 *
 *   cert.add_extension \
 *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
 *
 * The list of supported extensions (and in some cases their possible values)
 * can be derived from the "objects.h" file in the OpenSSL source code.
 *
 * === Signing a Certificate
 *
 * To sign a certificate set the issuer and use OpenSSL::X509::Certificate#sign
 * with a digest algorithm.  This creates a self-signed cert because we're using
 * the same name and key to sign the certificate as was used to create the
 * certificate.
 *
 *   cert.issuer = name
 *   cert.sign key, OpenSSL::Digest::SHA1.new
 *
 *   open 'certificate.pem', 'w' do |io| io.write cert.to_pem end
 *
 * === Loading a Certificate
 *
 * Like a key, a cert can also be loaded from a file.
 *
 *   cert2 = OpenSSL::X509::Certificate.new File.read 'certificate.pem'
 *
 * === Verifying a Certificate
 *
 * Certificate#verify will return true when a certificate was signed with the
 * given public key.
 *
 *   raise 'certificate can not be verified' unless cert2.verify key
 *
 * == Certificate Authority
 *
 * A certificate authority (CA) is a trusted third party that allows you to
 * verify the ownership of unknown certificates.  The CA issues key signatures
 * that indicate it trusts the user of that key.  A user encountering the key
 * can verify the signature by using the CA's public key.
 *
 * === CA Key
 *
 * CA keys are valuable, so we encrypt and save it to disk and make sure it is
 * not readable by other users.
 *
 *   ca_key = OpenSSL::PKey::RSA.new 2048
 *   pass_phrase = 'my secure pass phrase goes here'
 *
 *   cipher = OpenSSL::Cipher.new 'AES-128-CBC'
 *
 *   open 'ca_key.pem', 'w', 0400 do |io|
 *     io.write ca_key.export(cipher, pass_phrase)
 *   end
 *
 * === CA Certificate
 *
 * A CA certificate is created the same way we created a certificate above, but
 * with different extensions.
 *
 *   ca_name = OpenSSL::X509::Name.parse 'CN=ca/DC=example'
 *
 *   ca_cert = OpenSSL::X509::Certificate.new
 *   ca_cert.serial = 0
 *   ca_cert.version = 2
 *   ca_cert.not_before = Time.now
 *   ca_cert.not_after = Time.now + 86400
 *
 *   ca_cert.public_key = ca_key.public_key
 *   ca_cert.subject = ca_name
 *   ca_cert.issuer = ca_name
 *
 *   extension_factory = OpenSSL::X509::ExtensionFactory.new
 *   extension_factory.subject_certificate = ca_cert
 *   extension_factory.issuer_certificate = ca_cert
 *
 *   ca_cert.add_extension \
 *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
 *
 * This extension indicates the CA's key may be used as a CA.
 *
 *   ca_cert.add_extension \
 *     extension_factory.create_extension('basicConstraints', 'CA:TRUE', true)
 *
 * This extension indicates the CA's key may be used to verify signatures on
 * both certificates and certificate revocations.
 *
 *   ca_cert.add_extension \
 *     extension_factory.create_extension(
 *       'keyUsage', 'cRLSign,keyCertSign', true)
 *
 * Root CA certificates are self-signed.
 *
 *   ca_cert.sign ca_key, OpenSSL::Digest::SHA1.new
 *
 * The CA certificate is saved to disk so it may be distributed to all the
 * users of the keys this CA will sign.
 *
 *   open 'ca_cert.pem', 'w' do |io|
 *     io.write ca_cert.to_pem
 *   end
 *
 * === Certificate Signing Request
 *
 * The CA signs keys through a Certificate Signing Request (CSR).  The CSR
 * contains the information necessary to identify the key.
 *
 *   csr = OpenSSL::X509::Request.new
 *   csr.version = 0
 *   csr.subject = name
 *   csr.public_key = key.public_key
 *   csr.sign key, OpenSSL::Digest::SHA1.new
 *
 * A CSR is saved to disk and sent to the CA for signing.
 *
 *   open 'csr.pem', 'w' do |io|
 *     io.write csr.to_pem
 *   end
 *
 * === Creating a Certificate from a CSR
 *
 * Upon receiving a CSR the CA will verify it before signing it.  A minimal
 * verification would be to check the CSR's signature.
 *
 *   csr = OpenSSL::X509::Request.new File.read 'csr.pem'
 *
 *   raise 'CSR can not be verified' unless csr.verify csr.public_key
 *
 * After verification a certificate is created, marked for various usages,
 * signed with the CA key and returned to the requester.
 *
 *   csr_cert = OpenSSL::X509::Certificate.new
 *   csr_cert.serial = 0
 *   csr_cert.version = 2
 *   csr_cert.not_before = Time.now
 *   csr_cert.not_after = Time.now + 600
 *
 *   csr_cert.subject = csr.subject
 *   csr_cert.public_key = csr.public_key
 *   csr_cert.issuer = ca_cert.subject
 *
 *   extension_factory = OpenSSL::X509::ExtensionFactory.new
 *   extension_factory.subject_certificate = csr_cert
 *   extension_factory.issuer_certificate = ca_cert
 *
 *   csr_cert.add_extension \
 *     extension_factory.create_extension('basicConstraints', 'CA:FALSE')
 *
 *   csr_cert.add_extension \
 *     extension_factory.create_extension(
 *       'keyUsage', 'keyEncipherment,dataEncipherment,digitalSignature')
 *
 *   csr_cert.add_extension \
 *     extension_factory.create_extension('subjectKeyIdentifier', 'hash')
 *
 *   csr_cert.sign ca_key, OpenSSL::Digest::SHA1.new
 *
 *   open 'csr_cert.pem', 'w' do |io|
 *     io.write csr_cert.to_pem
 *   end
 *
 * == SSL and TLS Connections
 *
 * Using our created key and certificate we can create an SSL or TLS connection.
 * An SSLContext is used to set up an SSL session.
 *
 *   context = OpenSSL::SSL::SSLContext.new
 *
 * === SSL Server
 *
 * An SSL server requires the certificate and private key to communicate
 * securely with its clients:
 *
 *   context.cert = cert
 *   context.key = key
 *
 * Then create an SSLServer with a TCP server socket and the context.  Use the
 * SSLServer like an ordinary TCP server.
 *
 *   require 'socket'
 *
 *   tcp_server = TCPServer.new 5000
 *   ssl_server = OpenSSL::SSL::SSLServer.new tcp_server, context
 *
 *   loop do
 *     ssl_connection = ssl_server.accept
 *
 *     data = connection.gets
 *
 *     response = "I got #{data.dump}"
 *     puts response
 *
 *     connection.puts "I got #{data.dump}"
 *     connection.close
 *   end
 *
 * === SSL client
 *
 * An SSL client is created with a TCP socket and the context.
 * SSLSocket#connect must be called to initiate the SSL handshake and start
 * encryption.  A key and certificate are not required for the client socket.
 *
 * Note that SSLSocket#close doesn't close the underlying socket by default. Set
 * SSLSocket#sync_close to true if you want.
 *
 *   require 'socket'
 *
 *   tcp_socket = TCPSocket.new 'localhost', 5000
 *   ssl_client = OpenSSL::SSL::SSLSocket.new tcp_socket, context
 *   ssl_client.sync_close = true
 *   ssl_client.connect
 *
 *   ssl_client.puts "hello server!"
 *   puts ssl_client.gets
 *
 *   ssl_client.close # shutdown the TLS connection and close tcp_socket
 *
 * === Peer Verification
 *
 * An unverified SSL connection does not provide much security.  For enhanced
 * security the client or server can verify the certificate of its peer.
 *
 * The client can be modified to verify the server's certificate against the
 * certificate authority's certificate:
 *
 *   context.ca_file = 'ca_cert.pem'
 *   context.verify_mode = OpenSSL::SSL::VERIFY_PEER
 *
 *   require 'socket'
 *
 *   tcp_socket = TCPSocket.new 'localhost', 5000
 *   ssl_client = OpenSSL::SSL::SSLSocket.new tcp_socket, context
 *   ssl_client.connect
 *
 *   ssl_client.puts "hello server!"
 *   puts ssl_client.gets
 *
 * If the server certificate is invalid or <tt>context.ca_file</tt> is not set
 * when verifying peers an OpenSSL::SSL::SSLError will be raised.
 *
 */
void
Init_openssl(void)
{
    /*
     * Init timezone info
     */
#if 0
    tzset();
#endif

    /*
     * Init all digests, ciphers
     */
#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000
    if (!OPENSSL_init_ssl(0, NULL))
        rb_raise(rb_eRuntimeError, "OPENSSL_init_ssl");
#else
    OpenSSL_add_ssl_algorithms();
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();
    SSL_load_error_strings();
#endif

    /*
     * Init main module
     */
    mOSSL = rb_define_module("OpenSSL");
    rb_global_variable(&mOSSL);

    /*
     * OpenSSL ruby extension version
     */
    rb_define_const(mOSSL, "VERSION", rb_str_new2(OSSL_VERSION));

    /*
     * Version of OpenSSL the ruby OpenSSL extension was built with
     */
    rb_define_const(mOSSL, "OPENSSL_VERSION", rb_str_new2(OPENSSL_VERSION_TEXT));

    /*
     * Version of OpenSSL the ruby OpenSSL extension is running with
     */
#if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000
    rb_define_const(mOSSL, "OPENSSL_LIBRARY_VERSION", rb_str_new2(OpenSSL_version(OPENSSL_VERSION)));
#else
    rb_define_const(mOSSL, "OPENSSL_LIBRARY_VERSION", rb_str_new2(SSLeay_version(SSLEAY_VERSION)));
#endif

    /*
     * Version number of OpenSSL the ruby OpenSSL extension was built with
     * (base 16)
     */
    rb_define_const(mOSSL, "OPENSSL_VERSION_NUMBER", INT2NUM(OPENSSL_VERSION_NUMBER));

    /*
     * Boolean indicating whether OpenSSL is FIPS-capable or not
     */
    rb_define_const(mOSSL, "OPENSSL_FIPS",
#ifdef OPENSSL_FIPS
		    Qtrue
#else
		    Qfalse
#endif
		   );

    rb_define_module_function(mOSSL, "fips_mode", ossl_fips_mode_get, 0);
    rb_define_module_function(mOSSL, "fips_mode=", ossl_fips_mode_set, 1);

    /*
     * Generic error,
     * common for all classes under OpenSSL module
     */
    eOSSLError = rb_define_class_under(mOSSL,"OpenSSLError",rb_eStandardError);
    rb_global_variable(&eOSSLError);

    /*
     * Init debug core
     */
    dOSSL = Qfalse;
    rb_global_variable(&dOSSL);

    rb_define_module_function(mOSSL, "debug", ossl_debug_get, 0);
    rb_define_module_function(mOSSL, "debug=", ossl_debug_set, 1);
    rb_define_module_function(mOSSL, "errors", ossl_get_errors, 0);

    /*
     * Get ID of to_der
     */
    ossl_s_to_der = rb_intern("to_der");

#if !defined(HAVE_OPENSSL_110_THREADING_API)
    Init_ossl_locks();
#endif

    /*
     * Init components
     */
    Init_ossl_bn();
    Init_ossl_cipher();
    Init_ossl_config();
    Init_ossl_digest();
    Init_ossl_hmac();
    Init_ossl_ns_spki();
    Init_ossl_pkcs12();
    Init_ossl_pkcs7();
    Init_ossl_pkey();
    Init_ossl_rand();
    Init_ossl_ssl();
    Init_ossl_x509();
    Init_ossl_ocsp();
    Init_ossl_engine();
    Init_ossl_asn1();
    Init_ossl_kdf();

#if defined(OSSL_DEBUG)
    /*
     * For debugging Ruby/OpenSSL. Enable only when built with --enable-debug
     */
#if !defined(LIBRESSL_VERSION_NUMBER) && \
    (OPENSSL_VERSION_NUMBER >= 0x10100000 && !defined(OPENSSL_NO_CRYPTO_MDEBUG) || \
     defined(CRYPTO_malloc_debug_init))
    rb_define_module_function(mOSSL, "mem_check_start", mem_check_start, 0);
    rb_define_module_function(mOSSL, "print_mem_leaks", print_mem_leaks, 0);

#if defined(CRYPTO_malloc_debug_init) /* <= 1.0.2 */
    CRYPTO_malloc_debug_init();
#endif

#if defined(V_CRYPTO_MDEBUG_ALL) /* <= 1.0.2 */
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
#endif

#if OPENSSL_VERSION_NUMBER < 0x10100000 /* <= 1.0.2 */
    {
	int i;
	/*
	 * See crypto/ex_data.c; call def_get_class() immediately to avoid
	 * allocations. 15 is the maximum number that is used as the class index
	 * in OpenSSL 1.0.2.
	 */
	for (i = 0; i <= 15; i++) {
	    if (CRYPTO_get_ex_new_index(i, 0, (void *)"ossl-mdebug-dummy", 0, 0, 0) < 0)
		rb_raise(rb_eRuntimeError, "CRYPTO_get_ex_new_index for "
			 "class index %d failed", i);
	}
    }
#endif
#endif
#endif
}
int ssl_test_dsa(int argc, char **argv)
	{
	BN_GENCB cb;
	DSA *dsa=NULL;
	int counter,ret=0,i,j;
	unsigned char buf[256];
	unsigned long h;
	unsigned char sig[256];
	unsigned int siglen;
#ifndef OPENSSL_SYS_WINDOWS
		bio_err = BIO_new(BIO_s_mem());
		if (bio_err == NULL) return(1);
	
#else
		if (bio_err == NULL)
			bio_err=BIO_new_fp(OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE);
#endif


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

	ERR_load_crypto_strings();
	RAND_seed(rnd_seed, sizeof rnd_seed);

	TINYCLR_SSL_PRINTF("test generation of DSA parameters\n");

	BN_GENCB_set(&cb, dsa_cb, bio_err);
	if(((dsa = DSA_new()) == NULL) || !DSA_generate_parameters_ex(dsa, 512,
				seed, 20, &counter, &h, &cb))
		goto end;

	TINYCLR_SSL_PRINTF("seed\n");
	for (i=0; i<20; i+=4)
		{
		TINYCLR_SSL_PRINTF("%02X%02X%02X%02X ",
			seed[i],seed[i+1],seed[i+2],seed[i+3]);
		}
	TINYCLR_SSL_PRINTF("\ncounter=%d h=%ld\n",counter,h);
		
	DSA_print(bio_err,dsa,0);
	if (counter != 105) 
		{
		TINYCLR_SSL_PRINTF("counter should be 105\n");
		goto end;
		}
	if (h != 2)
		{
		TINYCLR_SSL_PRINTF("h should be 2\n");
		goto end;
		}

	i=BN_bn2bin(dsa->q,buf);
	j=sizeof(out_q);
	if ((i != j) || (TINYCLR_SSL_MEMCMP(buf,out_q,i) != 0))
		{
		TINYCLR_SSL_PRINTF("q value is wrong\n");
		goto end;
		}

	i=BN_bn2bin(dsa->p,buf);
	j=sizeof(out_p);
	if ((i != j) || (TINYCLR_SSL_MEMCMP(buf,out_p,i) != 0))
		{
		TINYCLR_SSL_PRINTF("p value is wrong\n");
		goto end;
		}

	i=BN_bn2bin(dsa->g,buf);
	j=sizeof(out_g);
	if ((i != j) || (TINYCLR_SSL_MEMCMP(buf,out_g,i) != 0))
		{
		TINYCLR_SSL_PRINTF("g value is wrong\n");
		goto end;
		}

	dsa->flags |= DSA_FLAG_NO_EXP_CONSTTIME;
	DSA_generate_key(dsa);
	DSA_sign(0, str1, 20, sig, &siglen, dsa);
	if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
		ret=1;

	dsa->flags &= ~DSA_FLAG_NO_EXP_CONSTTIME;
	DSA_generate_key(dsa);
	DSA_sign(0, str1, 20, sig, &siglen, dsa);
	if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1)
		ret=1;

end:
	if (!ret)
		ERR_print_errors(bio_err);
	if (dsa != NULL) DSA_free(dsa);
	CRYPTO_cleanup_all_ex_data();
	ERR_remove_thread_state(NULL);
	ERR_free_strings();
	CRYPTO_mem_leaks(bio_err);
	if (bio_err != NULL)
		{
		BIO_free(bio_err);
		bio_err = NULL;
		}
#ifdef OPENSSL_SYS_NETWARE
    if (!ret) TINYCLR_SSL_PRINTF("ERROR\n");
#endif
	return(0);
	}
int main(int argc, char *argv[])
	{
	ENGINE *block[512];
	char buf[256];
	const char *id, *name;
	ENGINE *ptr;
	int loop;
	int to_return = 1;
	ENGINE *new_h1 = NULL;
	ENGINE *new_h2 = NULL;
	ENGINE *new_h3 = NULL;
	ENGINE *new_h4 = NULL;

	/* enable memory leak checking unless explicitly disabled */
	if (!((getenv("OPENSSL_DEBUG_MEMORY") != NULL) && (0 == strcmp(getenv("OPENSSL_DEBUG_MEMORY"), "off"))))
		{
		CRYPTO_malloc_debug_init();
		CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
		}
	else
		{
		/* OPENSSL_DEBUG_MEMORY=off */
		CRYPTO_set_mem_debug_functions(0, 0, 0, 0, 0);
		}
	CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
	ERR_load_crypto_strings();

	memset(block, 0, 512 * sizeof(ENGINE *));
	if(((new_h1 = ENGINE_new()) == NULL) ||
			!ENGINE_set_id(new_h1, "test_id0") ||
			!ENGINE_set_name(new_h1, "First test item") ||
			((new_h2 = ENGINE_new()) == NULL) ||
			!ENGINE_set_id(new_h2, "test_id1") ||
			!ENGINE_set_name(new_h2, "Second test item") ||
			((new_h3 = ENGINE_new()) == NULL) ||
			!ENGINE_set_id(new_h3, "test_id2") ||
			!ENGINE_set_name(new_h3, "Third test item") ||
			((new_h4 = ENGINE_new()) == NULL) ||
			!ENGINE_set_id(new_h4, "test_id3") ||
			!ENGINE_set_name(new_h4, "Fourth test item"))
		{
		printf("Couldn't set up test ENGINE structures\n");
		goto end;
		}
	printf("\nenginetest beginning\n\n");
	display_engine_list();
	if(!ENGINE_add(new_h1))
		{
		printf("Add failed!\n");
		goto end;
		}
	display_engine_list();
	ptr = ENGINE_get_first();
	if(!ENGINE_remove(ptr))
		{
		printf("Remove failed!\n");
		goto end;
		}
	if (ptr)
		ENGINE_free(ptr);
	display_engine_list();
	if(!ENGINE_add(new_h3) || !ENGINE_add(new_h2))
		{
		printf("Add failed!\n");
		goto end;
		}
	display_engine_list();
	if(!ENGINE_remove(new_h2))
		{
		printf("Remove failed!\n");
		goto end;
		}
	display_engine_list();
	if(!ENGINE_add(new_h4))
		{
		printf("Add failed!\n");
		goto end;
		}
	display_engine_list();
	if(ENGINE_add(new_h3))
		{
		printf("Add *should* have failed but didn't!\n");
		goto end;
		}
	else
		printf("Add that should fail did.\n");
	ERR_clear_error();
	if(ENGINE_remove(new_h2))
		{
		printf("Remove *should* have failed but didn't!\n");
		goto end;
		}
	else
		printf("Remove that should fail did.\n");
	ERR_clear_error();
	if(!ENGINE_remove(new_h3))
		{
		printf("Remove failed!\n");
		goto end;
		}
	display_engine_list();
	if(!ENGINE_remove(new_h4))
		{
		printf("Remove failed!\n");
		goto end;
		}
	display_engine_list();
	/* Depending on whether there's any hardware support compiled
	 * in, this remove may be destined to fail. */
	ptr = ENGINE_get_first();
	if(ptr)
		if(!ENGINE_remove(ptr))
			printf("Remove failed!i - probably no hardware "
				"support present.\n");
	if (ptr)
		ENGINE_free(ptr);
	display_engine_list();
	if(!ENGINE_add(new_h1) || !ENGINE_remove(new_h1))
		{
		printf("Couldn't add and remove to an empty list!\n");
		goto end;
		}
	else
		printf("Successfully added and removed to an empty list!\n");
	printf("About to beef up the engine-type list\n");
	for(loop = 0; loop < 512; loop++)
		{
		sprintf(buf, "id%i", loop);
		id = BUF_strdup(buf);
		sprintf(buf, "Fake engine type %i", loop);
		name = BUF_strdup(buf);
		if(((block[loop] = ENGINE_new()) == NULL) ||
				!ENGINE_set_id(block[loop], id) ||
				!ENGINE_set_name(block[loop], name))
			{
			printf("Couldn't create block of ENGINE structures.\n"
				"I'll probably also core-dump now, damn.\n");
			goto end;
			}
		}
	for(loop = 0; loop < 512; loop++)
		{
		if(!ENGINE_add(block[loop]))
			{
			printf("\nAdding stopped at %i, (%s,%s)\n",
				loop, ENGINE_get_id(block[loop]),
				ENGINE_get_name(block[loop]));
			goto cleanup_loop;
			}
		else
			printf("."); fflush(stdout);
		}
cleanup_loop:
	printf("\nAbout to empty the engine-type list\n");
	while((ptr = ENGINE_get_first()) != NULL)
		{
		if(!ENGINE_remove(ptr))
			{
			printf("\nRemove failed!\n");
			goto end;
			}
		ENGINE_free(ptr);
		printf("."); fflush(stdout);
		}
	for(loop = 0; loop < 512; loop++)
		{
		OPENSSL_free((void *)ENGINE_get_id(block[loop]));
		OPENSSL_free((void *)ENGINE_get_name(block[loop]));
		}
	printf("\nTests completed happily\n");
	to_return = 0;
end:
	if(to_return)
		ERR_print_errors_fp(stderr);
	if(new_h1) ENGINE_free(new_h1);
	if(new_h2) ENGINE_free(new_h2);
	if(new_h3) ENGINE_free(new_h3);
	if(new_h4) ENGINE_free(new_h4);
	for(loop = 0; loop < 512; loop++)
		if(block[loop])
			ENGINE_free(block[loop]);
	ENGINE_cleanup();
	CRYPTO_cleanup_all_ex_data();
	ERR_free_strings();
	ERR_remove_thread_state(NULL);
	CRYPTO_mem_leaks_fp(stderr);
	return to_return;
	}
Beispiel #27
0
int main(int argc,char **argv)
    {
    const char *szTestFile;
    FILE *f;

    if(argc != 2)
	{
	fprintf(stderr,"%s <test file>\n",argv[0]);
	EXIT(1);
	}
    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);

    szTestFile=argv[1];

    f=fopen(szTestFile,"r");
    if(!f)
	{
	perror(szTestFile);
	EXIT(2);
	}

    /* Load up the software EVP_CIPHER and EVP_MD definitions */
    OpenSSL_add_all_ciphers();
    OpenSSL_add_all_digests();
#ifndef OPENSSL_NO_ENGINE
    /* Load all compiled-in ENGINEs */
    ENGINE_load_builtin_engines();
#endif
#if 0
    OPENSSL_config();
#endif
#ifndef OPENSSL_NO_ENGINE
    /* Register all available ENGINE implementations of ciphers and digests.
     * This could perhaps be changed to "ENGINE_register_all_complete()"? */
    ENGINE_register_all_ciphers();
    ENGINE_register_all_digests();
    /* If we add command-line options, this statement should be switchable.
     * It'll prevent ENGINEs being ENGINE_init()ialised for cipher/digest use if
     * they weren't already initialised. */
    /* ENGINE_set_cipher_flags(ENGINE_CIPHER_FLAG_NOINIT); */
#endif

    for( ; ; )
	{
	char line[4096];
	char *p;
	char *cipher;
	unsigned char *iv,*key,*plaintext,*ciphertext;
	int encdec;
	int kn,in,pn,cn;

	if(!fgets((char *)line,sizeof line,f))
	    break;
	if(line[0] == '#' || line[0] == '\n')
	    continue;
	p=line;
	cipher=sstrsep(&p,":");	
	key=ustrsep(&p,":");
	iv=ustrsep(&p,":");
	plaintext=ustrsep(&p,":");
	ciphertext=ustrsep(&p,":");
	if (p[-1] == '\n') {
	    p[-1] = '\0';
	    encdec = -1;
	} else {
	    encdec = atoi(sstrsep(&p,"\n"));
	}
	      

	kn=convert(key);
	in=convert(iv);
	pn=convert(plaintext);
	cn=convert(ciphertext);

	if(!test_cipher(cipher,key,kn,iv,in,plaintext,pn,ciphertext,cn,encdec)
	   && !test_digest(cipher,plaintext,pn,ciphertext,cn))
	    {
#ifdef OPENSSL_NO_AES
	    if (strstr(cipher, "AES") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
#ifdef OPENSSL_NO_DES
	    if (strstr(cipher, "DES") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
#ifdef OPENSSL_NO_RC4
	    if (strstr(cipher, "RC4") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
#ifdef OPENSSL_NO_CAMELLIA
	    if (strstr(cipher, "CAMELLIA") == cipher)
		{
		fprintf(stdout, "Cipher disabled, skipping %s\n", cipher); 
		continue;
		}
#endif
	    fprintf(stderr,"Can't find %s\n",cipher);
	    EXIT(3);
	    }
	}

#ifndef OPENSSL_NO_ENGINE
    ENGINE_cleanup();
#endif
    EVP_cleanup();
    CRYPTO_cleanup_all_ex_data();
    ERR_remove_state(0);
    ERR_free_strings();
    CRYPTO_mem_leaks_fp(stderr);

    return 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;

    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 < 3; v++)
	{
	key = RSA_new();
	switch (v) {
    case 0:
	clen = key1(key, ctext_ex);
	break;
    case 1:
	clen = key2(key, ctext_ex);
	break;
    case 2:
	clen = key3(key, ctext_ex);
	break;
	}

	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);
	    goto next;
	    }
    
	/* 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");
    next:
	RSA_free(key);
	}

    CRYPTO_cleanup_all_ex_data();
    ERR_remove_state(0);

    CRYPTO_mem_leaks_fp(stderr);

    return err;
    }
Beispiel #29
0
int main(int argc, char *argv[])
{
    BIO *err;
    int testresult = 0;
    int currtest = 0;

    SSL_library_init();
    SSL_load_error_strings();

    err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT);

    CRYPTO_malloc_debug_init();
    CRYPTO_set_mem_debug_options(V_CRYPTO_MDEBUG_ALL);
    CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);


    confctx = SSL_CONF_CTX_new();
    ctx = SSL_CTX_new(SSLv23_method());
    ssl = SSL_new(ctx);
    if (confctx == NULL || ctx == NULL)
        goto end;

    SSL_CONF_CTX_set_flags(confctx, SSL_CONF_FLAG_FILE
                                    | SSL_CONF_FLAG_CLIENT
                                    | SSL_CONF_FLAG_SERVER);

    /*
     * For each test set up an SSL_CTX and SSL and see whether SSLv2 is enabled
     * as expected after various SSL_CONF_cmd("Protocol", ...) calls.
     */
    for (currtest = 0; currtest < TOTAL_NUM_TESTS; currtest++) {
        BIO_printf(err, "SSLv2 CONF Test number %d\n", currtest);
        if (currtest == TEST_SSL_CTX)
            SSL_CONF_CTX_set_ssl_ctx(confctx, ctx);
        else
            SSL_CONF_CTX_set_ssl(confctx, ssl);

        /* SSLv2 should be off by default */
        if (!checksslv2(currtest, SSLV2OFF)) {
            BIO_printf(err, "SSLv2 CONF Test: Off by default test FAIL\n");
            goto end;
        }

        if (SSL_CONF_cmd(confctx, "Protocol", "ALL") != 2
                || !SSL_CONF_CTX_finish(confctx)) {
            BIO_printf(err, "SSLv2 CONF Test: SSL_CONF command FAIL\n");
            goto end;
        }

        /* Should still be off even after ALL Protocols on */
        if (!checksslv2(currtest, SSLV2OFF)) {
            BIO_printf(err, "SSLv2 CONF Test: Off after config #1 FAIL\n");
            goto end;
        }

        if (SSL_CONF_cmd(confctx, "Protocol", "SSLv2") != 2
                || !SSL_CONF_CTX_finish(confctx)) {
            BIO_printf(err, "SSLv2 CONF Test: SSL_CONF command FAIL\n");
            goto end;
        }

        /* Should still be off even if explicitly asked for */
        if (!checksslv2(currtest, SSLV2OFF)) {
            BIO_printf(err, "SSLv2 CONF Test: Off after config #2 FAIL\n");
            goto end;
        }

        if (SSL_CONF_cmd(confctx, "Protocol", "-SSLv2") != 2
                || !SSL_CONF_CTX_finish(confctx)) {
            BIO_printf(err, "SSLv2 CONF Test: SSL_CONF command FAIL\n");;
            goto end;
        }

        if (!checksslv2(currtest, SSLV2OFF)) {
            BIO_printf(err, "SSLv2 CONF Test: Off after config #3 FAIL\n");
            goto end;
        }

        if (currtest == TEST_SSL_CTX)
            SSL_CTX_clear_options(ctx, SSL_OP_NO_SSLv2);
        else
            SSL_clear_options(ssl, SSL_OP_NO_SSLv2);

        if (!checksslv2(currtest, SSLV2ON)) {
            BIO_printf(err, "SSLv2 CONF Test: On after clear FAIL\n");
            goto end;
        }

        if (SSL_CONF_cmd(confctx, "Protocol", "ALL") != 2
                || !SSL_CONF_CTX_finish(confctx)) {
            BIO_printf(err, "SSLv2 CONF Test: SSL_CONF command FAIL\n");
            goto end;
        }

        /* Option has been cleared and config says have SSLv2 so should be on */
        if (!checksslv2(currtest, SSLV2ON)) {
            BIO_printf(err, "SSLv2 CONF Test: On after config #1 FAIL\n");
            goto end;
        }

        if (SSL_CONF_cmd(confctx, "Protocol", "SSLv2") != 2
                || !SSL_CONF_CTX_finish(confctx)) {
            BIO_printf(err, "SSLv2 CONF Test: SSL_CONF command FAIL\n");
            goto end;
        }

        /* Option has been cleared and config says have SSLv2 so should be on */
        if (!checksslv2(currtest, SSLV2ON)) {
            BIO_printf(err, "SSLv2 CONF Test: On after config #2 FAIL\n");
            goto end;
        }

        if (SSL_CONF_cmd(confctx, "Protocol", "-SSLv2") != 2
                || !SSL_CONF_CTX_finish(confctx)) {
            BIO_printf(err, "SSLv2 CONF Test: SSL_CONF command FAIL\n");
            goto end;
        }

        /* Option has been cleared but config says no SSLv2 so should be off */
        if (!checksslv2(currtest, SSLV2OFF)) {
            BIO_printf(err, "SSLv2 CONF Test: Off after config #4 FAIL\n");
            goto end;
        }

    }

    testresult = 1;

 end:
    SSL_free(ssl);
    SSL_CTX_free(ctx);
    SSL_CONF_CTX_free(confctx);

    if (!testresult) {
        printf("SSLv2 CONF test: FAILED (Test %d)\n", currtest);
        ERR_print_errors(err);
    } else {
        printf("SSLv2 CONF test: PASSED\n");
    }

    ERR_free_strings();
    ERR_remove_thread_state(NULL);
    EVP_cleanup();
    CRYPTO_cleanup_all_ex_data();
    CRYPTO_mem_leaks(err);
    BIO_free(err);

    return testresult ? EXIT_SUCCESS : EXIT_FAILURE;
}
Beispiel #30
0
int main(int argc, char *argv[])
	{
	BN_GENCB _cb;
	DH *a;
	DH *b=NULL;
	char buf[12];
	unsigned char *abuf=NULL,*bbuf=NULL;
	int i,alen,blen,aout,bout,ret=1;
	BIO *out;

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

#ifdef OPENSSL_SYS_WIN32
	CRYPTO_malloc_init();
#endif

	RAND_seed(rnd_seed, sizeof rnd_seed);

	out=BIO_new(BIO_s_file());
	if (out == NULL) EXIT(1);
	BIO_set_fp(out,stdout,BIO_NOCLOSE);

	BN_GENCB_set(&_cb, &cb, out);
	if(((a = DH_new()) == NULL) || !DH_generate_parameters_ex(a, 64,
				DH_GENERATOR_5, &_cb))
		goto err;

	if (!DH_check(a, &i)) goto err;
	if (i & DH_CHECK_P_NOT_PRIME)
		BIO_puts(out, "p value is not prime\n");
	if (i & DH_CHECK_P_NOT_SAFE_PRIME)
		BIO_puts(out, "p value is not a safe prime\n");
	if (i & DH_UNABLE_TO_CHECK_GENERATOR)
		BIO_puts(out, "unable to check the generator value\n");
	if (i & DH_NOT_SUITABLE_GENERATOR)
		BIO_puts(out, "the g value is not a generator\n");

	BIO_puts(out,"\np    =");
	BN_print(out,a->p);
	BIO_puts(out,"\ng    =");
	BN_print(out,a->g);
	BIO_puts(out,"\n");

	b=DH_new();
	if (b == NULL) goto err;

	b->p=BN_dup(a->p);
	b->g=BN_dup(a->g);
	if ((b->p == NULL) || (b->g == NULL)) goto err;

	/* Set a to run with normal modexp and b to use constant time */
	a->flags &= ~DH_FLAG_NO_EXP_CONSTTIME;
	b->flags |= DH_FLAG_NO_EXP_CONSTTIME;

	if (!DH_generate_key(a)) goto err;
	BIO_puts(out,"pri 1=");
	BN_print(out,a->priv_key);
	BIO_puts(out,"\npub 1=");
	BN_print(out,a->pub_key);
	BIO_puts(out,"\n");

	if (!DH_generate_key(b)) goto err;
	BIO_puts(out,"pri 2=");
	BN_print(out,b->priv_key);
	BIO_puts(out,"\npub 2=");
	BN_print(out,b->pub_key);
	BIO_puts(out,"\n");

	alen=DH_size(a);
	abuf=(unsigned char *)OPENSSL_malloc(alen);
	aout=DH_compute_key(abuf,b->pub_key,a);

	BIO_puts(out,"key1 =");
	for (i=0; i<aout; i++)
		{
		snprintf(buf, sizeof(buf), "%02X",abuf[i]);
		BIO_puts(out,buf);
		}
	BIO_puts(out,"\n");

	blen=DH_size(b);
	bbuf=(unsigned char *)OPENSSL_malloc(blen);
	bout=DH_compute_key(bbuf,a->pub_key,b);

	BIO_puts(out,"key2 =");
	for (i=0; i<bout; i++)
		{
		snprintf(buf, sizeof(buf), "%02X",bbuf[i]);
		BIO_puts(out,buf);
		}
	BIO_puts(out,"\n");
	if ((aout < 4) || (bout != aout) || (memcmp(abuf,bbuf,aout) != 0))
		{
		fprintf(stderr,"Error in DH routines\n");
		ret=1;
		}
	else
		ret=0;
err:
	ERR_print_errors_fp(stderr);

	if (abuf != NULL) OPENSSL_free(abuf);
	if (bbuf != NULL) OPENSSL_free(bbuf);
	if(b != NULL) DH_free(b);
	if(a != NULL) DH_free(a);
	BIO_free(out);
#ifdef OPENSSL_SYS_NETWARE
    if (ret) printf("ERROR: %d\n", ret);
#endif
	EXIT(ret);
	return(ret);
	}