Add timeout to SSL connection attempt to prevent hanging threads

- Set socket non-blocking during SSL handshake
- Use select with 5-second timeout for SSL_connect
- Fallback to plain TCP if SSL fails for 'web' services
parent 32b7b4b9
......@@ -33,6 +33,7 @@
#include <netdb.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/select.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "web_proxy.h"
......@@ -506,10 +507,57 @@ static int handle_proxy_request(int client_fd, wssshd_state_t *state, const wsss
return -1;
}
} else {
tunnel_ssl = create_ssl_connection(ssl_ctx, tunnel_fd, 0);
if (!tunnel_ssl) {
printf("[WEB-PROXY] SSL connection failed\n");
// Set socket non-blocking for SSL timeout
int flags = fcntl(tunnel_fd, F_GETFL, 0);
fcntl(tunnel_fd, F_SETFL, flags | O_NONBLOCK);
tunnel_ssl = SSL_new(ssl_ctx);
SSL_set_fd(tunnel_ssl, tunnel_fd);
// Perform SSL connect with timeout
int ret;
fd_set fdset;
struct timeval tv;
tv.tv_sec = 5; // 5 second timeout
tv.tv_usec = 0;
while (1) {
ret = SSL_connect(tunnel_ssl);
if (ret > 0) {
printf("[WEB-PROXY] SSL connection established\n");
break;
}
int err = SSL_get_error(tunnel_ssl, ret);
if (err == SSL_ERROR_WANT_READ) {
FD_ZERO(&fdset);
FD_SET(tunnel_fd, &fdset);
int sel = select(tunnel_fd + 1, &fdset, NULL, NULL, &tv);
if (sel <= 0) {
printf("[WEB-PROXY] SSL connection timeout on read\n");
ret = -1;
break;
}
} else if (err == SSL_ERROR_WANT_WRITE) {
FD_ZERO(&fdset);
FD_SET(tunnel_fd, &fdset);
int sel = select(tunnel_fd + 1, NULL, &fdset, NULL, &tv);
if (sel <= 0) {
printf("[WEB-PROXY] SSL connection timeout on write\n");
ret = -1;
break;
}
} else {
printf("[WEB-PROXY] SSL connection failed with error %d\n", err);
ret = -1;
break;
}
}
if (ret <= 0) {
SSL_free(tunnel_ssl);
tunnel_ssl = NULL;
SSL_CTX_free(ssl_ctx);
ssl_ctx = NULL;
if (strcmp(service_type, "web") == 0) {
use_ssl = false; // Fallback to HTTP
printf("[WEB-PROXY] Falling back to plain TCP\n");
......@@ -518,8 +566,11 @@ static int handle_proxy_request(int client_fd, wssshd_state_t *state, const wsss
send_http_error(client_fd, 502, "Bad Gateway");
return -1;
}
} else {
printf("[WEB-PROXY] SSL connection established\n");
}
// Set socket back to blocking
if (tunnel_ssl) {
fcntl(tunnel_fd, F_SETFL, flags & ~O_NONBLOCK);
}
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment