BIO *Connect_SSL(char *hostname, int port) { //BIO *bio = NULL; char bio_addr[BUF_MAX] = { 0 }; snprintf(bio_addr, sizeof(bio_addr), "%s:%d", hostname, port); SSL_library_init(); SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method()); SSL *ssl = NULL; bio = BIO_new_ssl_connect(ctx); if (bio == NULL) { Error("BIO_new_ssl_connect"); } BIO_get_ssl(bio, &ssl); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); BIO_set_conn_hostname(bio, bio_addr); if (BIO_do_connect(bio) <= 0) { Error("SSL Unable to connect"); } return bio; }
/** setup SSL on the connection */ static SSL* setup_ssl(SSL_CTX* ctx, int fd) { SSL* ssl; X509* x; int r; ssl = SSL_new(ctx); if(!ssl) ssl_err("could not SSL_new"); SSL_set_connect_state(ssl); (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); if(!SSL_set_fd(ssl, fd)) ssl_err("could not SSL_set_fd"); while(1) { ERR_clear_error(); if( (r=SSL_do_handshake(ssl)) == 1) break; r = SSL_get_error(ssl, r); if(r != SSL_ERROR_WANT_READ && r != SSL_ERROR_WANT_WRITE) ssl_err("SSL handshake failed"); /* wants to be called again */ } /* check authenticity of server */ if(SSL_get_verify_result(ssl) != X509_V_OK) ssl_err("SSL verification failed"); x = SSL_get_peer_certificate(ssl); if(!x) ssl_err("Server presented no peer certificate"); X509_free(x); return ssl; }
static Pfd* opensslconnect(char *host) { Pfd *pfd; BIO *sbio; SSL_CTX *ctx; SSL *ssl; static int didinit; char buf[1024]; if(!didinit){ httpsinit(); didinit = 1; } ctx = SSL_CTX_new(SSLv23_client_method()); sbio = BIO_new_ssl_connect(ctx); BIO_get_ssl(sbio, &ssl); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); snprint(buf, sizeof buf, "%s:https", host); BIO_set_conn_hostname(sbio, buf); if(BIO_do_connect(sbio) <= 0 || BIO_do_handshake(sbio) <= 0){ ERR_error_string_n(ERR_get_error(), buf, sizeof buf); BIO_free_all(sbio); werrstr("openssl: %s", buf); return nil; } pfd = emalloc(sizeof *pfd); pfd->sbio = sbio; return pfd; }
void CSSLClientAsync::OnConnect(BOOL bConnected) { //无论是否连接成功,都认为已经判断结束 SetCheckConnect(FALSE); //连接完毕,则删除写/错误事件的注册,改成读事件 m_pio->Remove_WriteEvent(this); if (TRUE == bConnected) { SOCKET_IO_INFO("socket connect successed, remote ip: %s, port: %d.", GetRemoteIP(), GetRemotePort()); DoConnect(GetSocketID()); SSL_set_mode(GetSSL(), SSL_MODE_AUTO_RETRY); if (SSL_set_fd(GetSSL(), GetSocket()) != 1) { SOCKET_IO_ERROR("ssl set fd failed"); DoException(GetSocketID(), SOCKET_IO_SSL_CONNECT_FAILED); return; } SSLConnect(); } else { SOCKET_IO_ERROR("socket connect failed, remote ip: %s, port: %d.", GetRemoteIP(), GetRemotePort()); DoException(GetSocketID(), SOCKET_IO_TCP_CONNECT_FAILED); } }
BIO* connect_encrypted(char* host_and_port, char* store_path, char store_type, SSL_CTX** ctx, SSL** ssl) { BIO* bio = NULL; int r = 0; *ctx = SSL_CTX_new(SSLv23_client_method()); *ssl = NULL; if (store_type == 'f') r = SSL_CTX_load_verify_locations(*ctx, store_path, NULL); else r = SSL_CTX_load_verify_locations(*ctx, NULL, store_path); if (r == 0) { return NULL; } bio = BIO_new_ssl_connect(*ctx); BIO_get_ssl(bio, ssl); if (!(*ssl)) { return NULL; } SSL_set_mode(*ssl, SSL_MODE_AUTO_RETRY); BIO_set_conn_hostname(bio, host_and_port); if (BIO_do_connect(bio) < 1) { return NULL; } return bio; }
/* The first line specifiy some settings in the ctx and ssl object: SSL_OP_ALL: enables all work around codes SSL_OP_NO_SSLv2: no SSLv2 connections are allowed (this should fail anyway because only TLSv1 connection are allowed) SSL_OP_SINGLE_DH_USE: the server generates a new private key for each new connection SSL_VERIFY_PEER: asks the client for a certificate SSL_VERIFY_FAIL_IF_NO_PEER_CERT: if the client doesn't present a cert the connection gets terminated CIPHER_LIST: is defined in ssl_server.h (look there for a detailed description) After setting up these things the bio object will be created and a ssl object assigned. Then the ssl engine mode is set to SSL_MODE_AUTO_RETRY. All available modes are: SSL_MODE_ENABLE_PARTIAL_WRITE: Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success when just a single record has been written). When not set (the default), SSL_write() will only report success once the complete chunk was written. Once SSL_write() returns with r, r bytes have been successfully written and the next call to SSL_write() must only send the n-r bytes left, imitating the behaviour of write(). SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER: Make it possible to retry SSL_write() with changed buffer location (the buffer contents must stay the same). This is not the default to avoid the misconception that non-blocking SSL_write() behaves like non-blocking write(). SSL_MODE_AUTO_RETRY: Never bother the application with retries if the transport is blocking. If a renegotiation take place during normal operation, a ssl_read(3) or ssl_write(3) would return with -1 and indicate the need to retry with SSL_ERROR_WANT_READ . In a non-blocking environment applications must be prepared to handle incomplete read/write operations. In a blocking environment, applications are not always prepared to deal with read/write operations returning without success report. The flag SSL_MODE_AUTO_RETRY will cause read/write operations to only return after the handshake and successful completion. The server contains 3 bio objects: bio, abio and out. 'bio' contains the context, 'abio' binds to the socket and 'out' is the established connection. */ void SSL_Server::bind(){ SSL_CTX_set_verify(getCTX(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); SSL_CTX_set_options(getCTX(), SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_SINGLE_DH_USE); SSL_CTX_set_tmp_dh_callback(getCTX(), tmp_dh_callback); if(SSL_CTX_set_cipher_list(getCTX(), CIPHER_LIST) != 1) msgHandler->error("setting cipher list failed (no valid ciphers)", CRITICAL); msgHandler->debug("trying to set context to bio"); bio = BIO_new_ssl(getCTX(), 0); if(bio == NULL){ string error("Cannot set context to bio "); error.append(getSocket()); error.append("\nSSL_ERROR: "); error.append(ERR_reason_error_string(ERR_get_error())); msgHandler->error(error, CRITICAL); } else msgHandler->debug("set context to bio successful"); BIO_get_ssl(bio, &ssl); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); msgHandler->debug("trying to bind to socket"); abio = BIO_new_accept((char*)getSocket().c_str()); BIO_set_accept_bios(abio, bio); if(BIO_do_accept(abio) <= 0){ string error("Bind to socket "); error.append(getSocket()); error.append(" failed.\nSSL_ERROR: "); error.append(ERR_reason_error_string(ERR_get_error())); msgHandler->error(error, CRITICAL); } else msgHandler->log("bind to socket successful"); }
bool OpenSSL::init() { if( m_initLib ) SSL_library_init(); SSL_COMP_add_compression_method( 1, COMP_zlib() ); m_ctx = SSL_CTX_new( TLSv1_client_method() ); if( !m_ctx ) return false; if( !SSL_CTX_set_cipher_list( m_ctx, "HIGH:MEDIUM:AES:@STRENGTH" ) ) return false; m_ssl = SSL_new( m_ctx ); SSL_set_connect_state( m_ssl ); if( !BIO_new_bio_pair( &m_ibio, 0, &m_nbio, 0 ) ) return false; SSL_set_bio( m_ssl, m_ibio, m_ibio ); SSL_set_mode( m_ssl, SSL_MODE_AUTO_RETRY ); m_valid = true; return true; }
OpenSSL::OpenSSL( TLSHandler *th, const std::string& server ) : TLSBase( th, server ), m_ssl( 0 ), m_ctx( 0 ), m_buf( 0 ), m_bufsize( 17000 ) { m_buf = (char*)calloc( m_bufsize + 1, sizeof( char ) ); SSL_library_init(); SSL_COMP_add_compression_method( 1, COMP_zlib() ); m_ctx = SSL_CTX_new( TLSv1_client_method() ); if( !m_ctx ) return; if( !SSL_CTX_set_cipher_list( m_ctx, "HIGH:MEDIUM:AES:@STRENGTH" ) ) return; m_ssl = SSL_new( m_ctx ); SSL_set_connect_state( m_ssl ); if( !BIO_new_bio_pair( &m_ibio, 0, &m_nbio, 0 ) ) { return; } SSL_set_bio( m_ssl, m_ibio, m_ibio ); SSL_set_mode( m_ssl, SSL_MODE_AUTO_RETRY ); }
SSLClient::SSLClient(int sock, SSLClient::ERole role, const SSLConfig &ctx) throw(SocketConnectionClosed, SSLError) : SSLSocket(ctx), TCPSocket::TCPSocket(sock) { m_SSL = SSL_new(m_CTX); SSL_set_mode(m_SSL, SSL_MODE_AUTO_RETRY); m_BIO = BIO_new_socket(GetSocket(), BIO_NOCLOSE); SSL_set_bio(m_SSL, m_BIO, m_BIO); switch(role) { case SSLClient::CLIENT: if(SSL_connect(m_SSL) < 0) throw SSLError("Connect error"); break; case SSLClient::SERVER_FORCE_CERT: SSL_set_verify(m_SSL, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0); case SSLClient::SERVER: { if(SSL_accept(m_SSL) < 0) throw SSLError("Accept error"); } break; } }
int AXIS2_CALL axis2_ssl_stream_skip( axutil_stream_t * stream, const axutil_env_t * env, int count) { ssl_stream_impl_t *stream_impl = NULL; axis2_char_t *tmp_buffer = NULL; int len = -1; if (count < 0) { return -1; } stream_impl = AXIS2_INTF_TO_IMPL(stream); tmp_buffer = AXIS2_MALLOC(env->allocator, (size_t)count * sizeof(axis2_char_t)); if (tmp_buffer == NULL) { AXIS2_HANDLE_ERROR(env, AXIS2_ERROR_NO_MEMORY, AXIS2_FAILURE); return -1; } SSL_set_mode(stream_impl->ssl, SSL_MODE_AUTO_RETRY); len = SSL_read(stream_impl->ssl, tmp_buffer, count); AXIS2_FREE(env->allocator, tmp_buffer); return len; }
int AXIS2_CALL axis2_ssl_stream_read( axutil_stream_t * stream, const axutil_env_t * env, void *buffer, size_t count) { ssl_stream_impl_t *stream_impl = NULL; int data_read = -1; int len = -1; stream_impl = AXIS2_INTF_TO_IMPL(stream); SSL_set_mode(stream_impl->ssl, SSL_MODE_AUTO_RETRY); data_read = SSL_read(stream_impl->ssl, buffer, (int)count); /* We are sure that the difference lies within the int range */ switch (SSL_get_error(stream_impl->ssl, data_read)) { case SSL_ERROR_NONE: len = data_read; break; case SSL_ERROR_ZERO_RETURN: len = -1; break; case SSL_ERROR_SYSCALL: AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, "SSL Error: Premature close"); len = -1; break; default: len = -1; break; } return len; }
tnet_dtls_socket_handle_t* tnet_dtls_socket_create(struct tnet_socket_s* wrapped_sock, struct ssl_ctx_st* ssl_ctx) { #if !HAVE_OPENSSL || !HAVE_OPENSSL_DTLS TSK_DEBUG_ERROR("OpenSSL or DTLS not enabled"); return tsk_null; #else tnet_dtls_socket_t* socket; if (!wrapped_sock || !ssl_ctx){ TSK_DEBUG_ERROR("Invalid parameter"); return tsk_null; } if ((socket = tsk_object_new(tnet_dtls_socket_def_t))) { const tsk_bool_t set_mtu = TNET_SOCKET_TYPE_IS_DGRAM(wrapped_sock->type) || 1; //!\ This is required even if the local transport is TCP/TLS because the relayed (TURN) transport could be UDP socket->wrapped_sock = tsk_object_ref(wrapped_sock); if (!(socket->ssl = SSL_new(ssl_ctx))) { TSK_DEBUG_ERROR("SSL_new(CTX) failed [%s]", ERR_error_string(ERR_get_error(), tsk_null)); TSK_OBJECT_SAFE_FREE(socket); return tsk_null; } if (set_mtu) { SSL_set_options(socket->ssl, SSL_OP_NO_QUERY_MTU); SSL_set_mtu(socket->ssl, TNET_DTLS_MTU - 28); socket->ssl->d1->mtu = TNET_DTLS_MTU - 28; } if (!(socket->rbio = BIO_new(BIO_s_mem())) || !(socket->wbio = BIO_new(BIO_s_mem()))){ TSK_DEBUG_ERROR("BIO_new_socket(%d) failed [%s]", socket->wrapped_sock->fd, ERR_error_string(ERR_get_error(), tsk_null)); if (socket->rbio){ BIO_free(socket->rbio); } if (socket->wbio){ BIO_free(socket->wbio); } TSK_OBJECT_SAFE_FREE(socket); return tsk_null; } BIO_set_mem_eof_return(socket->rbio, -1); BIO_set_mem_eof_return(socket->wbio, -1); SSL_set_bio(socket->ssl, socket->rbio, socket->wbio); SSL_set_mode(socket->ssl, SSL_MODE_AUTO_RETRY); SSL_set_read_ahead(socket->ssl, 1); if (set_mtu) { BIO_ctrl(SSL_get_wbio(socket->ssl), BIO_CTRL_DGRAM_SET_MTU, TNET_DTLS_MTU - 28, NULL); } if ((socket->verify_peer = (SSL_CTX_get_verify_mode(ssl_ctx) != SSL_VERIFY_NONE))){ TSK_DEBUG_INFO("SSL cert verify: ON"); socket->verify_peer = tsk_true; SSL_set_verify(socket->ssl, (SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT), _tnet_dtls_verify_cert); } else { TSK_DEBUG_ERROR("Verity not enabled"); } SSL_set_app_data(socket->ssl, socket); } return socket; #endif }
int main() { SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); SSL_CTX *ctx = SSL_CTX_new(SSLv23_client_method()); if (ctx == NULL) { printf("SSL_CTX_new err func:%s\n reaseon:%s", ERR_func_error_string(ERR_get_error()), ERR_reason_error_string(ERR_get_error())); exit(1); } //加载可信任证书库 if (0 == SSL_CTX_load_verify_locations(ctx, "./push_cer.pem", NULL)) { printf("err func:%s\n reaseon:%s", ERR_func_error_string(ERR_get_error()), ERR_reason_error_string(ERR_get_error())); ERR_print_errors_fp(stdout); exit(1); } //set BIO BIO *bio = BIO_new_ssl_connect(ctx); if (bio == NULL) { printf("err func:%s\n", ERR_func_error_string(ERR_get_error())); ERR_print_errors_fp(stdout); exit(1); } SSL *ssl; BIO_get_ssl(bio, &ssl); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); //open safe connect BIO_set_conn_hostname(bio, "gateway.sandbox.push.apple.com:2195"); //verify connect ok if (BIO_do_connect(bio) <= 0) { ERR_print_errors_fp(stdout); exit(1); } if (SSL_get_verify_result(ssl) != X509_V_OK) { printf("SSL_get_verify_result not success\n"); } char buf[MAXBUF]; char *json = "{\"aps\":{\"badge\":123}}"; sendPayload(bio, token, json, strlen(json)); int ret = BIO_read(bio, buf, MAXBUF); if (ret <= 0) { printf("BIO_read return 0\n"); } SSL_CTX_free(ctx); BIO_free_all(bio); return 0; }
/** * Create a new TLS/SSL object and mark it as new. */ static int meth_create(lua_State *L) { p_ssl ssl; int mode = lsec_getmode(L, 1); SSL_CTX *ctx = lsec_checkcontext(L, 1); if (mode == LSEC_MODE_INVALID) { lua_pushnil(L); lua_pushstring(L, "invalid mode"); return 2; } ssl = (p_ssl)lua_newuserdata(L, sizeof(t_ssl)); if (!ssl) { lua_pushnil(L); lua_pushstring(L, "error creating SSL object"); return 2; } ssl->ssl = SSL_new(ctx); if (!ssl->ssl) { lua_pushnil(L); lua_pushfstring(L, "error creating SSL object (%s)", ERR_reason_error_string(ERR_get_error())); return 2; } ssl->state = LSEC_STATE_NEW; SSL_set_fd(ssl->ssl, (int)SOCKET_INVALID); SSL_set_mode(ssl->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #if defined(SSL_MODE_RELEASE_BUFFERS) SSL_set_mode(ssl->ssl, SSL_MODE_RELEASE_BUFFERS); #endif if (mode == LSEC_MODE_SERVER) SSL_set_accept_state(ssl->ssl); else SSL_set_connect_state(ssl->ssl); io_init(&ssl->io, (p_send)ssl_send, (p_recv)ssl_recv, (p_error) ssl_ioerror, ssl); timeout_init(&ssl->tm, -1, -1); buffer_init(&ssl->buf, &ssl->io, &ssl->tm); luaL_getmetatable(L, "SSL:Connection"); lua_setmetatable(L, -2); return 1; }
/* libev read handler for the bound socket. Socket is accepted, * the proxystate is allocated and initalized, and we're off the races * connecting to the backend */ static void handle_accept(struct ev_loop *loop, ev_io *w, int revents) { (void) revents; struct sockaddr_storage addr; socklen_t sl = sizeof(addr); int client = accept(w->fd, (struct sockaddr *) &addr, &sl); if (client == -1) { assert(errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN); return; } setnonblocking(client); int back = create_back_socket(); if (back == -1) { close(client); perror("{backend-connect}"); return; } SSL_CTX * ctx = (SSL_CTX *)w->data; SSL *ssl = SSL_new(ctx); SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE); SSL_set_accept_state(ssl); SSL_set_fd(ssl, client); proxystate *ps = (proxystate *)malloc(sizeof(proxystate)); ps->fd_up = client; ps->fd_down = back; ps->ssl = ssl; ps->want_shutdown = 0; ps->remote_ip = addr; ringbuffer_init(&ps->ring_up); ringbuffer_init(&ps->ring_down); /* set up events */ ev_io_init(&ps->ev_r_up, client_read, client, EV_READ); ev_io_init(&ps->ev_w_up, client_write, client, EV_WRITE); ev_io_init(&ps->ev_r_handshake, client_handshake, client, EV_READ); ev_io_init(&ps->ev_w_handshake, client_handshake, client, EV_WRITE); ev_io_init(&ps->ev_w_down, handle_connect, back, EV_WRITE); ev_io_start(loop, &ps->ev_w_down); ps->ev_r_up.data = ps; ps->ev_w_up.data = ps; ps->ev_r_down.data = ps; ps->ev_w_down.data = ps; ps->ev_r_handshake.data = ps; ps->ev_w_handshake.data = ps; }
bool Email::sendCode(std::string user, std::string code) { std::string msg,to; msg = m_m1 + code + m_m2; to = m_to1 + user + m_to3; SSL_CTX* ctx = SSL_CTX_new(SSLv23_client_method()); SSL* ssl; BIO* bio = BIO_new_ssl_connect(ctx); BIO_get_ssl(bio, &ssl); SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); BIO_set_conn_hostname(bio, m_amazonHostname.c_str()); if(BIO_do_connect(bio) <= 0){ BIO_free_all(bio); SSL_CTX_free(ctx); return false; } if(BIO_do_handshake(bio) <= 0){ BIO_free_all(bio); SSL_CTX_free(ctx); return false; } m_len = BIO_read(bio, m_buf, BUF_LEN) - 1; BIO_puts(bio, "HELO localhost\r\n"); m_len = BIO_read(bio, m_buf, BUF_LEN) - 1; BIO_puts(bio,"AUTH LOGIN\r\n"); m_len = BIO_read(bio,m_buf,BUF_LEN) - 1; BIO_puts(bio,"QUtJQUlFVzJDMlU3RUZYTU5PUVE=\r\n"); m_len = BIO_read(bio,m_buf,BUF_LEN) - 1; BIO_puts(bio,"QWd3TkZSOUJyb2dUTUkxYlJHeXh4dHZMYm4reldGZCtYSFJMbnJpNzZ5RC8=\r\n"); m_len = BIO_read(bio,m_buf,BUF_LEN) - 1; BIO_puts(bio,"MAIL FROM:[email protected]\r\n"); m_len = BIO_read(bio,m_buf,BUF_LEN) - 1; BIO_puts(bio,to.c_str()); m_len = BIO_read(bio,m_buf,BUF_LEN) - 1; BIO_puts(bio,"DATA\r\n"); m_len = BIO_read(bio,m_buf,BUF_LEN) - 1; BIO_puts(bio,"Subject:OneBrown Verification\r\n\r\n"); BIO_puts(bio,msg.c_str()); BIO_puts(bio,"\r\n.\r\n"); m_len = BIO_read(bio,m_buf,BUF_LEN) - 1; BIO_puts(bio,"QUIT\r\n"); m_len = BIO_read(bio,m_buf,BUF_LEN) - 1; BIO_free_all(bio); SSL_CTX_free(ctx); return true; }
bool SSLClient::initBIO() { mrBIO = BIO_new(BIO_s_mem()); mwBIO = BIO_new(BIO_s_mem()); if ((mpSSL == NULL) || (mrBIO == NULL) || (mwBIO == NULL)){ log(L_WARN, "SSL error"); return false; } SSL_set_bio(pSSL, rBIO, wBIO); SSL_set_mode(pSSL, SSL_MODE_AUTO_RETRY); return true; }
SSLConnect::SSLConnect( QObject *parent ) : QObject( parent ) , d( new SSLConnectPrivate() ) { d->ctx = SSL_CTX_new( TLSv1_client_method() ); if( d->ctx ) d->ssl = SSL_new( d->ctx ); if( d->ssl ) SSL_set_mode( d->ssl, SSL_MODE_AUTO_RETRY ); else d->setError(); }
CAMLprim value ocaml_ssl_set_mode(value socket, value mode) { CAMLparam2(socket,mode); long m; ssl_socket_t *ssl = ssl_socket_of_block(socket); m = 0; if (Bool_val(Field(mode, 0))) m |= SSL_MODE_ENABLE_PARTIAL_WRITE; if (Bool_val(Field(mode, 1))) m |= SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER; if (Bool_val(Field(mode, 2))) m |= SSL_MODE_AUTO_RETRY; SSL_set_mode(ssl->handler, m); CAMLreturn(Val_unit); }
/** setup SSL connection to the client */ static SSL* setup_ssl(int s, SSL_CTX* ctx) { SSL* ssl = SSL_new(ctx); if(!ssl) return NULL; SSL_set_accept_state(ssl); (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); if(!SSL_set_fd(ssl, s)) { SSL_free(ssl); return NULL; } return ssl; }
int ssl_timeoutconn(int t, int rfd, int wfd, SSL *ssl) { int r; /* if connection is established, keep NDELAY */ if (ndelay_on(rfd) == -1 || ndelay_on(wfd) == -1) return -1; r = ssl_timeoutio(SSL_connect, t, rfd, wfd, ssl, NULL, 0); if (r <= 0) { ndelay_off(rfd); ndelay_off(wfd); } else SSL_set_mode(ssl, SSL_MODE_ENABLE_PARTIAL_WRITE); return r; }
bool ssl_stream::open( SOCKET socket, long timeout_sec ) { socket_ = socket; SSL_library_init(); SSL_load_error_strings(); ssl_ctx_ = SSL_CTX_new( SSLv23_client_method() ); if( ssl_ctx_ == NULL ) { return false; } ssl_ = SSL_new( ssl_ctx_ ); if( ssl_ == NULL ) { return false; } SSL_set_fd( ssl_, static_cast< int >( socket_ ) ); SSL_set_mode( ssl_, SSL_MODE_AUTO_RETRY ); while( 1 ) { int res = SSL_connect( ssl_ ); switch( SSL_get_error( ssl_, res ) ) { case SSL_ERROR_NONE: return true; break; case SSL_ERROR_WANT_WRITE: if( check_select( socket_, /*check_read = */ false, /*check_write = */ true, timeout_sec ) == false ) { return false; } break; case SSL_ERROR_WANT_READ: if( check_select( socket_, /*check_read = */ true, /*check_write = */ false, timeout_sec ) == false ) { return false; } break; default: return false; } } return true; }
/** * \brief do TLS negotiation with client application * \param[in] *C The context of verse server * \return This function returns 1, when TLS connection was established and * it returns 0, when TLS was not established. */ int vs_TLS_handshake(struct vContext *C) { struct VS_CTX *vs_ctx = CTX_server_ctx(C); struct IO_CTX *io_ctx = CTX_io_ctx(C); struct VStreamConn *stream_conn = CTX_current_stream_conn(C); int flag, ret; /* Make sure socket is blocking */ flag = fcntl(stream_conn->io_ctx.sockfd, F_GETFL, 0); if( (fcntl(stream_conn->io_ctx.sockfd, F_SETFL, flag & ~O_NONBLOCK)) == -1) { if(is_log_level(VRS_PRINT_ERROR)) v_print_log(VRS_PRINT_ERROR, "fcntl(): %s\n", strerror(errno)); return 0; } /* Set up SSL */ if( (stream_conn->io_ctx.ssl = SSL_new(vs_ctx->tls_ctx)) == NULL) { v_print_log(VRS_PRINT_ERROR, "Setting up SSL failed.\n"); ERR_print_errors_fp(v_log_file()); SSL_free(stream_conn->io_ctx.ssl); stream_conn->io_ctx.ssl = NULL; close(io_ctx->sockfd); return 0; } /* Bind socket and SSL */ if (SSL_set_fd(stream_conn->io_ctx.ssl, io_ctx->sockfd) == 0) { v_print_log(VRS_PRINT_ERROR, "Failed binding socket descriptor and SSL.\n"); ERR_print_errors_fp(v_log_file()); SSL_free(stream_conn->io_ctx.ssl); stream_conn->io_ctx.ssl = NULL; close(io_ctx->sockfd); return 0; } SSL_set_mode(stream_conn->io_ctx.ssl, SSL_MODE_AUTO_RETRY); /* Do TLS handshake and negotiation */ if( (ret = SSL_accept(stream_conn->io_ctx.ssl)) != 1) { int err = SSL_get_error(stream_conn->io_ctx.ssl, ret); v_print_log(VRS_PRINT_ERROR, "SSL handshake failed: %d -> %d\n", ret, err); ERR_print_errors_fp(v_log_file()); SSL_free(stream_conn->io_ctx.ssl); stream_conn->io_ctx.ssl = NULL; close(io_ctx->sockfd); return 0; } v_print_log(VRS_PRINT_DEBUG_MSG, "SSL handshake succeed.\n"); return 1; }
int lws_tls_server_new_nonblocking(struct lws *wsi, lws_sockfd_type accept_fd) { #if !defined(USE_WOLFSSL) BIO *bio; #endif errno = 0; wsi->tls.ssl = SSL_new(wsi->vhost->tls.ssl_ctx); if (wsi->tls.ssl == NULL) { lwsl_err("SSL_new failed: %d (errno %d)\n", lws_ssl_get_error(wsi, 0), errno); lws_tls_err_describe(); return 1; } SSL_set_ex_data(wsi->tls.ssl, openssl_websocket_private_data_index, wsi); SSL_set_fd(wsi->tls.ssl, (int)(long long)accept_fd); #ifdef USE_WOLFSSL #ifdef USE_OLD_CYASSL CyaSSL_set_using_nonblock(wsi->tls.ssl, 1); #else wolfSSL_set_using_nonblock(wsi->tls.ssl, 1); #endif #else SSL_set_mode(wsi->tls.ssl, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_RELEASE_BUFFERS); bio = SSL_get_rbio(wsi->tls.ssl); if (bio) BIO_set_nbio(bio, 1); /* nonblocking */ else lwsl_notice("NULL rbio\n"); bio = SSL_get_wbio(wsi->tls.ssl); if (bio) BIO_set_nbio(bio, 1); /* nonblocking */ else lwsl_notice("NULL rbio\n"); #endif #if defined (LWS_HAVE_SSL_SET_INFO_CALLBACK) if (wsi->vhost->tls.ssl_info_event_mask) SSL_set_info_callback(wsi->tls.ssl, lws_ssl_info_callback); #endif return 0; }
/* ssl_negotiate: After SSL state has been initialized, attempt to negotiate * SSL over the wire, including certificate checks. */ static int ssl_negotiate (CONNECTION *conn, sslsockdata* ssldata) { int err; const char* errmsg; SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY); if ((err = SSL_connect (ssldata->ssl)) != 1) { switch (SSL_get_error (ssldata->ssl, err)) { case SSL_ERROR_SYSCALL: errmsg = _("I/O error"); break; case SSL_ERROR_SSL: errmsg = ERR_error_string (ERR_get_error (), NULL); break; default: errmsg = _("unknown error"); } mutt_error (_("SSL failed: %s"), errmsg); mutt_sleep (1); return -1; } ssldata->cert = SSL_get_peer_certificate (ssldata->ssl); if (!ssldata->cert) { mutt_error (_("Unable to get certificate from peer")); mutt_sleep (1); return -1; } if (!ssl_check_certificate (conn, ssldata)) return -1; /* L10N: %1$s is version (e.g. "TLSv1.2") %2$s is cipher_version (e.g. "TLSv1/SSLv3") %3$s is cipher_name (e.g. "ECDHE-RSA-AES128-GCM-SHA256") */ mutt_message (_("%s connection using %s (%s)"), SSL_get_version(ssldata->ssl), SSL_get_cipher_version (ssldata->ssl), SSL_get_cipher_name (ssldata->ssl)); mutt_sleep (0); return 0; }
/* ssl_negotiate: After SSL state has been initialised, attempt to negotiate * SSL over the wire, including certificate checks. */ static int ssl_negotiate (CONNECTION *conn, sslsockdata* ssldata) { int err; const char* errmsg; #if OPENSSL_VERSION_NUMBER >= 0x00906000L /* This only exists in 0.9.6 and above. Without it we may get interrupted * reads or writes. Bummer. */ SSL_set_mode (ssldata->ssl, SSL_MODE_AUTO_RETRY); #endif if ((err = SSL_connect (ssldata->ssl)) != 1) { switch (SSL_get_error (ssldata->ssl, err)) { case SSL_ERROR_SYSCALL: errmsg = _("I/O error"); break; case SSL_ERROR_SSL: errmsg = ERR_error_string (ERR_get_error (), NULL); break; default: errmsg = _("unknown error"); } mutt_error (_("SSL failed: %s"), errmsg); mutt_sleep (1); return -1; } ssldata->cert = SSL_get_peer_certificate (ssldata->ssl); if (!ssldata->cert) { mutt_error (_("Unable to get certificate from peer")); mutt_sleep (1); return -1; } if (!ssl_check_certificate (conn, ssldata)) return -1; mutt_message (_("%s connection using %s (%s)"), SSL_get_version(ssldata->ssl), SSL_get_cipher_version (ssldata->ssl), SSL_get_cipher_name (ssldata->ssl)); mutt_sleep (0); return 0; }
static FILE *_ssl_fopen(int sd, int client) { int r; mssl_cookie_t *kuki; FILE *f; _dprintf("%s()\n", __FUNCTION__); if ((kuki = calloc(1, sizeof(*kuki))) == NULL) { errno = ENOMEM; return NULL; } kuki->sd = sd; if ((kuki->ssl = SSL_new(ctx)) == NULL) { _dprintf("%s: SSL_new failed\n", __FUNCTION__); goto ERROR; } #ifdef USE_OPENSSL SSL_set_verify(kuki->ssl, SSL_VERIFY_NONE, NULL); SSL_set_mode(kuki->ssl, SSL_MODE_AUTO_RETRY); #endif SSL_set_fd(kuki->ssl, kuki->sd); r = client ? SSL_connect(kuki->ssl) : SSL_accept(kuki->ssl); if (r <= 0) { _dprintf("%s: SSL handshake failed\n", __FUNCTION__); mssl_print_err(kuki->ssl); goto ERROR; } #ifdef USE_OPENSSL _dprintf("SSL connection using %s cipher\n", SSL_get_cipher(kuki->ssl)); #endif if ((f = fopencookie(kuki, "r+", mssl)) == NULL) { _dprintf("%s: fopencookie failed\n", __FUNCTION__); goto ERROR; } _dprintf("%s() success\n", __FUNCTION__); return f; ERROR: mssl_close(kuki); return NULL; }
void* outgoing_ssl_fd(void* sslctx, int fd) { SSL* ssl = SSL_new((SSL_CTX*)sslctx); if(!ssl) { log_crypto_err("could not SSL_new"); return NULL; } SSL_set_connect_state(ssl); (void)SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); if(!SSL_set_fd(ssl, fd)) { log_crypto_err("could not SSL_set_fd"); SSL_free(ssl); return NULL; } return ssl; }
void WebSocket::initPoll(Server *server, uv_os_fd_t fd, void *ssl, void *perMessageDeflate) { uv_poll_init_socket(server->loop, p, fd); SocketData *socketData = new SocketData; socketData->pmd = (PerMessageDeflate *) perMessageDeflate; socketData->server = server; socketData->ssl = (SSL *) ssl; if (socketData->ssl) { SSL_set_fd(socketData->ssl, fd); SSL_set_mode(socketData->ssl, SSL_MODE_ENABLE_PARTIAL_WRITE); } p->data = socketData; uv_poll_start(p, UV_READABLE, onReadable); }
/** * Connect to a host using an encrypted stream */ BIO* connect_encrypted(char* host_and_port, char* store_path, char store_type, SSL_CTX** ctx, SSL** ssl) { BIO* bio = NULL; int r = 0; /* Set up the SSL pointers */ *ctx = SSL_CTX_new(SSLv23_client_method()); *ssl = NULL; /* Load the trust store from the pem location in argv[2] */ if (store_type == 'f') r = SSL_CTX_load_verify_locations(*ctx, store_path, NULL); else r = SSL_CTX_load_verify_locations(*ctx, NULL, store_path); if (r == 0) { print_ssl_error_2("Unable to load the trust store from %s.\n", store_path, stdout); return NULL; } /* Setting up the BIO SSL object */ bio = BIO_new_ssl_connect(*ctx); BIO_get_ssl(bio, ssl); if (!(*ssl)) { print_ssl_error("Unable to allocate SSL pointer.\n", stdout); return NULL; } SSL_set_mode(*ssl, SSL_MODE_AUTO_RETRY); /* Attempt to connect */ BIO_set_conn_hostname(bio, host_and_port); /* Verify the connection opened and perform the handshake */ if (BIO_do_connect(bio) < 1) { print_ssl_error_2("Unable to connect BIO.%s\n", host_and_port, stdout); return NULL; } if (SSL_get_verify_result(*ssl) != X509_V_OK) { print_ssl_error("Unable to verify connection result.\n", stdout); } return bio; }