示例#1
0
static EC_KEY *ecdh_auto_cb(SSL *ssl, int is_export, int keylength)
{
	static EC_KEY *ecdh;
	int last_nid;
	int nid = 0;
	EVP_PKEY *pk;
	EC_KEY *ec;

	/* pick curve from EC key */
	pk = SSL_get_privatekey(ssl);
	if (pk && pk->type == EVP_PKEY_EC) {
		ec = EVP_PKEY_get1_EC_KEY(pk);
		if (ec) {
			nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ec));
			EC_KEY_free(ec);
		}
	}

	/* ssl->tlsext_ellipticcurvelist is empty, nothing else to do... */
	if (nid == 0)
		nid = NID_X9_62_prime256v1;

	if (ecdh) {
		last_nid = EC_GROUP_get_curve_name(EC_KEY_get0_group(ecdh));
		if (last_nid == nid)
			return ecdh;
		EC_KEY_free(ecdh);
		ecdh = NULL;
	}

	ecdh = EC_KEY_new_by_curve_name(nid);
	return ecdh;
}
示例#2
0
struct SSLConnection *
tls_connection_create(struct in_addr caddr, uint16_t cport, struct in_addr saddr, uint16_t sport) {
    struct SSLConnection *conn = NULL;
    conn = sng_malloc(sizeof(struct SSLConnection));

    memcpy(&conn->client_addr, &caddr, sizeof(struct in_addr));
    memcpy(&conn->server_addr, &saddr, sizeof(struct in_addr));
    memcpy(&conn->client_port, &cport, sizeof(uint16_t));
    memcpy(&conn->server_port, &sport, sizeof(uint16_t));

    SSL_library_init();
    ERR_load_crypto_strings();
    OpenSSL_add_all_algorithms();

    if (!(conn->ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
        return NULL;

    SSL_CTX_use_PrivateKey_file(conn->ssl_ctx, capture_get_keyfile(),
                                SSL_FILETYPE_PEM);
    if (!(conn->ssl = SSL_new(conn->ssl_ctx)))
        return NULL;

    conn->server_private_key = SSL_get_privatekey(conn->ssl);

    // Add this connection to the list
    conn->next = connections;
    connections = conn;

    return conn;
}
示例#3
0
/**
 * FIXME Replace this with a tls_load_key function and use it
 * in tls_connection_create.
 *
 * Most probably we only need one context and key for all connections
 */
int
tls_check_keyfile(const char *keyfile)
{
    SSL *ssl;
    SSL_CTX *ssl_ctx;

    SSL_library_init();
    ERR_load_crypto_strings();
    OpenSSL_add_all_algorithms();

    if (access(capture_get_keyfile(), R_OK) != 0)
        return 0;

    if (!(ssl_ctx = SSL_CTX_new(SSLv23_server_method())))
        return 0;

    SSL_CTX_use_PrivateKey_file(ssl_ctx, capture_get_keyfile(), SSL_FILETYPE_PEM);
    if (!(ssl = SSL_new(ssl_ctx)))
        return 0;

    if (!SSL_get_privatekey(ssl))
        return 0;

    return 1;
}
示例#4
0
static DH *dh_auto_cb(SSL *s, int is_export, int keylength)
{
	EVP_PKEY *pk;
	int bits;

	pk = SSL_get_privatekey(s);
	if (!pk)
		return load_dh_buffer(&dh2048, file_dh2048);

	bits = EVP_PKEY_bits(pk);
	if (bits >= 3072)
		return load_dh_buffer(&dh4096, file_dh4096);
	if (bits >= 1536)
		return load_dh_buffer(&dh2048, file_dh2048);
	return load_dh_buffer(&dh1024, file_dh1024);
}
示例#5
0
文件: Family.cpp 项目: PurpleI2P/i2pd
	std::string CreateFamilySignature (const std::string& family, const IdentHash& ident)
	{
		auto filename = i2p::fs::DataDirPath("family", (family + ".key"));
		std::string sig;
		SSL_CTX * ctx = SSL_CTX_new (TLS_method ());
		int ret = SSL_CTX_use_PrivateKey_file (ctx, filename.c_str (), SSL_FILETYPE_PEM);
		if (ret)
		{
			SSL * ssl = SSL_new (ctx);
			EVP_PKEY * pkey = SSL_get_privatekey (ssl);
			EC_KEY * ecKey = EVP_PKEY_get1_EC_KEY (pkey);
			if (ecKey)
			{
				auto group = EC_KEY_get0_group (ecKey);
				if (group)
				{
					int curve = EC_GROUP_get_curve_name (group);
					if (curve == NID_X9_62_prime256v1)
					{
						uint8_t signingPrivateKey[32], buf[50], signature[64];
						i2p::crypto::bn2buf (EC_KEY_get0_private_key (ecKey), signingPrivateKey, 32);
						i2p::crypto::ECDSAP256Signer signer (signingPrivateKey);
						size_t len = family.length ();
						memcpy (buf, family.c_str (), len);
						memcpy (buf + len, (const uint8_t *)ident, 32);
						len += 32;
						signer.Sign (buf, len, signature);
						len = Base64EncodingBufferSize (64);
						char * b64 = new char[len+1];
						len = ByteStreamToBase64 (signature, 64, b64, len);
						b64[len] = 0;
						sig = b64;
						delete[] b64;
					}
					else
						LogPrint (eLogWarning, "Family: elliptic curve ", curve, " is not supported");
				}
			}
			SSL_free (ssl);
		}
		else
			LogPrint (eLogError, "Family: Can't open keys file: ", filename);
		SSL_CTX_free (ctx);
		return sig;
	}
示例#6
0
文件: ssl.c 项目: UIKit0/picogui
static void *
_SSL_get_sess_obj(SSL *ssl, int type)
{
	void *obj = NULL;


	switch (type) {
	    case 0:
		obj = X509_get_pubkey(SSL_get_certificate(ssl));
		break;
	    case 1:
		obj = SSL_get_privatekey(ssl);
		break;
	    case 2:
		obj = SSL_get_certificate(ssl);
		break;
	}
	return (obj);
}
示例#7
0
文件: sign.c 项目: haad/syslogd
int
syslog_sign_init()
{
    SSL *ssl;

    sign_global_conf =  EVP_MD_CTX_create();
    EVP_MD_CTX_init(sign_global_conf);

    if (ssl = SSL_new(ssl_global_conf)) {
        dprintf("Try to get keys from TLS X.509 cert...\n");

        if (!(xcert = SSL_get_certificate(ssl))) {
            logerror("SSL_get_certificate() failed");
            SSL_free(ssl);
            return EXIT_FAILURE;
        }
        if (!(eprivkey = SSL_get_privatekey(ssl))) {
            logerror("SSL_get_privatekey() failed");
            SSL_free(ssl);
            return EXIT_FAILURE;
        }
        if (!(epubkey = X509_get_pubkey(xcert))) {
            logerror("X509_get_pubkey() failed");
            SSL_free(ssl);
            return EXIT_FAILURE;
        }
    }

    SSL_free(ssl);

    if (EVP_PKEY_DSA != EVP_PKEY_type(epubkey->type)) {
        dprintf("X.509 cert has no DSA key\n");
        EVP_PKEY_free(epubkey);
        eprivkey = NULL;
        epubkey = NULL;
    } else {
        dprintf("Got public and private key "
                "from X.509 --> use type PKIX\n");

        sign_method = EVP_dss1();
    }
}
示例#8
0
static DH* SSLGetDHCallback(SSL* ssl, int exp, int keylen) {
    (void)exp;
    EVP_PKEY* pkey = SSL_get_privatekey(ssl);
    int type = pkey ? EVP_PKEY_base_id(pkey) : EVP_PKEY_NONE;

    // The keylen supplied by OpenSSL can only be 512 or 1024.
    // See ssl3_send_server_key_exchange() in ssl/s3_srvr.c
    if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA) {
        keylen = EVP_PKEY_bits(pkey);
    }

    if (keylen >= 8192) {
        return g_dh_8192;
    } else if (keylen >= 4096) {
        return g_dh_4096;
    } else if (keylen >= 2048) {
        return g_dh_2048;
    } else {
        return g_dh_1024;
    }
}
示例#9
0
SSL *SSLSocket::createSSL(SSL_CTX *ctx) {
  ERR_clear_error();

  /* look at options in the stream and set appropriate verification flags */
  if (m_context[s_verify_peer].toBoolean()) {
    /* turn on verification callback */
    SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verifyCallback);

    /* CA stuff */
    String cafile = m_context[s_cafile].toString();
    String capath = m_context[s_capath].toString();

    if (!cafile.empty() || !capath.empty()) {
      if (!SSL_CTX_load_verify_locations(ctx, cafile.data(), capath.data())) {
        raise_warning("Unable to set verify locations `%s' `%s'",
                      cafile.data(), capath.data());
        return nullptr;
      }
    }

    int64_t depth = m_context[s_verify_depth].toInt64();
    if (depth) {
      SSL_CTX_set_verify_depth(ctx, depth);
    }
  } else {
    SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);
  }

  /* callback for the passphrase (for localcert) */
  if (!m_context[s_passphrase].toString().empty()) {
    SSL_CTX_set_default_passwd_cb_userdata(ctx, this);
    SSL_CTX_set_default_passwd_cb(ctx, passwdCallback);
  }

  String cipherlist = m_context[s_ciphers].toString();
  if (cipherlist.empty()) {
    cipherlist = "DEFAULT";
  }
  SSL_CTX_set_cipher_list(ctx, cipherlist.data());

  String certfile = m_context[s_local_cert].toString();
  if (!certfile.empty()) {
    String resolved_path_buff = File::TranslatePath(certfile);
    if (!resolved_path_buff.empty()) {
      /* a certificate to use for authentication */
      if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff.data())
          != 1) {
        raise_warning("Unable to set local cert chain file `%s'; Check "
                      "that your cafile/capath settings include details of "
                      "your certificate and its issuer", certfile.data());
        return nullptr;
      }

      if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff.data(),
                                      SSL_FILETYPE_PEM) != 1) {
        raise_warning("Unable to set private key file `%s'",
                      resolved_path_buff.data());
        return nullptr;
      }

      SSL *tmpssl = SSL_new(ctx);
      X509 *cert = SSL_get_certificate(tmpssl);
      if (cert) {
        EVP_PKEY *key = X509_get_pubkey(cert);
        EVP_PKEY_copy_parameters(key, SSL_get_privatekey(tmpssl));
        EVP_PKEY_free(key);
      }
      SSL_free(tmpssl);

      if (!SSL_CTX_check_private_key(ctx)) {
        raise_warning("Private key does not match certificate!");
      }
    }
  }

  SSL *ssl = SSL_new(ctx);
  if (ssl) {
    SSL_set_ex_data(ssl, GetSSLExDataIndex(), this); /* map SSL => stream */
  }
  return ssl;
}
示例#10
0
EVP_PKEY* CertificateManager::loadKeyFromFile(const char* file) {
  SSL_CTX *context = SSL_CTX_new(SSLv23_server_method());
  SSL_CTX_use_PrivateKey_file(context, file, SSL_FILETYPE_PEM);

  return SSL_get_privatekey(SSL_new(context));
}
示例#11
0
static
int cert_stuff(struct connectdata *conn,
               SSL_CTX* ctx,
               char *cert_file,
               const char *cert_type,
               char *key_file,
               const char *key_type)
{
  struct SessionHandle *data = conn->data;
  int file_type;

  if(cert_file != NULL) {
    SSL *ssl;
    X509 *x509;

    if(data->set.key_passwd) {
#ifndef HAVE_USERDATA_IN_PWD_CALLBACK
      /*
       * If password has been given, we store that in the global
       * area (*shudder*) for a while:
       */
      size_t len = strlen(data->set.key_passwd);
      if(len < sizeof(global_passwd))
        memcpy(global_passwd, data->set.key_passwd, len+1);
#else
      /*
       * We set the password in the callback userdata
       */
      SSL_CTX_set_default_passwd_cb_userdata(ctx,
                                             data->set.key_passwd);
#endif
      /* Set passwd callback: */
      SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
    }

    file_type = do_file_type(cert_type);

    switch(file_type) {
    case SSL_FILETYPE_PEM:
      /* SSL_CTX_use_certificate_chain_file() only works on PEM files */
      if(SSL_CTX_use_certificate_chain_file(ctx,
                                            cert_file) != 1) {
        failf(data, "unable to set certificate file (wrong password?)");
        return 0;
      }
      break;

    case SSL_FILETYPE_ASN1:
      /* SSL_CTX_use_certificate_file() works with either PEM or ASN1, but
         we use the case above for PEM so this can only be performed with
         ASN1 files. */
      if(SSL_CTX_use_certificate_file(ctx,
                                      cert_file,
                                      file_type) != 1) {
        failf(data, "unable to set certificate file (wrong password?)");
        return 0;
      }
      break;
    case SSL_FILETYPE_ENGINE:
      failf(data, "file type ENG for certificate not implemented");
      return 0;

    default:
      failf(data, "not supported file type '%s' for certificate", cert_type);
      return 0;
    }

    file_type = do_file_type(key_type);

    switch(file_type) {
    case SSL_FILETYPE_PEM:
      if(key_file == NULL)
        /* cert & key can only be in PEM case in the same file */
        key_file=cert_file;
    case SSL_FILETYPE_ASN1:
      if(SSL_CTX_use_PrivateKey_file(ctx, key_file, file_type) != 1) {
        failf(data, "unable to set private key file: '%s' type %s\n",
              key_file, key_type?key_type:"PEM");
        return 0;
      }
      break;
    case SSL_FILETYPE_ENGINE:
#ifdef HAVE_OPENSSL_ENGINE_H
      {                         /* XXXX still needs some work */
        EVP_PKEY *priv_key = NULL;
        if(conn && conn->data && conn->data->engine) {
#ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
          UI_METHOD *ui_method = UI_OpenSSL();
#endif
          if(!key_file || !key_file[0]) {
            failf(data, "no key set to load from crypto engine\n");
            return 0;
          }
          /* the typecast below was added to please mingw32 */
          priv_key = (EVP_PKEY *)
            ENGINE_load_private_key(conn->data->engine,key_file,
#ifdef HAVE_ENGINE_LOAD_FOUR_ARGS
                                    ui_method,
#endif
                                    data->set.key_passwd);
          if(!priv_key) {
            failf(data, "failed to load private key from crypto engine\n");
            return 0;
          }
          if(SSL_CTX_use_PrivateKey(ctx, priv_key) != 1) {
            failf(data, "unable to set private key\n");
            EVP_PKEY_free(priv_key);
            return 0;
          }
          EVP_PKEY_free(priv_key);  /* we don't need the handle any more... */
        }
        else {
          failf(data, "crypto engine not set, can't load private key\n");
          return 0;
        }
      }
      break;
#else
      failf(data, "file type ENG for private key not supported\n");
      return 0;
#endif
    default:
      failf(data, "not supported file type for private key\n");
      return 0;
    }

    ssl=SSL_new(ctx);
    x509=SSL_get_certificate(ssl);

    /* This version was provided by Evan Jordan and is supposed to not
       leak memory as the previous version: */
    if(x509 != NULL) {
      EVP_PKEY *pktmp = X509_get_pubkey(x509);
      EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(ssl));
      EVP_PKEY_free(pktmp);
    }

    SSL_free(ssl);

    /* If we are using DSA, we can copy the parameters from
     * the private key */


    /* Now we know that a key and cert have been set against
     * the SSL context */
    if(!SSL_CTX_check_private_key(ctx)) {
      failf(data, "Private key does not match the certificate public key");
      return(0);
    }
#ifndef HAVE_USERDATA_IN_PWD_CALLBACK
    /* erase it now */
    memset(global_passwd, 0, sizeof(global_passwd));
#endif
  }
  return(1);
}
示例#12
0
文件: ssl.c 项目: Brilon314/jabberd2
        DH_free(dh);
        return NULL;
    }
    return dh;
}

