Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions ixwebsocket/IXSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,11 @@ namespace ix
#endif
}

// Darwin TSan can confuse reused per-thread errno storage with shared memory.
// These accessors touch only OS thread-local error state; keep callers instrumented.
#if defined(__APPLE__) && defined(__clang__)
__attribute__((no_sanitize("thread")))
#endif
int Socket::getErrno()
{
int err;
Expand All @@ -319,6 +324,9 @@ namespace ix
return err;
}

#if defined(__APPLE__) && defined(__clang__)
__attribute__((no_sanitize("thread")))
#endif
void Socket::setErrno(int err)
{
#ifdef _WIN32
Expand Down
22 changes: 17 additions & 5 deletions ixwebsocket/IXSocketAppleSSL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ namespace ix

OSStatus SocketAppleSSL::readFromSocket(SSLConnectionRef connection, void* data, size_t* len)
{
int fd = (int) (long) connection;
auto* socket = static_cast<SocketAppleSSL*>(const_cast<void*>(connection));
int fd = socket->_sockfd;
socket->_handshakeWantsRead = true;
if (fd < 0) return errSSLInternal;

assert(data != nullptr);
Expand Down Expand Up @@ -116,7 +118,9 @@ namespace ix
const void* data,
size_t* len)
{
int fd = (int) (long) connection;
auto* socket = static_cast<SocketAppleSSL*>(const_cast<void*>(connection));
int fd = socket->_sockfd;
socket->_handshakeWantsRead = false;
if (fd < 0) return errSSLInternal;

assert(data != nullptr);
Expand Down Expand Up @@ -176,17 +180,25 @@ namespace ix
status = SSLHandshake(_sslContext);

// Interrupt the handshake
if (isCancellationRequested())
if (isCancellationRequested && isCancellationRequested())
{
errMsg = "Cancellation requested";
return errSSLInternal;
}
if (status == errSSLWouldBlock)
{
const auto ready = _handshakeWantsRead ? isReadyToRead(10) : isReadyToWrite(10);
if (ready == PollResultType::Error)
{
errMsg = "Socket error during TLS handshake";
return errSSLInternal;
}
}
} while (status == errSSLWouldBlock || status == errSSLServerAuthCompleted);

return status;
}

// No wait support
bool SocketAppleSSL::connect(const std::string& host,
int port,
std::string& errMsg,
Expand All @@ -203,7 +215,7 @@ namespace ix

SSLSetIOFuncs(
_sslContext, SocketAppleSSL::readFromSocket, SocketAppleSSL::writeToSocket);
SSLSetConnection(_sslContext, (SSLConnectionRef)(long) _sockfd);
SSLSetConnection(_sslContext, this);
SSLSetProtocolVersionMin(_sslContext, kTLSProtocol12);

if (!_tlsOptions.disable_hostname_validation)
Expand Down
2 changes: 2 additions & 0 deletions ixwebsocket/IXSocketAppleSSL.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ namespace ix
const CancellationRequest& isCancellationRequested);

SSLContextRef _sslContext;
// SecureTransport uses one would-block status for both I/O directions.
bool _handshakeWantsRead = true;
mutable std::mutex _mutex; // AppleSSL routines are not thread-safe

SocketTLSOptions _tlsOptions;
Expand Down
82 changes: 30 additions & 52 deletions ixwebsocket/IXSocketMbedTLS.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,36 @@ namespace ix

mbedtls_ssl_set_bio(&_ssl, &_sockfd, mbedtls_net_send, mbedtls_net_recv, NULL);

return handshake(errMsg, isCancellationRequested);
}

bool SocketMbedTLS::connect(const std::string& host,
int port,
std::string& errMsg,
const CancellationRequest& isCancellationRequested)
{
{
std::lock_guard<std::mutex> lock(_mutex);
_sockfd = connectToHost(host, port, errMsg, isCancellationRequested);
if (_sockfd == -1) return false;
}

bool isClient = true;
bool initialized = init(host, isClient, errMsg);
if (!initialized)
{
close();
return false;
}

mbedtls_ssl_set_bio(&_ssl, &_sockfd, mbedtls_net_send, mbedtls_net_recv, NULL);

return handshake(errMsg, isCancellationRequested);
}

