コード例 #1
0
ファイル: stud.c プロジェクト: mqudsi/stud
/* Init library and load specified certificate.
 * Establishes a SSL_ctx, to act as a template for
 * each connection */
static SSL_CTX * init_openssl() {
    SSL_library_init();
    SSL_load_error_strings();
    SSL_CTX *ctx = NULL;
    long ssloptions = SSL_OP_NO_SSLv2 | SSL_OP_ALL | 
            SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION;

    if (OPTIONS.ETYPE == ENC_TLS)
        ctx = SSL_CTX_new(TLSv1_server_method());
    else if (OPTIONS.ETYPE == ENC_SSL)
        ctx = SSL_CTX_new(SSLv23_server_method());
    else
        assert(OPTIONS.ETYPE == ENC_TLS || OPTIONS.ETYPE == ENC_SSL);

#ifdef SSL_OP_NO_COMPRESSION
    ssloptions |= SSL_OP_NO_COMPRESSION;
#endif

    SSL_CTX_set_options(ctx, ssloptions);

    if (SSL_CTX_use_certificate_chain_file(ctx, OPTIONS.CERT_FILE) <= 0) {
        ERR_print_errors_fp(stderr);
        exit(1);
    }
    if (SSL_CTX_use_RSAPrivateKey_file(ctx, OPTIONS.CERT_FILE, SSL_FILETYPE_PEM) <= 0) {
        ERR_print_errors_fp(stderr);
        exit(1);
    }

#ifndef OPENSSL_NO_DH
    init_dh(ctx, OPTIONS.CERT_FILE);
#endif /* OPENSSL_NO_DH */

    if (OPTIONS.CIPHER_SUITE)
        if (SSL_CTX_set_cipher_list(ctx, OPTIONS.CIPHER_SUITE) != 1)
            ERR_print_errors_fp(stderr);

#ifdef USE_SHARED_CACHE
    if (OPTIONS.SHARED_CACHE) {
        if (shared_context_init(ctx, OPTIONS.SHARED_CACHE) < 0) {
            ERR("Unable to alloc memory for shared cache.\n");
            exit(1);
        }
    }
#endif

    return ctx;
}
コード例 #2
0
ファイル: q34.c プロジェクト: hundt/crypto-challenges
dh_key B_get_key(mpz_t *p, mpz_t *g) {
    mpz_t* new_p = (mpz_t*)calloc(1, sizeof(mpz_t));
    mpz_t* new_g = (mpz_t*)calloc(1, sizeof(mpz_t));
    mpz_t* a = (mpz_t*)calloc(1, sizeof(mpz_t));
    mpz_t* A = (mpz_t*)calloc(1, sizeof(mpz_t));

    init_dh();
    mpz_init_set(*new_p, *p);
    mpz_init_set(*new_g, *g);
    mpz_init(*a);
    mpz_urandomm(*a, rand_state, *p);
    mpz_init(*A);
    mpz_powm(*A, *g, *a, *p);

    return (dh_key) {.p = new_p, .g = new_g, .private = a, .public = A};
}
コード例 #3
0
int EVP_PKEY_set_std_dp(EVP_PKEY *key, int stnd_dp) {

    DH *dh = NULL;
    EC_KEY *ec = NULL;

    if (!key) {
        log_err("Invalid arguments");
        return 0;
    }

    /* Generate key from standardized domain parameters */
    switch(stnd_dp) {
        case 0:
        case 1:
        case 2:
            if (!init_dh(&dh, stnd_dp))
                return 0;
            EVP_PKEY_set1_DH(key, dh);
            /* Decrement reference count */
            DH_free(dh);
            break;

        case 8:
        case 9:
        case 10:
        case 11:
        case 12:
        case 13:
        case 14:
        case 15:
        case 16:
        case 17:
        case 18:
            if (!init_ecdh(&ec, stnd_dp))
                return 0;
            EVP_PKEY_set1_EC_KEY(key, ec);
            /* Decrement reference count */
            EC_KEY_free(ec);
            break;

        default:
            log_err("Invalid arguments");
            return 0;
    }

    return 1;
}
コード例 #4
0
void context_init(void) { /* init SSL */
    int i;

#if SSLEAY_VERSION_NUMBER >= 0x00907000L
    /* Load all bundled ENGINEs into memory and make them visible */
    ENGINE_load_builtin_engines();
    /* Register all of them for every algorithm they collectively implement */
    ENGINE_register_all_complete();
#endif
    if(!init_prng())
        log(LOG_INFO, "PRNG seeded successfully");
    SSLeay_add_ssl_algorithms();
    SSL_load_error_strings();
    if(options.option.client) {
        ctx=SSL_CTX_new(SSLv3_client_method());
    } else { /* Server mode */
        ctx=SSL_CTX_new(SSLv23_server_method());
#ifndef NO_RSA
        SSL_CTX_set_tmp_rsa_callback(ctx, tmp_rsa_cb);
#endif /* NO_RSA */
        if(init_dh())
            log(LOG_WARNING, "Diffie-Hellman initialization failed");
    }
    if(options.ssl_options) {
        log(LOG_DEBUG, "Configuration SSL options: 0x%08lX",
            options.ssl_options);
        log(LOG_DEBUG, "SSL options set: 0x%08lX", 
            SSL_CTX_set_options(ctx, options.ssl_options));
    }
#if SSLEAY_VERSION_NUMBER >= 0x00906000L
    SSL_CTX_set_mode(ctx,
        SSL_MODE_ENABLE_PARTIAL_WRITE|SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
#endif /* OpenSSL-0.9.6 */

    SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_BOTH);
    SSL_CTX_set_timeout(ctx, options.session_timeout);
    if(options.option.cert) {
        if(!SSL_CTX_use_certificate_chain_file(ctx, options.cert)) {
            log(LOG_ERR, "Error reading certificate file: %s", options.cert);
            sslerror("SSL_CTX_use_certificate_chain_file");
            exit(1);
        }
        log(LOG_DEBUG, "Certificate: %s", options.cert);
        log(LOG_DEBUG, "Key file: %s", options.key);
#ifdef USE_WIN32
        SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb);
#endif
        for(i=0; i<3; i++) {
#ifdef NO_RSA
            if(SSL_CTX_use_PrivateKey_file(ctx, options.key,
                    SSL_FILETYPE_PEM))
#else /* NO_RSA */
            if(SSL_CTX_use_RSAPrivateKey_file(ctx, options.key,
                    SSL_FILETYPE_PEM))
#endif /* NO_RSA */
                break;
            if(i<2 && ERR_GET_REASON(ERR_peek_error())==EVP_R_BAD_DECRYPT) {
                sslerror_stack(); /* dump the error stack */
                log(LOG_ERR, "Wrong pass phrase: retrying");
                continue;
            }
#ifdef NO_RSA
            sslerror("SSL_CTX_use_PrivateKey_file");
#else /* NO_RSA */
            sslerror("SSL_CTX_use_RSAPrivateKey_file");
#endif /* NO_RSA */
            exit(1);
        }
        if(!SSL_CTX_check_private_key(ctx)) {
            sslerror("Private key does not match the certificate");
            exit(1);
        }
    }

    verify_init(); /* Initialize certificate verification */

    SSL_CTX_set_info_callback(ctx, info_callback);

    if(options.cipher_list) {
        if (!SSL_CTX_set_cipher_list(ctx, options.cipher_list)) {
            sslerror("SSL_CTX_set_cipher_list");
            exit(1);
        }
    }
}
コード例 #5
0
ファイル: ctx.c プロジェクト: Jimdo/stunnel
int context_init(SERVICE_OPTIONS *section) { /* init SSL context */
    /* create SSL context */
    if(section->option.client)
        section->ctx=SSL_CTX_new(section->client_method);
    else /* server mode */
        section->ctx=SSL_CTX_new(section->server_method);
    if(!section->ctx) {
        sslerror("SSL_CTX_new");
        return 1; /* FAILED */
    }
    SSL_CTX_set_ex_data(section->ctx, opt_index, section); /* for callbacks */

    /* load certificate and private key to be verified by the peer server */
#ifdef HAVE_OSSL_ENGINE_H
    if(section->option.client && section->engine) {
        if(SSL_CTX_set_client_cert_engine(section->ctx, section->engine))
            s_log(LOG_INFO, "Client certificate engine (%s) enabled",
                ENGINE_get_id(section->engine));
        else /* no client certificate functionality in this engine */
            sslerror("SSL_CTX_set_client_cert_engine"); /* ignore error */
    }
#endif
    if(load_cert(section))
        return 1; /* FAILED */

    /* initialize verification of the peer server certificate */
    if(verify_init(section))
        return 1; /* FAILED */

    /* initialize DH/ECDH server mode */
    if(!section->option.client) {
#ifndef OPENSSL_NO_TLSEXT
        SSL_CTX_set_tlsext_servername_arg(section->ctx, section);
        SSL_CTX_set_tlsext_servername_callback(section->ctx, servername_cb);
#endif /* OPENSSL_NO_TLSEXT */
#ifndef OPENSSL_NO_DH
        init_dh(section); /* ignore the result (errors are not critical) */
#endif /* OPENSSL_NO_DH */
#ifndef OPENSSL_NO_ECDH
        init_ecdh(section); /* ignore the result (errors are not critical) */
#endif /* OPENSSL_NO_ECDH */
    }

    /* setup session cache */
    if(!section->option.client) {
        unsigned int servname_len=strlen(section->servname);
        if(servname_len>SSL_MAX_SSL_SESSION_ID_LENGTH)
            servname_len=SSL_MAX_SSL_SESSION_ID_LENGTH;
        if(!SSL_CTX_set_session_id_context(section->ctx,
                (unsigned char *)section->servname, servname_len)) {
            sslerror("SSL_CTX_set_session_id_context");
            return 1; /* FAILED */
        }
    }
    SSL_CTX_set_session_cache_mode(section->ctx, SSL_SESS_CACHE_BOTH);
    SSL_CTX_sess_set_cache_size(section->ctx, section->session_size);
    SSL_CTX_set_timeout(section->ctx, section->session_timeout);
    if(section->option.sessiond) {
        SSL_CTX_sess_set_new_cb(section->ctx, sess_new_cb);
        SSL_CTX_sess_set_get_cb(section->ctx, sess_get_cb);
        SSL_CTX_sess_set_remove_cb(section->ctx, sess_remove_cb);
    }

    /* set info callback */
    SSL_CTX_set_info_callback(section->ctx, info_callback);

    /* ciphers, options, mode */
    if(section->cipher_list)
        if(!SSL_CTX_set_cipher_list(section->ctx, section->cipher_list)) {
            sslerror("SSL_CTX_set_cipher_list");
            return 1; /* FAILED */
        }
    s_log(LOG_DEBUG, "SSL options set: 0x%08lX",
        SSL_CTX_set_options(section->ctx, section->ssl_options));
#ifdef SSL_MODE_RELEASE_BUFFERS
    SSL_CTX_set_mode(section->ctx,
        SSL_MODE_ENABLE_PARTIAL_WRITE |
        SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
        SSL_MODE_RELEASE_BUFFERS);
#else
    SSL_CTX_set_mode(section->ctx,
        SSL_MODE_ENABLE_PARTIAL_WRITE |
        SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
#endif
    return 0; /* OK */
}
コード例 #6
0
ファイル: tls.c プロジェクト: Zabrane/SPOCP
SSL_CTX        *
tls_init(srv_t * srv)
{
	char            path[_POSIX_PATH_MAX];
	SSL_CTX        *ctx;
	int             r;
	char            errorstr[1024];
	unsigned long   e;

	SSL_library_init();
	SSL_load_error_strings();	/* basic set up */
	OpenSSL_add_ssl_algorithms();

	/*
	 * Create a TLS context 
	 */

	if (!(ctx = SSL_CTX_new(SSLv23_method()))) {
		LOG(SPOCP_ERR) traceLog(LOG_ERR,"Error allocation SSL_CTX");
		return 0;
	}

	LOG(SPOCP_DEBUG) traceLog(LOG_DEBUG,"Do we have enough randomness ??");

	if (!RAND_status()) {
		/*
		 * load entropy from files 
		 */
		add_entropy(srv->SslEntropyFile);
		add_entropy(RAND_file_name(path, sizeof(path)));

		/*
		 * load entropy from egd sockets 
		 */
#ifdef HAVE_RAND_EGD
		add_entropy(getenv("EGDSOCKET"));
		snprintf(path, sizeof(path), "%s/.entropy", NONULL(Homedir));
		add_entropy(path);
		add_entropy("/tmp/entropy");
#endif

		/*
		 * shuffle $RANDFILE (or ~/.rnd if unset) 
		 */
		RAND_write_file(RAND_file_name(path, sizeof(path)));
		if (!RAND_status()) {
			LOG(SPOCP_ERR)
				traceLog(LOG_ERR,
				    "Failed to find enough entropy on your system");
			return 0;
		}
	}

	/*
	 * Initialize with DH parameters if supplied 
	 */

	if (srv->dhFile) {
		if (init_dh(ctx, (unsigned char *) srv->dhFile) == FALSE) {
			LOG(SPOCP_ERR) traceLog(LOG_ERR,"Error initializing DH");
			SSL_CTX_free(ctx);
			return 0;
		} else
			LOG(SPOCP_ERR) traceLog(LOG_ERR,"Initializing DH OK");
	}

	/*
	 * and a RSA key too 
	 */

	if (generate_eph_rsa_key(ctx, 512) == FALSE) {
		LOG(SPOCP_ERR) traceLog(LOG_ERR,"Error initializing RSA key");
		SSL_CTX_free(ctx);
		return 0;
	} else
		LOG(SPOCP_ERR) traceLog(LOG_ERR,"Initializing RSA key OK");

	/*
	 * Set up certificates and keys 
	 */

	if (srv->certificateFile != NULL) {
		LOG(SPOCP_INFO) traceLog(LOG_INFO,"Reading Certificate File");
		if (!SSL_CTX_use_certificate_chain_file
		    (ctx, srv->certificateFile)) {
			LOG(SPOCP_ERR)
			    traceLog(LOG_ERR,"Error in SSL_CTX_use_certificate_file");
			SSL_CTX_free(ctx);
			return 0;
		}
	}

	if (srv->privateKey != NULL) {

		if (srv->passwd) {
			SSL_CTX_set_default_passwd_cb_userdata(ctx,
							       (void *) srv->
							       passwd);
			SSL_CTX_set_default_passwd_cb(ctx, password_cb);
		}

		LOG(SPOCP_INFO) traceLog(LOG_INFO,"Reading Private Key File");
		r = SSL_CTX_use_PrivateKey_file(ctx, srv->privateKey,
						SSL_FILETYPE_PEM);
		if (r == 0) {
			e = ERR_get_error();
			ERR_error_string_n(e, errorstr, 1024);

			LOG(SPOCP_ERR)
			    traceLog(LOG_ERR,"Error in SSL_CTX_use_PrivateKey_file");
			LOG(SPOCP_ERR) traceLog(LOG_ERR,"%s", errorstr);

			SSL_CTX_free(ctx);
			return 0;
		}
	}

	if (srv->caList != NULL) {
		LOG(SPOCP_INFO) traceLog(LOG_INFO,"Reading Trusted CAs File");
		if (!SSL_CTX_load_verify_locations(ctx, srv->caList, 0)) {
			LOG(SPOCP_ERR)
			    traceLog(LOG_ERR,"Error in SSL_CTX_load_verify_locations");
			SSL_CTX_free(ctx);
			return 0;
		}
	}

	if (srv->clientcert == NONE)
		SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback_ok);
	else {
		int             i = SSL_VERIFY_PEER;
		if (srv->clientcert == HARD)
			i |= SSL_VERIFY_CLIENT_ONCE;

		SSL_CTX_set_verify(ctx, i, verify_callback);
	}

	SSL_CTX_set_verify_depth(ctx, srv->sslverifydepth);

	SSL_CTX_set_options(ctx, SSL_OP_ALL | SSL_OP_NO_SSLv2);

	if (SSL_CTX_set_cipher_list(ctx, CIPHER_LIST) != 1) {
		LOG(SPOCP_ERR) traceLog(LOG_ERR,"No valid ciphers in cipherlist");
		SSL_CTX_free(ctx);
		return 0;
	}

	LOG(SPOCP_DEBUG) traceLog(LOG_DEBUG,"Initialised TLS");

	return ctx;
}
コード例 #7
0
ファイル: tls-gnu.c プロジェクト: fanf2/exim
static int
tls_init(host_item *host, uschar *certificate, uschar *privatekey, uschar *cas,
  uschar *crl)
{
int rc;
uschar *cert_expanded, *key_expanded, *cas_expanded, *crl_expanded;

client_host = host;

rc = gnutls_global_init();
if (rc < 0) return tls_error(US"tls-init", host, gnutls_strerror(rc));

/* Create D-H parameters, or read them from the cache file. This function does
its own SMTP error messaging. */

rc = init_dh(host);
if (rc != OK) return rc;

/* Create the credentials structure */

rc = gnutls_certificate_allocate_credentials(&x509_cred);
if (rc < 0)
  return tls_error(US"certificate_allocate_credentials",
    host, gnutls_strerror(rc));

/* This stuff must be done for each session, because different certificates
may be required for different sessions. */

if (!expand_check(certificate, US"tls_certificate", &cert_expanded))
  return DEFER;

key_expanded = NULL;
if (privatekey != NULL)
  {
  if (!expand_check(privatekey, US"tls_privatekey", &key_expanded))
    return DEFER;
  }

/* If expansion was forced to fail, key_expanded will be NULL. If the result of
the expansion is an empty string, ignore it also, and assume that the private
key is in the same file as the certificate. */

if (key_expanded == NULL || *key_expanded == 0)
  key_expanded = cert_expanded;

/* Set the certificate and private keys */

if (cert_expanded != NULL)
  {
  DEBUG(D_tls) debug_printf("certificate file = %s\nkey file = %s\n",
    cert_expanded, key_expanded);
  rc = gnutls_certificate_set_x509_key_file(x509_cred, CS cert_expanded,
    CS key_expanded, GNUTLS_X509_FMT_PEM);
  if (rc < 0)
    {
    uschar *msg = string_sprintf("cert/key setup: cert=%s key=%s",
      cert_expanded, key_expanded);
    return tls_error(msg, host, gnutls_strerror(rc));
    }
  }

/* A certificate is mandatory in a server, but not in a client */

else
  {
  if (host == NULL)
    return tls_error(US"no TLS server certificate is specified", NULL, NULL);
  DEBUG(D_tls) debug_printf("no TLS client certificate is specified\n");
  }

/* Set the trusted CAs file if one is provided, and then add the CRL if one is
provided. Experiment shows that, if the certificate file is empty, an unhelpful
error message is provided. However, if we just refrain from setting anything up
in that case, certificate verification fails, which seems to be the correct
behaviour. */

if (cas != NULL)
  {
  struct stat statbuf;

  if (!expand_check(cas, US"tls_verify_certificates", &cas_expanded))
    return DEFER;

  if (stat(CS cas_expanded, &statbuf) < 0)
    {
    log_write(0, LOG_MAIN|LOG_PANIC, "could not stat %s "
      "(tls_verify_certificates): %s", cas_expanded, strerror(errno));
    return DEFER;
    }

  DEBUG(D_tls) debug_printf("verify certificates = %s size=" OFF_T_FMT "\n",
    cas_expanded, statbuf.st_size);

  /* If the cert file is empty, there's no point in loading the CRL file. */

  if (statbuf.st_size > 0)
    {
    rc = gnutls_certificate_set_x509_trust_file(x509_cred, CS cas_expanded,
      GNUTLS_X509_FMT_PEM);
    if (rc < 0) return tls_error(US"setup_certs", host, gnutls_strerror(rc));

    if (crl != NULL && *crl != 0)
      {
      if (!expand_check(crl, US"tls_crl", &crl_expanded))
        return DEFER;
      DEBUG(D_tls) debug_printf("loading CRL file = %s\n", crl_expanded);
      rc = gnutls_certificate_set_x509_crl_file(x509_cred, CS crl_expanded,
        GNUTLS_X509_FMT_PEM);
      if (rc < 0) return tls_error(US"CRL setup", host, gnutls_strerror(rc));
      }
    }
  }

/* Associate the parameters with the x509 credentials structure. */

gnutls_certificate_set_dh_params(x509_cred, dh_params);

DEBUG(D_tls) debug_printf("initialized certificate stuff\n");
return OK;
}