static void sx_ssl_free_dh_params(void) {
    unsigned i;
    for (i = 0; i < sizeof(dhparams)/sizeof(dhparams[0]); i++) {
        DH_free(dhparams[i].dh);
        dhparams[i].dh = NULL;
    }
}

static DH *_sx_ssl_tmp_dh_callback(SSL *ssl, int export, int keylen) {
    EVP_PKEY *pkey = SSL_get_privatekey(ssl);
    int type = pkey ? EVP_PKEY_type(pkey->type) : EVP_PKEY_NONE;
    unsigned i;

    if (type == EVP_PKEY_RSA || type == EVP_PKEY_DSA)
        keylen = EVP_PKEY_bits(pkey);

    for (i = 0; i < sizeof(dhparams)/sizeof(dhparams[0]); i++) {
        if (keylen >= dhparams[i].minlen) {
            if (dhparams[i].dh == NULL)
                dhparams[i].dh = sx_ssl_make_dh_params(dhparams[i].get_prime, "2");
            return dhparams[i].dh;
        }
    }

    return NULL;
示例#13
0
void
tls_ctx_load_ecdh_params (struct tls_root_ctx *ctx, const char *curve_name
    )
{
#ifndef OPENSSL_NO_EC
  int nid = NID_undef;
  EC_KEY *ecdh = NULL;
  const char *sname = NULL;

  /* Generate a new ECDH key for each SSL session (for non-ephemeral ECDH) */
  SSL_CTX_set_options(ctx->ctx, SSL_OP_SINGLE_ECDH_USE);
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
  /* OpenSSL 1.0.2 and newer can automatically handle ECDH parameter loading */
  if (NULL == curve_name) {
    SSL_CTX_set_ecdh_auto(ctx->ctx, 1);
    return;
  }
#endif
  /* For older OpenSSL, we'll have to do the parameter loading on our own */
  if (curve_name != NULL)
    {
      /* Use user supplied curve if given */
      msg (D_TLS_DEBUG, "Using user specified ECDH curve (%s)", curve_name);
      nid = OBJ_sn2nid(curve_name);
    }
  else
    {
      /* Extract curve from key */
      EC_KEY *eckey = NULL;
      const EC_GROUP *ecgrp = NULL;
      EVP_PKEY *pkey = NULL;

      /* Little hack to get private key ref from SSL_CTX, yay OpenSSL... */
      SSL ssl;
      ssl.cert = ctx->ctx->cert;
      pkey = SSL_get_privatekey(&ssl);

      msg (D_TLS_DEBUG, "Extracting ECDH curve from private key");

      if (pkey != NULL && (eckey = EVP_PKEY_get1_EC_KEY(pkey)) != NULL &&
          (ecgrp = EC_KEY_get0_group(eckey)) != NULL)
        nid = EC_GROUP_get_curve_name(ecgrp);
    }

  /* Translate NID back to name , just for kicks */
  sname = OBJ_nid2sn(nid);
  if (sname == NULL) sname = "(Unknown)";

  /* Create new EC key and set as ECDH key */
  if (NID_undef == nid || NULL == (ecdh = EC_KEY_new_by_curve_name(nid)))
    {
      /* Creating key failed, fall back on sane default */
      ecdh = EC_KEY_new_by_curve_name(NID_secp384r1);
      const char *source = (NULL == curve_name) ?
          "extract curve from certificate" : "use supplied curve";
      msg (D_TLS_DEBUG_LOW,
          "Failed to %s (%s), using secp384r1 instead.", source, sname);
      sname = OBJ_nid2sn(NID_secp384r1);
    }

  if (!SSL_CTX_set_tmp_ecdh(ctx->ctx, ecdh))
    msg (M_SSLERR, "SSL_CTX_set_tmp_ecdh: cannot add curve");

  msg (D_TLS_DEBUG_LOW, "ECDH curve %s added", sname);

  EC_KEY_free(ecdh);
#else
  msg (M_DEBUG, "Your OpenSSL library was built without elliptic curve support."
		" Skipping ECDH parameter loading.");
#endif /* OPENSSL_NO_EC */
}
示例#14
0
static void setup_ssl(tcptest_t *item)
{
	static int ssl_init_complete = 0;
	struct servent *sp;
	char portinfo[100];
	X509 *peercert;
	char *certcn, *certstart, *certend;
	int err;
	strbuffer_t *sslinfo;
	char msglin[2048];

	item->sslrunning = 1;

	if (!ssl_init_complete) {
		/* Setup entropy */
		if (RAND_status() != 1) {
			char path[PATH_MAX];	/* Path for the random file */

			/* load entropy from files */
			RAND_load_file(RAND_file_name(path, sizeof (path)), -1);

			/* load entropy from egd sockets */
			RAND_egd("/var/run/egd-pool");
			RAND_egd("/dev/egd-pool");
			RAND_egd("/etc/egd-pool");
			RAND_egd("/var/spool/prngd/pool");

			/* shuffle $RANDFILE (or ~/.rnd if unset) */
			RAND_write_file(RAND_file_name(path, sizeof (path)));
			if (RAND_status() != 1) {
				errprintf("Failed to find enough entropy on your system");
				item->errcode = CONTEST_ESSL;
				return;
			}
		}

		SSL_load_error_strings();
		SSL_library_init();
		ssl_init_complete = 1;
	}

	if (item->sslctx == NULL) {
		switch (item->ssloptions->sslversion) {
		  case SSLVERSION_V2:
			item->sslctx = SSL_CTX_new(SSLv2_client_method()); break;
		  case SSLVERSION_V3:
			item->sslctx = SSL_CTX_new(SSLv3_client_method()); break;
		  case SSLVERSION_TLS1:
			item->sslctx = SSL_CTX_new(TLSv1_client_method()); break;
		  default:
			item->sslctx = SSL_CTX_new(SSLv23_client_method()); break;
		}

		if (!item->sslctx) {
			char sslerrmsg[256];

			ERR_error_string(ERR_get_error(), sslerrmsg);
			errprintf("Cannot create SSL context - IP %s, service %s: %s\n", 
				   inet_ntoa(item->addr.sin_addr), item->svcinfo->svcname, sslerrmsg);
			item->sslrunning = 0;
			item->errcode = CONTEST_ESSL;
			return;
		}

		/* Workaround SSL bugs */
		SSL_CTX_set_options(item->sslctx, SSL_OP_ALL);
		SSL_CTX_set_quiet_shutdown(item->sslctx, 1);

		/* Limit set of ciphers, if user wants to */
		if (item->ssloptions->cipherlist) 
			SSL_CTX_set_cipher_list(item->sslctx, item->ssloptions->cipherlist);

		if (item->ssloptions->clientcert) {
			int status;
			char certfn[PATH_MAX];

			SSL_CTX_set_default_passwd_cb(item->sslctx, cert_password_cb);
			SSL_CTX_set_default_passwd_cb_userdata(item->sslctx, item);

			sprintf(certfn, "%s/certs/%s", xgetenv("XYMONHOME"), item->ssloptions->clientcert);
			status = SSL_CTX_use_certificate_chain_file(item->sslctx, certfn);
			if (status == 1) {
				status = SSL_CTX_use_PrivateKey_file(item->sslctx, certfn, SSL_FILETYPE_PEM);
			}

			if (status != 1) {
				char sslerrmsg[256];

				ERR_error_string(ERR_get_error(), sslerrmsg);
				errprintf("Cannot load SSL client certificate/key %s: %s\n", 
					  item->ssloptions->clientcert, sslerrmsg);
				item->sslrunning = 0;
				item->errcode = CONTEST_ESSL;
				return;
			}
		}
	}

	if (item->ssldata == NULL) {
		item->ssldata = SSL_new(item->sslctx);
		if (!item->ssldata) {
			char sslerrmsg[256];

			ERR_error_string(ERR_get_error(), sslerrmsg);
			errprintf("SSL_new failed - IP %s, service %s: %s\n", 
				   inet_ntoa(item->addr.sin_addr), item->svcinfo->svcname, sslerrmsg);
			item->sslrunning = 0;
			SSL_CTX_free(item->sslctx);
			item->errcode = CONTEST_ESSL;
			return;
		}

		/* Verify that the client certificate is working */
		if (item->ssloptions->clientcert) {
			X509 *x509;

			x509 = SSL_get_certificate(item->ssldata);
			if(x509 != NULL) {
				EVP_PKEY *pktmp = X509_get_pubkey(x509);
				EVP_PKEY_copy_parameters(pktmp,SSL_get_privatekey(item->ssldata));
				EVP_PKEY_free(pktmp);
			}

			if (!SSL_CTX_check_private_key(item->sslctx)) {
				errprintf("Private/public key mismatch for certificate %s\n", item->ssloptions->clientcert);
				item->sslrunning = 0;
				item->errcode = CONTEST_ESSL;
				return;
			}
		}

		/* SSL setup is done. Now attach the socket FD to the SSL protocol handler */
		if (SSL_set_fd(item->ssldata, item->fd) != 1) {
			char sslerrmsg[256];

			ERR_error_string(ERR_get_error(), sslerrmsg);
			errprintf("Could not initiate SSL on connection - IP %s, service %s: %s\n", 
				   inet_ntoa(item->addr.sin_addr), item->svcinfo->svcname, sslerrmsg);
			item->sslrunning = 0;
			SSL_free(item->ssldata); 
			SSL_CTX_free(item->sslctx);
			item->errcode = CONTEST_ESSL;
			return;
		}
	}

	sp = getservbyport(item->addr.sin_port, "tcp");
	if (sp) {
		sprintf(portinfo, "%s (%d/tcp)", sp->s_name, item->addr.sin_port);
	}
	else {
		sprintf(portinfo, "%d/tcp", item->addr.sin_port);
	}
	if ((err = SSL_connect(item->ssldata)) != 1) {
		char sslerrmsg[256];

		switch (SSL_get_error (item->ssldata, err)) {
		  case SSL_ERROR_WANT_READ:
		  case SSL_ERROR_WANT_WRITE:
			item->sslrunning = SSLSETUP_PENDING;
			break;
		  case SSL_ERROR_SYSCALL:
			ERR_error_string(ERR_get_error(), sslerrmsg);
			/* Filter out the bogus SSL error */
			if (strstr(sslerrmsg, "error:00000000:") == NULL) {
				errprintf("IO error in SSL_connect to %s on host %s: %s\n",
					  portinfo, inet_ntoa(item->addr.sin_addr), sslerrmsg);
			}
			item->errcode = CONTEST_ESSL;
			item->sslrunning = 0; SSL_free(item->ssldata); SSL_CTX_free(item->sslctx);
			break;
		  case SSL_ERROR_SSL:
			ERR_error_string(ERR_get_error(), sslerrmsg);
			errprintf("Unspecified SSL error in SSL_connect to %s on host %s: %s\n",
				  portinfo, inet_ntoa(item->addr.sin_addr), sslerrmsg);
			item->errcode = CONTEST_ESSL;
			item->sslrunning = 0; SSL_free(item->ssldata); SSL_CTX_free(item->sslctx);
			break;
		  default:
			ERR_error_string(ERR_get_error(), sslerrmsg);
			errprintf("Unknown error %d in SSL_connect to %s on host %s: %s\n",
				  err, portinfo, inet_ntoa(item->addr.sin_addr), sslerrmsg);
			item->errcode = CONTEST_ESSL;
			item->sslrunning = 0; SSL_free(item->ssldata); SSL_CTX_free(item->sslctx);
			break;
		}

		return;
	}

	/* If we get this far, the SSL handshake has completed. So grab the certificate */
	peercert = SSL_get_peer_certificate(item->ssldata);
	if (!peercert) {
		errprintf("Cannot get peer certificate for %s on host %s\n",
			  portinfo, inet_ntoa(item->addr.sin_addr));
		item->errcode = CONTEST_ESSL;
		item->sslrunning = 0; SSL_free(item->ssldata); SSL_CTX_free(item->sslctx);
		return;
	}

	sslinfo = newstrbuffer(0);

	certcn = X509_NAME_oneline(X509_get_subject_name(peercert), NULL, 0);
	certstart = strdup(xymon_ASN1_UTCTIME(X509_get_notBefore(peercert)));
	certend = strdup(xymon_ASN1_UTCTIME(X509_get_notAfter(peercert)));

	snprintf(msglin, sizeof(msglin),
		"Server certificate:\n\tsubject:%s\n\tstart date: %s\n\texpire date:%s\n", 
		certcn, certstart, certend);
	addtobuffer(sslinfo, msglin);
	item->certsubject = strdup(certcn);
	item->certexpires = sslcert_expiretime(certend);
	xfree(certcn); xfree(certstart); xfree(certend);
	X509_free(peercert);

	/* We list the available ciphers in the SSL cert data */
	{
		int i;
		STACK_OF(SSL_CIPHER) *sk;

		addtobuffer(sslinfo, "\nAvailable ciphers:\n");
		sk = SSL_get_ciphers(item->ssldata);
		for (i=0; i<sk_SSL_CIPHER_num(sk); i++) {
			int b1, b2;
			char *cph;

			b1 = SSL_CIPHER_get_bits(sk_SSL_CIPHER_value(sk,i), &b2);
			cph = SSL_CIPHER_get_name(sk_SSL_CIPHER_value(sk,i));
			snprintf(msglin, sizeof(msglin), "Cipher %d: %s (%d bits)\n", i, cph, b1);
			addtobuffer(sslinfo, msglin);

			if ((item->mincipherbits == 0) || (b1 < item->mincipherbits)) item->mincipherbits = b1;
		}
	}

	item->certinfo = grabstrbuffer(sslinfo);
}
示例#15
0
SSL *SSL_new_from_context(SSL_CTX *ctx, stream *stream) /* {{{ */
{
    zval **val = NULL;
    char *cafile = NULL;
    char *capath = NULL;
    char *certfile = NULL;
    char *cipherlist = NULL;
    int ok = 1;

    ERR_clear_error();

    /* look at context options in the stream and set appropriate verification flags */
    if (GET_VER_OPT("verify_peer") && zval_is_true(*val)) {

        /* turn on verification callback */
        SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);

        /* CA stuff */
        GET_VER_OPT_STRING("cafile", cafile);
        GET_VER_OPT_STRING("capath", capath);

        if (cafile || capath) {
            if (!SSL_CTX_load_verify_locations(ctx, cafile, capath)) {
                error_docref(NULL, E_WARNING, "Unable to set verify locations `%s' `%s'", cafile, capath);
                return NULL;
            }
        }

        if (GET_VER_OPT("verify_depth")) {
            convert_to_long_ex(val);
            SSL_CTX_set_verify_depth(ctx, Z_LVAL_PP(val));
        }
    } else {
        SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
    }

    /* callback for the passphrase (for localcert) */
    if (GET_VER_OPT("passphrase")) {
        SSL_CTX_set_default_passwd_cb_userdata(ctx, stream);
        SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
    }

    GET_VER_OPT_STRING("ciphers", cipherlist);
    if (!cipherlist) {
        cipherlist = "DEFAULT";
    }
    if (SSL_CTX_set_cipher_list(ctx, cipherlist) != 1) {
        return NULL;
    }

    GET_VER_OPT_STRING("local_cert", certfile);
    if (certfile) {
        X509 *cert = NULL;
        EVP_PKEY *key = NULL;
        SSL *tmpssl;
        char resolved_path_buff[MAXPATHLEN];
        const char * private_key = NULL;

        if (VCWD_REALPATH(certfile, resolved_path_buff)) {
            /* a certificate to use for authentication */
            if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff) != 1) {
                error_docref(NULL, E_WARNING, "Unable to set local cert chain file `%s'; Check that your cafile/capath settings include details of your certificate and its issuer", certfile);
                return NULL;
            }
            GET_VER_OPT_STRING("local_pk", private_key);

            if (private_key) {
                char resolved_path_buff_pk[MAXPATHLEN];
                if (VCWD_REALPATH(private_key, resolved_path_buff_pk)) {
                    if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff_pk, SSL_FILETYPE_PEM) != 1) {
                        error_docref(NULL, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff_pk);
                        return NULL;
                    }
                }
            } else {
                if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff, SSL_FILETYPE_PEM) != 1) {
                    error_docref(NULL, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff);
                    return NULL;
                }
            }

            tmpssl = SSL_new(ctx);
            cert = SSL_get_certificate(tmpssl);

            if (cert) {
                key = X509_get_pubkey(cert);
                EVP_PKEY_copy_parameters(key, SSL_get_privatekey(tmpssl));
                EVP_PKEY_free(key);
            }
            SSL_free(tmpssl);

            if (!SSL_CTX_check_private_key(ctx)) {
                error_docref(NULL, E_WARNING, "Private key does not match certificate!");
            }
        }
    }
    if (ok) {
        SSL *ssl = SSL_new(ctx);

        if (ssl) {
            /* map SSL => stream */
            SSL_set_ex_data(ssl, ssl_stream_data_index, stream);
        }
        return ssl;
    }

    return NULL;
}
示例#16
0
static
int cert_stuff(struct connectdata *conn,
               char *cert_file,
               const char *cert_type,
               char *key_file,
               const char *key_type)
{
  struct SessionHandle *data = conn->data;
  int file_type;

  if (cert_file != NULL) {
    SSL *ssl;
    X509 *x509;

    if(data->set.key_passwd) {
#ifndef HAVE_USERDATA_IN_PWD_CALLBACK
      /*
       * If password has been given, we store that in the global
       * area (*shudder*) for a while:
       */
      strcpy(global_passwd, data->set.key_passwd);
#else
      /*
       * We set the password in the callback userdata
       */
      SSL_CTX_set_default_passwd_cb_userdata(conn->ssl.ctx,
                                             data->set.key_passwd);
#endif
      /* Set passwd callback: */
      SSL_CTX_set_default_passwd_cb(conn->ssl.ctx, passwd_callback);
    }

#if 0
    if (SSL_CTX_use_certificate_file(conn->ssl.ctx,
				     cert_file,
				     SSL_FILETYPE_PEM) != 1) {
      failf(data, "unable to set certificate file (wrong password?)");
      return(0);
    }
    if (key_file == NULL)
      key_file=cert_file;

    if (SSL_CTX_use_PrivateKey_file(conn->ssl.ctx,
				    key_file,
				    SSL_FILETYPE_PEM) != 1) {
      failf(data, "unable to set public key file");
      return(0);
    }
#else
    /* The '#ifdef 0' section above was removed on 17-dec-2001 */

    file_type = do_file_type(cert_type);

    switch(file_type) {
    case SSL_FILETYPE_PEM:
    case SSL_FILETYPE_ASN1:
      if (SSL_CTX_use_certificate_file(conn->ssl.ctx,
                                       cert_file,
                                       file_type) != 1) {
        failf(data, "unable to set certificate file (wrong password?)");
        return 0;
      }
      break;
    case SSL_FILETYPE_ENGINE:
      failf(data, "file type ENG for certificate not implemented");
      return 0;

    default:
      failf(data, "not supported file type '%s' for certificate", cert_type);
      return 0;
    }

    file_type = do_file_type(key_type);

    switch(file_type) {
    case SSL_FILETYPE_PEM:
      if (key_file == NULL)
        /* cert & key can only be in PEM case in the same file */
        key_file=cert_file;
    case SSL_FILETYPE_ASN1:
      if (SSL_CTX_use_PrivateKey_file(conn->ssl.ctx,
                                      key_file,
                                      file_type) != 1) {
        failf(data, "unable to set private key file\n");
        return 0;
      }
      break;
    case SSL_FILETYPE_ENGINE:
#ifdef HAVE_OPENSSL_ENGINE_H
      {                         /* XXXX still needs some work */
        EVP_PKEY *priv_key = NULL;
        if (conn && conn->data && conn->data->engine) {
          if (!key_file || !key_file[0]) {
            failf(data, "no key set to load from crypto engine\n");
            return 0;
          }
          priv_key = ENGINE_load_private_key(conn->data->engine,key_file,
                                             data->set.key_passwd);
          if (!priv_key) {
            failf(data, "failed to load private key from crypto engine\n");
            return 0;
          }
          if (SSL_CTX_use_PrivateKey(conn->ssl.ctx, priv_key) != 1) {
            failf(data, "unable to set private key\n");
            EVP_PKEY_free(priv_key);
            return 0;
          }
          EVP_PKEY_free(priv_key);  /* we don't need the handle any more... */
        }
        else {
          failf(data, "crypto engine not set, can't load private key\n");
          return 0;
        }
      }
#else
      failf(data, "file type ENG for private key not supported\n");
      return 0;
#endif
      break;
    default:
      failf(data, "not supported file type for private key\n");
      return 0;
    }

#endif
    
    ssl=SSL_new(conn->ssl.ctx);
    x509=SSL_get_certificate(ssl);
    
    if (x509 != NULL)
      EVP_PKEY_copy_parameters(X509_get_pubkey(x509),
			       SSL_get_privatekey(ssl));
    SSL_free(ssl);

    /* If we are using DSA, we can copy the parameters from
     * the private key */
		
    
    /* Now we know that a key and cert have been set against
     * the SSL context */
    if (!SSL_CTX_check_private_key(conn->ssl.ctx)) {
      failf(data, "Private key does not match the certificate public key");
      return(0);
    }
#ifndef HAVE_USERDATA_IN_PWD_CALLBACK    
    /* erase it now */
    memset(global_passwd, 0, sizeof(global_passwd));
#endif
  }
  return(1);
}