本文整理汇总了C++中SSL_set_fd函数的典型用法代码示例。如果您正苦于以下问题:C++ SSL_set_fd函数的具体用法?C++ SSL_set_fd怎么用?C++ SSL_set_fd使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了SSL_set_fd函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: OPENSSL_init_ssl
Result<SslFd> SslFd::init(SocketFd fd, CSlice host, CSlice cert_file, VerifyPeer verify_peer) {
#if TD_WINDOWS
return Status::Error("TODO");
#else
static bool init_openssl = [] {
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
return OPENSSL_init_ssl(0, nullptr) != 0;
#else
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
return OpenSSL_add_ssl_algorithms() != 0;
#endif
}();
CHECK(init_openssl);
openssl_clear_errors("Before SslFd::init");
CHECK(!fd.empty());
auto ssl_method =
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
TLS_client_method();
#else
SSLv23_client_method();
#endif
if (ssl_method == nullptr) {
return create_openssl_error(-6, "Failed to create an SSL client method");
}
auto ssl_ctx = SSL_CTX_new(ssl_method);
if (ssl_ctx == nullptr) {
return create_openssl_error(-7, "Failed to create an SSL context");
}
auto ssl_ctx_guard = ScopeExit() + [&]() { SSL_CTX_free(ssl_ctx); };
long options = 0;
#ifdef SSL_OP_NO_SSLv2
options |= SSL_OP_NO_SSLv2;
#endif
#ifdef SSL_OP_NO_SSLv3
options |= SSL_OP_NO_SSLv3;
#endif
SSL_CTX_set_options(ssl_ctx, options);
SSL_CTX_set_mode(ssl_ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
if (cert_file.empty()) {
SSL_CTX_set_default_verify_paths(ssl_ctx);
} else {
if (SSL_CTX_load_verify_locations(ssl_ctx, cert_file.c_str(), nullptr) == 0) {
return create_openssl_error(-8, "Failed to set custom cert file");
}
}
if (VERIFY_PEER && verify_peer == VerifyPeer::On) {
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, verify_callback);
if (VERIFY_DEPTH != -1) {
SSL_CTX_set_verify_depth(ssl_ctx, VERIFY_DEPTH);
}
} else {
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_NONE, nullptr);
}
// TODO(now): cipher list
string cipher_list;
if (SSL_CTX_set_cipher_list(ssl_ctx, cipher_list.empty() ? "DEFAULT" : cipher_list.c_str()) == 0) {
return create_openssl_error(-9, PSLICE("Failed to set cipher list \"%s\"", cipher_list.c_str()));
}
auto ssl_handle = SSL_new(ssl_ctx);
if (ssl_handle == nullptr) {
return create_openssl_error(-13, "Failed to create an SSL handle");
}
auto ssl_handle_guard = ScopeExit() + [&]() {
do_ssl_shutdown(ssl_handle);
SSL_free(ssl_handle);
};
#if OPENSSL_VERSION_NUMBER >= 0x10002000L
X509_VERIFY_PARAM *param = SSL_get0_param(ssl_handle);
/* Enable automatic hostname checks */
// TODO: X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
X509_VERIFY_PARAM_set_hostflags(param, 0);
X509_VERIFY_PARAM_set1_host(param, host.c_str(), 0);
#else
#warning DANGEROUS! HTTPS HOST WILL NOT BE CHECKED. INSTALL OPENSSL >= 1.0.2 OR IMPLEMENT HTTPS HOST CHECK MANUALLY
#endif
if (!SSL_set_fd(ssl_handle, fd.get_fd().get_native_fd())) {
return create_openssl_error(-14, "Failed to set fd");
}
#if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
auto host_str = host.str();
SSL_set_tlsext_host_name(ssl_handle, MutableCSlice(host_str).begin());
#endif
SSL_set_connect_state(ssl_handle);
ssl_ctx_guard.dismiss();
ssl_handle_guard.dismiss();
return SslFd(std::move(fd), ssl_handle, ssl_ctx);
#endif
}
示例2: _lm_ssl_begin
gboolean
_lm_ssl_begin (LmSSL *ssl, gint fd, const gchar *server, GError **error)
{
gint ssl_ret;
GIOStatus status;
LmSSLBase *base;
base = LM_SSL_BASE(ssl);
if (!ssl->ssl_ctx) {
g_set_error (error,
LM_ERROR, LM_ERROR_CONNECTION_OPEN,
"No SSL Context for OpenSSL");
return FALSE;
}
if (base->cipher_list) {
SSL_CTX_set_cipher_list(ssl->ssl_ctx, base->cipher_list);
}
if (base->ca_path) {
_lm_ssl_set_ca (ssl, base->ca_path);
} else {
SSL_CTX_set_default_verify_paths (ssl->ssl_ctx);
}
ssl->ssl = SSL_new(ssl->ssl_ctx);
if (ssl->ssl == NULL) {
g_log (LM_LOG_DOMAIN, LM_LOG_LEVEL_SSL, "SSL_new() == NULL");
g_set_error(error, LM_ERROR, LM_ERROR_CONNECTION_OPEN,
"SSL_new()");
return FALSE;
}
if (!SSL_set_fd (ssl->ssl, fd)) {
g_log (LM_LOG_DOMAIN, LM_LOG_LEVEL_SSL, "SSL_set_fd() failed");
g_set_error(error, LM_ERROR, LM_ERROR_CONNECTION_OPEN,
"SSL_set_fd()");
return FALSE;
}
/*ssl->bio = BIO_new_socket (fd, BIO_NOCLOSE);
if (ssl->bio == NULL) {
g_warning("BIO_new_socket() failed");
g_set_error(error, LM_ERROR, LM_ERROR_CONNECTION_OPEN,
"BIO_new_socket()");
return FALSE;
}
SSL_set_bio(ssl->ssl, ssl->bio, ssl->bio);*/
do {
ssl_ret = SSL_connect(ssl->ssl);
if (ssl_ret <= 0) {
status = ssl_io_status_from_return(ssl, ssl_ret);
if (status != G_IO_STATUS_AGAIN) {
ssl_print_state(ssl, "SSL_connect",
ssl_ret);
g_set_error(error, LM_ERROR,
LM_ERROR_CONNECTION_OPEN,
"SSL_connect()");
return FALSE;
}
}
} while (ssl_ret <= 0);
if (!ssl_verify_certificate (ssl, server)) {
g_set_error (error, LM_ERROR, LM_ERROR_CONNECTION_OPEN,
"*** SSL certificate verification failed");
return FALSE;
}
return TRUE;
}
示例3: main
int main(int argc, char **argv)
{
int sockfd, new_fd;
socklen_t len;
struct sockaddr_in my_addr, their_addr;
unsigned int myport, lisnum;
char buf[MAXBUF + 1];
SSL_CTX *ctx;
if (argv[1])
myport = atoi(argv[1]);
else
myport = 7838;
if (argv[2])
lisnum = atoi(argv[2]);
else
lisnum = 2;
/* SSL 库初始化 */
SSL_library_init();
/* 载入所有 SSL 算法 */
OpenSSL_add_all_algorithms();
/* 载入所有 SSL 错误消息 */
SSL_load_error_strings();
/* 以 SSL V2 和 V3 标准兼容方式产生一个 SSL_CTX ,即 SSL Content Text */
ctx = SSL_CTX_new(SSLv23_server_method());
/* 也可以用 SSLv2_server_method() 或 SSLv3_server_method() 单独表示 V2 或 V3标准 */
if (ctx == NULL) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 载入用户的数字证书, 此证书用来发送给客户端。 证书里包含有公钥 */
if (SSL_CTX_use_certificate_file(ctx, argv[3], SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 载入用户私钥 */
if (SSL_CTX_use_PrivateKey_file(ctx, argv[4], SSL_FILETYPE_PEM) <= 0) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 检查用户私钥是否正确 */
if (!SSL_CTX_check_private_key(ctx)) {
ERR_print_errors_fp(stdout);
exit(1);
}
/* 开启一个 socket 监听 */
if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
} else
printf("socket created\n");
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = PF_INET;
my_addr.sin_port = htons(myport);
my_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr))
== -1) {
perror("bind");
exit(1);
} else
printf("binded\n");
if (listen(sockfd, lisnum) == -1) {
perror("listen");
exit(1);
} else
printf("begin listen\n");
while (1) {
SSL *ssl;
len = sizeof(struct sockaddr);
/* 等待客户端连上来 */
if ((new_fd =
accept(sockfd, (struct sockaddr *) &their_addr,
&len)) == -1) {
perror("accept");
exit(errno);
} else
printf("server: got connection from %s, port %d, socket %d\n",
inet_ntoa(their_addr.sin_addr),
ntohs(their_addr.sin_port), new_fd);
/* 基于 ctx 产生一个新的 SSL */
ssl = SSL_new(ctx);
/* 将连接用户的 socket 加入到 SSL */
SSL_set_fd(ssl, new_fd);
/* 建立 SSL 连接 */
if (SSL_accept(ssl) == -1) {
perror("accept");
close(new_fd);
break;
}
/* 开始处理每个新连接上的数据收发 */
bzero(buf, MAXBUF + 1);
//.........这里部分代码省略.........
示例4: handle_connect_result
/* handle_connect_results assumes that select or poll have already shown the
* descriptor to be active */
void handle_connect_result(struct npool *ms, struct nevent *nse, enum nse_status status) {
int optval;
socklen_t optlen = sizeof(int);
struct niod *iod = nse->iod;
#if HAVE_OPENSSL
int sslerr;
int rc = 0;
int sslconnect_inprogress = nse->type == NSE_TYPE_CONNECT_SSL && nse->iod &&
(nse->sslinfo.ssl_desire == SSL_ERROR_WANT_READ ||
nse->sslinfo.ssl_desire == SSL_ERROR_WANT_WRITE);
#else
int sslconnect_inprogress = 0;
#endif
if (status == NSE_STATUS_TIMEOUT || status == NSE_STATUS_CANCELLED) {
nse->status = status;
nse->event_done = 1;
} else if (sslconnect_inprogress) {
/* Do nothing */
} else if (status == NSE_STATUS_SUCCESS) {
/* First we want to determine whether the socket really is connected */
if (getsockopt(iod->sd, SOL_SOCKET, SO_ERROR, (char *)&optval, &optlen) != 0)
optval = socket_errno(); /* Stupid Solaris */
switch (optval) {
case 0:
nse->status = NSE_STATUS_SUCCESS;
break;
/* EACCES can be caused by ICMPv6 dest-unreach-admin, or when a port is
blocked by Windows Firewall (WSAEACCES). */
case EACCES:
case ECONNREFUSED:
case EHOSTUNREACH:
case ENETDOWN:
case ENETUNREACH:
case ENETRESET:
case ECONNABORTED:
case ETIMEDOUT:
case EHOSTDOWN:
case ECONNRESET:
#ifdef WIN32
case WSAEADDRINUSE:
case WSAEADDRNOTAVAIL:
#endif
#ifndef WIN32
case EPIPE: /* Has been seen after connect on Linux. */
case ENOPROTOOPT: /* Also seen on Linux, perhaps in response to protocol unreachable. */
#endif
nse->status = NSE_STATUS_ERROR;
nse->errnum = optval;
break;
default:
/* I'd like for someone to report it */
fatal("Strange connect error from %s (%d): %s",
inet_ntop_ez(&iod->peer, iod->peerlen), optval,
socket_strerror(optval));
}
/* Now special code for the SSL case where the TCP connection was successful. */
if (nse->type == NSE_TYPE_CONNECT_SSL &&
nse->status == NSE_STATUS_SUCCESS) {
#if HAVE_OPENSSL
assert(ms->sslctx != NULL);
/* Reuse iod->ssl if present. If set, this is the second try at connection
without the SSL_OP_NO_SSLv2 option set. */
if (iod->ssl == NULL) {
iod->ssl = SSL_new(ms->sslctx);
if (!iod->ssl)
fatal("SSL_new failed: %s", ERR_error_string(ERR_get_error(), NULL));
}
#if HAVE_SSL_SET_TLSEXT_HOST_NAME
if (iod->hostname != NULL) {
if (SSL_set_tlsext_host_name(iod->ssl, iod->hostname) != 1)
fatal("SSL_set_tlsext_host_name failed: %s", ERR_error_string(ERR_get_error(), NULL));
}
#endif
/* Associate our new SSL with the connected socket. It will inherit the
* non-blocking nature of the sd */
if (SSL_set_fd(iod->ssl, iod->sd) != 1)
fatal("SSL_set_fd failed: %s", ERR_error_string(ERR_get_error(), NULL));
/* Event not done -- need to do SSL connect below */
nse->sslinfo.ssl_desire = SSL_ERROR_WANT_CONNECT;
#endif
} else {
/* This is not an SSL connect (in which case we are always done), or the
* TCP connect() underlying the SSL failed (in which case we are also done */
nse->event_done = 1;
}
} else {
fatal("Unknown status (%d)", status);
}
/* At this point the TCP connection is done, whether successful or not.
* Therefore decrease the read/write listen counts that were incremented in
//.........这里部分代码省略.........
示例5: echoclient_test
void echoclient_test(void* args)
{
SOCKET_T sockfd = 0;
FILE* fin = stdin;
FILE* fout = stdout;
int inCreated = 0;
int outCreated = 0;
char send[1024];
char reply[1024];
SSL_METHOD* method = 0;
SSL_CTX* ctx = 0;
SSL* ssl = 0;
int doDTLS = 0;
int sendSz;
int argc = 0;
char** argv = 0;
((func_args*)args)->return_code = -1; /* error state */
argc = ((func_args*)args)->argc;
argv = ((func_args*)args)->argv;
if (argc >= 2) {
fin = fopen(argv[1], "r");
inCreated = 1;
}
if (argc >= 3) {
fout = fopen(argv[2], "w");
outCreated = 1;
}
if (!fin) err_sys("can't open input file");
if (!fout) err_sys("can't open output file");
#ifdef CYASSL_DTLS
doDTLS = 1;
#endif
tcp_connect(&sockfd, yasslIP, yasslPort, doDTLS);
#if defined(CYASSL_DTLS)
method = DTLSv1_client_method();
#elif !defined(NO_TLS)
method = CyaSSLv23_client_method();
#else
method = SSLv3_client_method();
#endif
ctx = SSL_CTX_new(method);
#ifndef NO_FILESYSTEM
if (SSL_CTX_load_verify_locations(ctx, caCert, 0) != SSL_SUCCESS)
err_sys("can't load ca file, Please run from CyaSSL home dir");
#ifdef HAVE_ECC
if (SSL_CTX_load_verify_locations(ctx, eccCert, 0) != SSL_SUCCESS)
err_sys("can't load ca file, Please run from CyaSSL home dir");
#endif
#else
load_buffer(ctx, caCert, CYASSL_CA);
#endif
#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
/* don't use EDH, can't sniff tmp keys */
SSL_CTX_set_cipher_list(ctx, "AES256-SHA");
#endif
#ifdef OPENSSL_EXTRA
SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif
ssl = SSL_new(ctx);
SSL_set_fd(ssl, sockfd);
#if defined(USE_WINDOWS_API) && defined(CYASSL_DTLS) && defined(NO_MAIN_DRIVER)
/* let echoserver bind first, TODO: add Windows signal like pthreads does */
Sleep(100);
#endif
if (SSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed");
while (fgets(send, sizeof(send), fin)) {
sendSz = (int)strlen(send);
if (SSL_write(ssl, send, sendSz) != sendSz)
err_sys("SSL_write failed");
if (strncmp(send, "quit", 4) == 0) {
fputs("sending server shutdown command: quit!\n", fout);
break;
}
if (strncmp(send, "break", 5) == 0) {
fputs("sending server session close: break!\n", fout);
break;
}
while (sendSz) {
int got;
//.........这里部分代码省略.........
示例6: xrdp_tls_accept
int APP_CC
xrdp_tls_accept(struct xrdp_tls *self)
{
int connection_status;
long options = 0;
/**
* SSL_OP_NO_SSLv2:
*
* We only want SSLv3 and TLSv1, so disable SSLv2.
* SSLv3 is used by, eg. Microsoft RDC for Mac OS X.
*/
options |= SSL_OP_NO_SSLv2;
#if defined(SSL_OP_NO_COMPRESSION)
/**
* SSL_OP_NO_COMPRESSION:
*
* The Microsoft RDP server does not advertise support
* for TLS compression, but alternative servers may support it.
* This was observed between early versions of the FreeRDP server
* and the FreeRDP client, and caused major performance issues,
* which is why we're disabling it.
*/
options |= SSL_OP_NO_COMPRESSION;
#endif
/**
* SSL_OP_TLS_BLOCK_PADDING_BUG:
*
* The Microsoft RDP server does *not* support TLS padding.
* It absolutely needs to be disabled otherwise it won't work.
*/
options |= SSL_OP_TLS_BLOCK_PADDING_BUG;
/**
* SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:
*
* Just like TLS padding, the Microsoft RDP server does not
* support empty fragments. This needs to be disabled.
*/
options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
self->ctx = SSL_CTX_new(SSLv23_server_method());
/* set context options */
SSL_CTX_set_mode(self->ctx,
SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER |
SSL_MODE_ENABLE_PARTIAL_WRITE);
SSL_CTX_set_options(self->ctx, options);
SSL_CTX_set_read_ahead(self->ctx, 1);
if (self->ctx == NULL)
{
g_writeln("xrdp_tls_accept: SSL_CTX_new failed");
return 1;
}
if (SSL_CTX_use_RSAPrivateKey_file(self->ctx, self->key, SSL_FILETYPE_PEM)
<= 0)
{
g_writeln("xrdp_tls_accept: SSL_CTX_use_RSAPrivateKey_file failed");
return 1;
}
self->ssl = SSL_new(self->ctx);
if (self->ssl == NULL)
{
g_writeln("xrdp_tls_accept: SSL_new failed");
return 1;
}
if (SSL_use_certificate_file(self->ssl, self->cert, SSL_FILETYPE_PEM) <= 0)
{
g_writeln("xrdp_tls_accept: SSL_use_certificate_file failed");
return 1;
}
if (SSL_set_fd(self->ssl, self->trans->sck) < 1)
{
g_writeln("xrdp_tls_accept: SSL_set_fd failed");
return 1;
}
connection_status = SSL_accept(self->ssl);
if (connection_status <= 0)
{
if (xrdp_tls_print_error("SSL_accept", self->ssl, connection_status))
{
return 1;
}
}
g_writeln("xrdp_tls_accept: TLS connection accepted");
return 0;
}
示例7: irc_malloc
sock *socket_connect(sock_address *src, sock_address *dst, int flags)
{
sock *s = (sock *) irc_malloc(sizeof(sock));
struct sockaddr_storage ss;
int ss_len = sizeof(ss);
sock_address sa;
memset(s, 0, sizeof(sock));
#ifdef HAVE_SSL
if (flags & SOCKET_SSL)
{
if (ctx == NULL)
{
_socket_free(s);
return NULL;
}
s->sslstate = SSL_CONNECT;
}
#endif
s->flags = flags;
if (flags & SOCKET_DGRAM)
{
s->fd = socket(dst->addr->sa_family,SOCK_DGRAM,0);
}
else
{
s->fd = socket(dst->addr->sa_family,SOCK_STREAM,0);
}
if (s->fd == -1)
{
_socket_free(s);
return NULL;
}
fcntl(s->fd, F_SETFL, O_NONBLOCK);
if (src == NULL)
{
switch (dst->addr->sa_family)
{
case AF_INET:
src = local;
break;
#ifdef AF_INET6
case AF_INET6:
src = local6;
break;
#endif
}
}
if (src != NULL)
{
if (bind(s->fd, src->addr, src->len))
{
close(s->fd);
_socket_free(s);
return NULL;
}
}
if (connect(s->fd, dst->addr, dst->len) && errno != EINPROGRESS)
{
close(s->fd);
_socket_free(s);
return NULL;
}
s->raddr = address_copy(dst);
if (getsockname(s->fd, (struct sockaddr *) &ss, &ss_len))
{
close(s->fd);
_socket_free(s);
return NULL;
}
sa.addr = (struct sockaddr *) &ss;
sa.len = ss_len;
s->laddr = address_copy(&sa);
fds[s->fd] = s;
#ifdef HAVE_SSL
if (s->sslstate == SSL_CONNECT)
{
s->ssl = SSL_new(ctx);
SSL_set_fd (s->ssl, s->fd);
_socket_monitor(s->fd, MONITOR_WRITE);
}
#endif
return s;
}
示例8: test_TLSVerifyPeer
static void test_TLSVerifyPeer(void)
{
ASSERT_IF_NOT_INITIALIZED;
RESET_STATUS;
SSL *ssl = NULL;
ConnectionInfo *conn_info = NULL;
/*
* Open a socket and establish a tcp connection.
*/
struct sockaddr_in server_addr;
int server = 0;
int result = 0;
conn_info = ConnectionInfoNew();
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server = socket(AF_INET, SOCK_STREAM, 0);
assert_int_not_equal(-1, server);
server_addr.sin_family = AF_INET;
ConnectionInfoSetSocket(conn_info, server);
/* We should not use inet_addr, but it is easier for this particular case. */
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(8035);
/*
* Connect
*/
result = connect(server, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
assert_int_not_equal(-1, result);
/*
* Create a SSL instance
*/
ssl = SSL_new(SSLCLIENTCONTEXT);
assert_true(ssl != NULL);
SSL_set_fd(ssl, server);
/*
* Establish the TLS connection over the socket.
*/
result = SSL_connect(ssl);
assert_int_not_equal(-1, result);
/*
* Fill the remaining fields on ConnectionInfo
*/
ConnectionInfoSetProtocolVersion(conn_info, CF_PROTOCOL_TLS);
ConnectionInfoSetSSL(conn_info, ssl);
/*
* Fill in the structures we need for testing.
*/
X509 *certificate = NULL;
FILE *certificate_stream = fopen(server_certificate_template_public, "r");
certificate = PEM_read_X509(certificate_stream, (X509 **)NULL, NULL, NULL);
assert_true(certificate != NULL);
/*
* Start testing
*/
USE_MOCK(SSL_get_peer_certificate);
assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
USE_MOCK(X509_get_pubkey);
X509_GET_PUBKEY_RETURN(NULL);
assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
/*
* Due to the cleaning up we do after failing, we need to re read the certificate after
* very failure. The same is true for the public key.
*/
REREAD_CERTIFICATE(certificate_stream, certificate);
SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
EVP_PKEY *server_pubkey = NULL;
FILE *stream = NULL;
stream = fopen(server_name_template_public, "r");
RSA *pubkey = PEM_read_RSAPublicKey(stream, (RSA **)NULL, NULL, NULL);
server_pubkey = EVP_PKEY_new();
EVP_PKEY_assign_RSA(server_pubkey, pubkey);
X509_GET_PUBKEY_RETURN(server_pubkey);
USE_MOCK(EVP_PKEY_type);
EVP_PKEY_TYPE_RETURN(EVP_PKEY_DSA);
assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
EVP_PKEY_TYPE_RETURN(EVP_PKEY_RSA);
REREAD_CERTIFICATE(certificate_stream, certificate);
SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
X509_GET_PUBKEY_RETURN(server_pubkey);
USE_MOCK(X509_verify);
X509_VERIFY_RETURN(-1);
assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
X509_VERIFY_RETURN(0);
REREAD_CERTIFICATE(certificate_stream, certificate);
SSL_GET_PEER_CERTIFICATE_RETURN(certificate);
REREAD_PUBLIC_KEY(stream, pubkey, server_pubkey);
X509_GET_PUBKEY_RETURN(server_pubkey);
assert_int_equal(-1, TLSVerifyPeer(conn_info, "127.0.0.1", "root"));
X509_VERIFY_RETURN(1);
USE_MOCK(HavePublicKey);
//.........这里部分代码省略.........
示例9: test_TLSBasicIO
/*
* This test checks for the three basic operations:
* - TLSSend
* - TLSRecv
* - TLSRecvLine
* It is difficult to test each one separatedly, so we test all at once.
* The test consists on establishing a connection to our child process and then
* sending and receiving data. We switch between the original functions and the
* mock functions.
* We do not test SSL_new, SSL_accept and such because those will be covered by either
* the client or server tests.
*/
static void test_TLSBasicIO(void)
{
ASSERT_IF_NOT_INITIALIZED;
RESET_STATUS;
SSL *ssl = NULL;
char output_buffer[] = "this is a buffer";
int output_buffer_length = strlen(output_buffer);
char input_buffer[4096];
int result = 0;
/*
* Open a socket and establish a tcp connection.
*/
struct sockaddr_in server_addr;
int server = 0;
memset(&server_addr, 0, sizeof(struct sockaddr_in));
server = socket(AF_INET, SOCK_STREAM, 0);
assert_int_not_equal(-1, server);
server_addr.sin_family = AF_INET;
/* We should not use inet_addr, but it is easier for this particular case. */
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(8035);
/*
* Connect
*/
result = connect(server, (struct sockaddr *)&server_addr, sizeof(struct sockaddr_in));
assert_int_not_equal(-1, result);
/*
* Create a SSL instance
*/
ssl = SSL_new(SSLCLIENTCONTEXT);
assert_true(ssl != NULL);
SSL_set_fd(ssl, server);
/*
* Establish the TLS connection over the socket.
*/
result = SSL_connect(ssl);
assert_int_not_equal(-1, result);
/*
* Start testing. The first obvious thing to test is to send data.
*/
result = TLSSend(ssl, output_buffer, output_buffer_length);
assert_int_equal(result, output_buffer_length);
/*
* Good we sent data and the data was sent. Let's check what we get back
* by using TLSRecv.
*/
result = TLSRecv(ssl, input_buffer, output_buffer_length);
assert_int_equal(output_buffer_length, result);
input_buffer[output_buffer_length] = '\0';
assert_string_equal(output_buffer, input_buffer);
/*
* Brilliant! We transmitted and received data using simple communication.
* Let's try the line sending.
*/
char output_line_buffer[] = "hello\ngoodbye\n";
int output_line_buffer_length = strlen(output_line_buffer);
char output_just_hello[] = "hello";
int output_just_hello_length = strlen(output_just_hello);
result = TLSSend(ssl, output_line_buffer, output_line_buffer_length);
assert_int_equal(result, output_line_buffer_length);
result = TLSRecvLine(ssl, input_buffer, output_line_buffer_length);
/* The reply should be up to the first hello */
assert_int_equal(result, output_just_hello_length);
assert_string_equal(input_buffer, output_just_hello);
/*
* Basic check
*/
USE_MOCK(SSL_write);
USE_MOCK(SSL_read);
assert_int_equal(0, TLSSend(ssl, output_buffer, 0));
assert_int_equal(-1, TLSSend(ssl, output_buffer, output_buffer_length));
assert_int_equal(-1, TLSRecv(ssl, input_buffer, output_buffer_length));
RESET_STATUS;
/*
* Start replacing the functions inside to check that the logic works
* We start by testing TLSSend, then TLSRead and at last TLSRecvLine.
*/
USE_MOCK(SSL_write);
SSL_WRITE_RETURN(0);
assert_int_equal(0, TLSSend(ssl, output_buffer, output_buffer_length));
//.........这里部分代码省略.........
示例10: lws_server_socket_service_ssl
LWS_VISIBLE int
lws_server_socket_service_ssl(struct lws *wsi, lws_sockfd_type accept_fd)
{
struct lws_context *context = wsi->context;
struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
int n, m;
#if !defined(USE_WOLFSSL) && !defined(LWS_USE_POLARSSL) && !defined(LWS_USE_MBEDTLS)
BIO *bio;
#endif
if (!LWS_SSL_ENABLED(wsi->vhost))
return 0;
switch (wsi->mode) {
case LWSCM_SSL_INIT:
if (wsi->ssl)
lwsl_err("%s: leaking ssl\n", __func__);
if (accept_fd == LWS_SOCK_INVALID)
assert(0);
#if defined(LWS_USE_POLARSSL)
{
ssl_session *ssn;
int rc;
wsi->ssl = lws_zalloc(sizeof(ssl_context));
ssn = lws_zalloc(sizeof(ssl_session));
rc = ssl_init(wsi->ssl);
if (rc) {
lwsl_err("ssl_init failed\n");
goto fail;
}
ssl_set_endpoint(wsi->ssl, SSL_IS_SERVER);
ssl_set_authmode(wsi->ssl, SSL_VERIFY_OPTIONAL);
ssl_set_rng(wsi->ssl, urandom_bytes, NULL);
ssl_set_dbg(wsi->ssl, pssl_debug, NULL);
ssl_set_bio(wsi->ssl, net_recv, &wsi->sock, net_send, &wsi->sock);
ssl_set_ciphersuites(wsi->ssl, ciphers);
ssl_set_session(wsi->ssl, ssn);
ssl_set_ca_chain(wsi->ssl, &wsi->vhost->ssl_ctx->ca,
NULL, NULL);
ssl_set_own_cert_rsa(wsi->ssl,
&wsi->vhost->ssl_ctx->certificate,
&wsi->vhost->ssl_ctx->key);
// ssl_set_dh_param(wsi->ssl, my_dhm_P, my_dhm_G);
lwsl_err("%s: polarssl init done\n", __func__);
}
#else
#if defined(LWS_USE_MBEDTLS)
#else
wsi->ssl = SSL_new(wsi->vhost->ssl_ctx);
if (wsi->ssl == NULL) {
lwsl_err("SSL_new failed: %s\n",
ERR_error_string(lws_ssl_get_error(wsi, 0), NULL));
lws_decode_ssl_error();
if (accept_fd != LWS_SOCK_INVALID)
compatible_close(accept_fd);
goto fail;
}
SSL_set_ex_data(wsi->ssl,
openssl_websocket_private_data_index, wsi->vhost);
SSL_set_fd(wsi->ssl, accept_fd);
#endif
#endif
#ifdef USE_WOLFSSL
#ifdef USE_OLD_CYASSL
CyaSSL_set_using_nonblock(wsi->ssl, 1);
#else
wolfSSL_set_using_nonblock(wsi->ssl, 1);
#endif
#else
#if defined(LWS_USE_POLARSSL)
#else
#if defined(LWS_USE_MBEDTLS)
#else
SSL_set_mode(wsi->ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
bio = SSL_get_rbio(wsi->ssl);
if (bio)
BIO_set_nbio(bio, 1); /* nonblocking */
else
lwsl_notice("NULL rbio\n");
bio = SSL_get_wbio(wsi->ssl);
if (bio)
BIO_set_nbio(bio, 1); /* nonblocking */
else
lwsl_notice("NULL rbio\n");
#endif
//.........这里部分代码省略.........
示例11: echoclient_test
//.........这里部分代码省略.........
CyaSSL_CTX_set_psk_client_callback(ctx, my_psk_client_cb);
#ifdef HAVE_NULL_CIPHER
defaultCipherList = "PSK-NULL-SHA256";
#else
defaultCipherList = "PSK-AES128-CBC-SHA256";
#endif
if (CyaSSL_CTX_set_cipher_list(ctx,defaultCipherList) !=SSL_SUCCESS)
err_sys("client can't set cipher list 2");
#endif
}
#ifdef OPENSSL_EXTRA
SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif
#if defined(CYASSL_MDK_ARM)
CyaSSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, 0);
#endif
ssl = SSL_new(ctx);
if (doDTLS) {
SOCKADDR_IN_T addr;
build_addr(&addr, yasslIP, port, 1);
CyaSSL_dtls_set_peer(ssl, &addr, sizeof(addr));
tcp_socket(&sockfd, 1);
}
else {
tcp_connect(&sockfd, yasslIP, port, 0);
}
SSL_set_fd(ssl, sockfd);
#if defined(USE_WINDOWS_API) && defined(CYASSL_DTLS) && defined(NO_MAIN_DRIVER)
/* let echoserver bind first, TODO: add Windows signal like pthreads does */
Sleep(100);
#endif
if (SSL_connect(ssl) != SSL_SUCCESS) err_sys("SSL_connect failed");
while (fgets(msg, sizeof(msg), fin) != 0) {
sendSz = (int)strlen(msg);
if (SSL_write(ssl, msg, sendSz) != sendSz)
err_sys("SSL_write failed");
if (strncmp(msg, "quit", 4) == 0) {
fputs("sending server shutdown command: quit!\n", fout);
break;
}
if (strncmp(msg, "break", 5) == 0) {
fputs("sending server session close: break!\n", fout);
break;
}
#ifndef CYASSL_MDK_SHELL
while (sendSz) {
int got;
if ( (got = SSL_read(ssl, reply, sizeof(reply)-1)) > 0) {
reply[got] = 0;
fputs(reply, fout);
fflush(fout) ;
sendSz -= got;
示例12: server_test
//.........这里部分代码省略.........
if (doCliCertCheck && usePsk == 0) {
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER |
SSL_VERIFY_FAIL_IF_NO_PEER_CERT,0);
if (SSL_CTX_load_verify_locations(ctx, verifyCert, 0) != SSL_SUCCESS)
err_sys("can't load ca file, Please run from CyaSSL home dir");
}
#endif
#ifdef OPENSSL_EXTRA
SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack);
#endif
#if defined(CYASSL_SNIFFER) && !defined(HAVE_NTRU) && !defined(HAVE_ECC)
/* don't use EDH, can't sniff tmp keys */
if (cipherList == NULL) {
if (SSL_CTX_set_cipher_list(ctx, "AES256-SHA256") != SSL_SUCCESS)
err_sys("server can't set cipher list 3");
}
#endif
#ifdef HAVE_SNI
if (sniHostName) {
if (CyaSSL_CTX_UseSNI(ctx, CYASSL_SNI_HOST_NAME, sniHostName,
XSTRLEN(sniHostName)))
err_sys("UseSNI failed");
else
CyaSSL_CTX_SNI_SetOptions(ctx, CYASSL_SNI_HOST_NAME,
CYASSL_SNI_ABORT_ON_MISMATCH);
}
#endif
ssl = SSL_new(ctx);
if (ssl == NULL)
err_sys("unable to get SSL");
CyaSSL_set_quiet_shutdown(ssl, 1) ;
#ifdef HAVE_CRL
CyaSSL_EnableCRL(ssl, 0);
CyaSSL_LoadCRL(ssl, crlPemDir, SSL_FILETYPE_PEM, CYASSL_CRL_MONITOR |
CYASSL_CRL_START_MON);
CyaSSL_SetCRL_Cb(ssl, CRL_CallBack);
#endif
osDelay(5000) ;
tcp_accept(&sockfd, &clientfd, (func_args*)args, port, useAnyAddr, doDTLS);
if (!doDTLS)
CloseSocket(sockfd);
SSL_set_fd(ssl, clientfd);
if (usePsk == 0) {
#if !defined(NO_FILESYSTEM) && defined(OPENSSL_EXTRA)
CyaSSL_SetTmpDH_file(ssl, dhParam, SSL_FILETYPE_PEM);
#elif !defined(NO_CERTS)
SetDH(ssl); /* repick suites with DHE, higher priority than PSK */
#endif
}
osDelay(5000) ;
#ifndef CYASSL_CALLBACKS
if (nonBlocking) {
CyaSSL_set_using_nonblock(ssl, 1);
tcp_set_nonblocking(&clientfd);
NonBlockingSSL_Accept(ssl);
} else if (SSL_accept(ssl) != SSL_SUCCESS) {
int err = SSL_get_error(ssl, 0);
char buffer[80];
printf("error = %d, %s\n", err, ERR_error_string(err, buffer));
err_sys("SSL_accept failed");
}
#else
NonBlockingSSL_Accept(ssl);
#endif
showPeer(ssl);
osDelay(5000) ;
idx = SSL_read(ssl, input, sizeof(input)-1);
if (idx > 0) {
input[idx] = 0;
printf("Client message: %s\n", input);
}
else if (idx < 0) {
int readErr = SSL_get_error(ssl, 0);
if (readErr != SSL_ERROR_WANT_READ)
err_sys("SSL_read failed");
}
if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg))
err_sys("SSL_write failed");
SSL_shutdown(ssl);
SSL_free(ssl);
SSL_CTX_free(ctx);
CloseSocket(clientfd);
((func_args*)args)->return_code = 0;
#ifdef USE_CYASSL_MEMORY
if (trackMemory)
ShowMemoryTracker();
#endif /* USE_CYASSL_MEMORY */
return 0;
}
示例13: main_tls_client
int main_tls_client() {
SSL_CTX *ctx;
SSL *ssl;
int server = 0;
int ret;
if ( (ctx = SSL_CTX_new(SSLv23_client_method())) == NULL)
printf("Unable to create a new SSL context structure.\n");
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
// Force gcm(aes) mode
SSL_CTX_set_cipher_list(ctx, "ECDH-ECDSA-AES128-GCM-SHA256");
ssl = SSL_new(ctx);
server = create_socket();
SSL_set_fd(ssl, server);
if ( SSL_connect(ssl) != 1 ) {
printf("Error: Could not build a SSL session\n");
exit(-1);
}
// Start tests
clock_t start, end;
double cpu_time_used;
int filefd;
int bytes;
int totalbytes = 0;
bytes_recv = 0;
char buf[16384];
int res = 0;
int total_recv = 0;
start = clock();
filefd = open(test_data, O_RDONLY);
totalbytes = 0;
do {
bytes = read(filefd, buf, sizeof(buf));
totalbytes += bytes;
if (bytes > 0)
SSL_write(ssl, buf, bytes);
} while(bytes > 0);
close(filefd);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("OpenSSL receive time: %.02f\n", cpu_time_used);
res = 0;
total_recv = 0;
res = SSL_read(ssl, buf, 1);
total_recv += res;
if (res < 0) {
printf("SSL Read error: %i\n", res);
}
printf("Received openssl test data: %i %i\n", res, total_recv);
/* Kernel TLS tests */
int tfmfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (tfmfd == -1) {
perror("socket error:");
exit(-1);
}
struct sockaddr_alg sa = {
.salg_family = AF_ALG,
.salg_type = "tls", /* this selects the hash logic in the kernel */
.salg_name = "rfc5288(gcm(aes))" /* this is the cipher name */
};
if (bind(tfmfd, (struct sockaddr *)&sa, sizeof(sa)) == -1) {
perror("AF_ALG: bind failed");
close(tfmfd);
exit(-1);
}
int opfd = accept(tfmfd, NULL, 0);
if (opfd == -1) {
perror("accept:");
close(tfmfd);
exit(-1);
}
if (setsockopt(tfmfd, SOL_ALG, ALG_SET_AEAD_AUTHSIZE, NULL, 16)) {
perror("AF_ALG: set authsize failed\n");
exit(-1);
}
//.........这里部分代码省略.........
示例14: main
//.........这里部分代码省略.........
} else if (argc!=1) {
if (strcmp(argv[1], "-c") == 0) {
printf (gettext("\nnetUstad: Invalid Number Of Arguments\n\n"));
} else {
printf(gettext("\nnetUstad: Invalid Argument\n\n"));
}
exit(1);
}
/**********************/
/* Start Main Program */
/**********************/
readconfig(conffile);
if (setlocale (LC_ALL, (const char*) lc_all) == NULL) {
log_msg(mainlogfile, gettext("setlocale failed\n"), 1);
printf(gettext("setlocale failed\n"));
}
bindtextdomain (PACKAGE, PACKAGE_LOCALE_DIR);
textdomain ( PACKAGE );
nameoftty = ttyname(0);
daemonize();
#ifndef WITHOUT_SSL
ssl = nunetwork_init_ssl( nunetwork_init_ctx( cert_file, key_file) );
#endif
server_sock = startup(&port); /* Open Socket & Listen */
log_msg(mainlogfile, "<<<<<<<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>>>>>>>\n", 0);
snprintf(log_msg_text, sizeof(log_msg_text)-1, "netUstad-%s\n", NUVERSION);
log_msg(mainlogfile, log_msg_text, 0);
snprintf(log_msg_text, sizeof (log_msg_text)-1, "%s",
gettext("netUstad is started\n"));
log_msg(mainlogfile, log_msg_text, 1);
snprintf(log_msg_text, sizeof (log_msg_text)-1, gettext("\nListening port %d\n"), port);
log_msg(mainlogfile, log_msg_text, 0);
log_msg(mainlogfile, gettext("Ready for requests...\n\n"), 0);
snprintf(log_msg_text, sizeof(log_msg_text)-1, "netUstad-%s\n", NUVERSION);
log_msg(nameoftty, log_msg_text, 0);
snprintf(log_msg_text, sizeof (log_msg_text)-1,
gettext("\nnetUstad is started\nListening port %d\n"), port);
log_msg(nameoftty, log_msg_text, 0);
while (1) {
client_sock = accept(server_sock,
(struct sockaddr *) &client_name,
(socklen_t *)&client_name_len);
if (client_sock == -1)
continue;
#ifndef WITHOUT_SSL
SSL_set_fd(ssl, client_sock);
sslerror = SSL_accept(ssl);
if ( sslerror <= 0 ) {
sslerror= SSL_get_error(ssl, sslerror);
ERR_error_string(sslerror, log_msg_text);
log_msg(mainlogfile, log_msg_text, 1);
log_msg(mainlogfile, "\n",0);
SSL_shutdown(ssl);
SSL_free(ssl);
close(client_sock);
ssl = nunetwork_init_ssl(ctx);
continue;
}
request = nunetwork_getheaders(ssl, header_buf, nu_acceptedheaders);
if (request > 0)
accept_request(ssl, header_buf);
else if (request==-2 || request==0)
bad_request(ssl);
nunetwork_close(ssl);
#else
request = nunetwork_getheaders(client_sock, header_buf, nu_acceptedheaders);
if (request > 0)
accept_request(client_sock, header_buf);
else if (request==-2 || request==0 )
bad_request(ssl);
nunetwork_close(client_sock);
#endif
}
#ifndef WITHOUT_SSL
SSL_shutdown(ssl);
SSL_free(ssl);
SSL_CTX_free(ctx);
#else
close(server_sock);
#endif
return (0);
}
示例15: np_net_ssl_init_with_hostname_version_and_cert
int np_net_ssl_init_with_hostname_version_and_cert(int sd, char *host_name, int version, char *cert, char *privkey) {
SSL_METHOD *method = NULL;
switch (version) {
case 0: /* Deafult to auto negotiation */
method = SSLv23_client_method();
break;
case 1: /* TLSv1 protocol */
method = TLSv1_client_method();
break;
case 2: /* SSLv2 protocol */
#if defined(USE_GNUTLS) || defined(OPENSSL_NO_SSL2)
printf(("%s\n", _("CRITICAL - SSL protocol version 2 is not supported by your SSL library.")));
return STATE_CRITICAL;
#else
method = SSLv2_client_method();
#endif
break;
case 3: /* SSLv3 protocol */
method = SSLv3_client_method();
break;
default: /* Unsupported */
printf("%s\n", _("CRITICAL - Unsupported SSL protocol version."));
return STATE_CRITICAL;
}
if (!initialized) {
/* Initialize SSL context */
SSLeay_add_ssl_algorithms();
SSL_load_error_strings();
OpenSSL_add_all_algorithms();
initialized = 1;
}
if ((c = SSL_CTX_new(method)) == NULL) {
printf("%s\n", _("CRITICAL - Cannot create SSL context."));
return STATE_CRITICAL;
}
if (cert && privkey) {
SSL_CTX_use_certificate_file(c, cert, SSL_FILETYPE_PEM);
SSL_CTX_use_PrivateKey_file(c, privkey, SSL_FILETYPE_PEM);
if (!SSL_CTX_check_private_key(c)) {
printf ("%s\n", _("CRITICAL - Private key does not seem to match certificate!\n"));
return STATE_CRITICAL;
}
}
#ifdef SSL_OP_NO_TICKET
SSL_CTX_set_options(c, SSL_OP_NO_TICKET);
#endif
SSL_CTX_set_mode(c, SSL_MODE_AUTO_RETRY);
if ((s = SSL_new(c)) != NULL) {
#ifdef SSL_set_tlsext_host_name
if (host_name != NULL)
SSL_set_tlsext_host_name(s, host_name);
#endif
SSL_set_fd(s, sd);
if (SSL_connect(s) == 1) {
return OK;
} else {
printf("%s\n", _("CRITICAL - Cannot make SSL connection."));
# ifdef USE_OPENSSL /* XXX look into ERR_error_string */
ERR_print_errors_fp(stdout);
# endif /* USE_OPENSSL */
}
} else {
printf("%s\n", _("CRITICAL - Cannot initiate SSL handshake."));
}
return STATE_CRITICAL;
}