bool SocketMbedTLS::handshake(std::string& errMsg,
const CancellationRequest& isCancellationRequested)
{
int res;
do
{
Expand Down Expand Up @@ -299,58 +329,6 @@ namespace ix
return true;
}

bool SocketMbedTLS::connect(const std::string& host,
int port,
std::string& errMsg,
const CancellationRequest& isCancellationRequested)
{
{
std::lock_guard<std::mutex> lock(_mutex);
_sockfd = connectToHost(host, port, errMsg, isCancellationRequested);
if (_sockfd == -1) return false;
}

bool isClient = true;
bool initialized = init(host, isClient, errMsg);
if (!initialized)
{
close();
return false;
}

mbedtls_ssl_set_bio(&_ssl, &_sockfd, mbedtls_net_send, mbedtls_net_recv, NULL);

int res;
do
{
{
std::lock_guard<std::mutex> lock(_mutex);
res = mbedtls_ssl_handshake(&_ssl);
}

if (isCancellationRequested())
{
errMsg = "Cancellation requested";
close();
return false;
}
} while (res == MBEDTLS_ERR_SSL_WANT_READ || res == MBEDTLS_ERR_SSL_WANT_WRITE);

if (res != 0)
{
char buf[256];
mbedtls_strerror(res, buf, sizeof(buf));

errMsg = "error in handshake : ";
errMsg += buf;

close();
return false;
}

return true;
}

void SocketMbedTLS::close()
{
std::lock_guard<std::mutex> lock(_mutex);
Expand Down
1 change: 1 addition & 0 deletions ixwebsocket/IXSocketMbedTLS.h
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ namespace ix

bool init(const std::string& host, bool isClient, std::string& errMsg);
void initMBedTLS();
bool handshake(std::string& errMsg, const CancellationRequest& isCancellationRequested);
bool loadSystemCertificates(std::string& errMsg);
};

Expand Down
6 changes: 4 additions & 2 deletions ixwebsocket/IXSocketOpenSSL.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ namespace ix
return false;
}

if (isCancellationRequested())
if (isCancellationRequested && isCancellationRequested())
{
errMsg = "Cancellation requested";
return false;
Expand All @@ -419,7 +419,9 @@ namespace ix
bool rc = false;
if (reason == SSL_ERROR_WANT_READ || reason == SSL_ERROR_WANT_WRITE)
{
rc = true;
auto ready = reason == SSL_ERROR_WANT_READ ? isReadyToRead(10) : isReadyToWrite(10);
rc = ready != PollResultType::Error;
if (!rc) errMsg = "Socket error during TLS handshake";
}
else
{
Expand Down
36 changes: 34 additions & 2 deletions test/IXSocketAppleSSLReadTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,31 @@ namespace ix
*size = 0;
return errSecIO;
}
static void install(SocketAppleSSL& socket)
static OSStatus readBlocked(SSLConnectionRef, void*, size_t* size)
{
*size = 0;
return errSSLWouldBlock;
}
static OSStatus writeBlocked(SSLConnectionRef, const void*, size_t* size)
{
*size = 0;
return errSSLWouldBlock;
}
static OSStatus handshake(SocketAppleSSL& socket,
std::string& error,
const CancellationRequest& cancelled)
{
return socket.tlsHandShake(error, cancelled);
}
static void install(SocketAppleSSL& socket, bool blocked = false, bool reading = true)
{
socket._sslContext =
SSLCreateContext(kCFAllocatorDefault, kSSLClientSide, kSSLStreamType);
REQUIRE(socket._sslContext != nullptr);
REQUIRE(SSLSetIOFuncs(socket._sslContext, read, write) == noErr);
socket._handshakeWantsRead = reading;
REQUIRE(SSLSetIOFuncs(socket._sslContext,
blocked ? readBlocked : read,
blocked ? writeBlocked : write) == noErr);
}
};
} // namespace ix
Expand All @@ -40,3 +59,16 @@ TEST_CASE("SecureTransport terminal errors clear a previous wait status", "[sock
CHECK_FALSE(ix::Socket::isWaitNeeded());
CHECK(ix::Socket::getErrno() != 0);
}

TEST_CASE("SecureTransport handshakes stop on readiness errors", "[socket_apple][handshake_wait]")
{
const bool reading = GENERATE(false, true);
ix::SocketAppleSSL socket(ix::SocketTLSOptions {});
ix::SocketAppleSSLReadTestAccess::install(socket, true, reading);
unsigned checks = 0;
std::string error;
CHECK(ix::SocketAppleSSLReadTestAccess::handshake(
socket, error, [&] { return ++checks > 3; }) == errSSLInternal);
CHECK(checks == 1);
CHECK(error == "Socket error during TLS handshake");
}
27 changes: 27 additions & 0 deletions test/IXSocketMbedTLSWriteTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ namespace ix
{
struct SocketMbedTLSWriteTestAccess
{
static bool handshake(SocketMbedTLS& socket,
std::string& error,
const CancellationRequest& cancelled)
{
return socket.handshake(error, cancelled);
}
static int reset(SocketMbedTLS& socket)
{
return mbedtls_ssl_session_reset(&socket._ssl);
}
static void install(SocketMbedTLS& socket, mbedtls_ssl_context& session)
{
socket.initMBedTLS();
Expand Down Expand Up @@ -307,6 +317,23 @@ TEST_CASE("MbedTLS readBytes completes from TLS buffers without polling", "[sock
CHECK(result.second == "abc");
}

TEST_CASE("MbedTLS client handshakes stop on readiness errors", "[socket_mbedtls][handshake_wait]")
{
const bool blockedWrite = GENERATE(false, true);
ix::SocketMbedTLS socket(ix::SocketTLSOptions {});
MemoryConnection connection(socket);
REQUIRE(ix::SocketMbedTLSWriteTestAccess::reset(socket) == 0);
connection.client.incoming.clear();
connection.server.incoming.clear();
if (blockedWrite) connection.client.writesBeforeBlocking = 0;
unsigned checks = 0;
std::string error;
CHECK_FALSE(
ix::SocketMbedTLSWriteTestAccess::handshake(socket, error, [&] { return ++checks > 3; }));
CHECK(checks == 1);
CHECK(error == "Socket error during TLS handshake");
}

#else
TEST_CASE("MbedTLS memory write tests require TLS 1.2 PSK and PSA crypto", "[socket_mbedtls]")
{
Expand Down
27 changes: 27 additions & 0 deletions test/IXSocketOpenSSLWriteTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@ namespace ix
{
struct SocketOpenSSLWriteTestAccess
{
static bool handshake(SocketOpenSSL& socket,
std::string& error,
const CancellationRequest& cancelled)
{
return socket.openSSLClientHandshake("memory.invalid", error, cancelled);
}
static int reset(SocketOpenSSL& socket)
{
return SSL_clear(socket._ssl_connection);
}
static void install(SocketOpenSSL& socket, SSL*& session, SSL_CTX*& context)
{
std::swap(socket._ssl_connection, session);
Expand Down Expand Up @@ -283,6 +293,23 @@ TEST_CASE("OpenSSL readBytes completes from TLS buffers without polling", "[sock
CHECK(result.second == "abc");
}

TEST_CASE("OpenSSL client handshakes stop on readiness errors", "[socket_openssl][handshake_wait]")
{
const bool blockedWrite = GENERATE(false, true);
ix::SocketOpenSSL socket(ix::SocketTLSOptions {});
MemoryConnection connection(socket);
REQUIRE(ix::SocketOpenSSLWriteTestAccess::reset(socket) == 1);
connection.client.incoming.clear();
connection.server.incoming.clear();
if (blockedWrite) connection.client.writesBeforeBlocking = 0;
unsigned checks = 0;
std::string error;
CHECK_FALSE(
ix::SocketOpenSSLWriteTestAccess::handshake(socket, error, [&] { return ++checks > 3; }));
CHECK(checks == 1);
CHECK(error == "Socket error during TLS handshake");
}

#else
TEST_CASE("OpenSSL memory write tests require TLS 1.2 PSK and OpenSSL 1.1 APIs", "[socket_openssl]")
{
Expand Down
24 changes: 24 additions & 0 deletions test/IXSocketTest.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
#include <ixwebsocket/IXSocket.h>
#include <ixwebsocket/IXSocketFactory.h>
#include <string.h>
#include <thread>

using namespace ix;

Expand Down Expand Up @@ -107,6 +108,29 @@ TEST_CASE("Empty and cancelled socket reads do not receive data", "[socket][read
CHECK(socket.reads == 0);
}

TEST_CASE("Socket error state remains local when threads are reused", "[socket][errno]")
{
std::atomic<bool> isolated {true};
auto churn = [&](int error)
{
for (int i = 0; i < 16; ++i)
{
std::thread worker(
[&, error]
{
Socket::setErrno(error);
if (Socket::getErrno() != error) isolated = false;
});
worker.join();
}
};
std::thread a(churn, EWOULDBLOCK);
std::thread b(churn, EINVAL);
a.join();
b.join();
CHECK(isolated.load());
}

namespace ix
{
void testSocket(const std::string& host,
Expand Down
Loading