22#include <freerdp/config.h>
23#include <freerdp/version.h>
25#include <winpr/assert.h>
28#include <winpr/synch.h>
29#include <winpr/print.h>
30#include <winpr/stream.h>
31#include <winpr/winsock.h>
32#include <winpr/cred.h>
34#include "../settings.h"
36#include <freerdp/log.h>
37#include <freerdp/error.h>
38#include <freerdp/utils/ringbuffer.h>
39#include <freerdp/utils/smartcardlogon.h>
44#include "../credssp_auth.h"
47#include "../../crypto/opensslcompat.h"
51#define TAG FREERDP_TAG("core.gateway.wst")
53#define AUTH_PKG NEGO_SSP_NAME
68 websocket_context* wscontext;
72static const char arm_query_param[] =
"%s%cClmTk=Bearer%%20%s";
74static BOOL wst_get_gateway_credentials(wLog* log, rdpContext* context, rdp_auth_reason reason)
76 WINPR_ASSERT(context);
77 freerdp* instance = context->instance;
79 auth_status rc = utils_authenticate_gateway(instance, reason);
86 freerdp_set_last_error_log(instance->context, FREERDP_ERROR_CONNECT_CANCELLED);
88 case AUTH_NO_CREDENTIALS:
89 WLog_Print(log, WLOG_INFO,
"No credentials provided - using nullptr identity");
97static BOOL wst_auth_init(rdpWst* wst, rdpTls* tls, TCHAR* authPkg)
101 WINPR_ASSERT(authPkg);
103 rdpContext* context = wst->context;
104 rdpSettings* settings = context->settings;
105 SEC_WINNT_AUTH_IDENTITY identity = WINPR_C_ARRAY_INIT;
108 wst->auth_required = TRUE;
109 if (!credssp_auth_init(wst->auth, authPkg, tls->Bindings))
112 if (!wst_get_gateway_credentials(wst->log, context, GW_AUTH_RDG))
115 if (!identity_set_from_settings(&identity, settings, FreeRDP_GatewayUsername,
116 FreeRDP_GatewayDomain, FreeRDP_GatewayPassword))
119 SEC_WINNT_AUTH_IDENTITY* identityArg = (settings->GatewayUsername ? &identity :
nullptr);
120 if (!credssp_auth_setup_client(wst->auth,
"HTTP", wst->gwhostname, identityArg,
nullptr))
122 sspi_FreeAuthIdentity(&identity);
125 sspi_FreeAuthIdentity(&identity);
127 credssp_auth_set_flags(wst->auth, ISC_REQ_CONFIDENTIALITY | ISC_REQ_MUTUAL_AUTH);
129 rc = credssp_auth_authenticate(wst->auth);
133static BOOL wst_set_auth_header(rdpCredsspAuth* auth, HttpRequest* request)
136 WINPR_ASSERT(request);
138 const SecBuffer* authToken = credssp_auth_get_output_buffer(auth);
139 char* base64AuthToken =
nullptr;
143 if (authToken->cbBuffer > INT_MAX)
146 base64AuthToken = crypto_base64_encode(authToken->pvBuffer, authToken->cbBuffer);
151 BOOL rc = http_request_set_auth_scheme(request, credssp_auth_pkg_name(auth)) &&
152 http_request_set_auth_param(request, base64AuthToken);
153 free(base64AuthToken);
162static BOOL wst_recv_auth_token(rdpCredsspAuth* auth, HttpResponse* response)
165 size_t authTokenLength = 0;
166 BYTE* authTokenData =
nullptr;
167 SecBuffer authToken = WINPR_C_ARRAY_INIT;
170 if (!auth || !response)
173 const UINT16 StatusCode = http_response_get_status_code(response);
176 case HTTP_STATUS_DENIED:
180 http_response_log_error_status(WLog_Get(TAG), WLOG_WARN, response);
184 const char* token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth));
189 len = strlen(token64);
191 crypto_base64_decode(token64, len, &authTokenData, &authTokenLength);
193 if (authTokenLength && (authTokenLength <= UINT32_MAX) && authTokenData)
195 authToken.pvBuffer = authTokenData;
196 authToken.cbBuffer = (UINT32)authTokenLength;
197 credssp_auth_take_input_buffer(auth, &authToken);
202 rc = credssp_auth_authenticate(auth);
206static BOOL wst_tls_connect(rdpWst* wst, rdpTls* tls, UINT32 timeout)
212 BIO* socketBio =
nullptr;
213 BIO* bufferedBio =
nullptr;
214 rdpSettings* settings = wst->context->settings;
215 const char* peerHostname = wst->gwhostname;
216 UINT16 peerPort = wst->gwport;
217 const char* proxyUsername =
nullptr;
218 const char* proxyPassword =
nullptr;
219 BOOL isProxyConnection =
220 proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);
222 sockfd = freerdp_tcp_connect(wst->context, peerHostname, peerPort, timeout);
224 WLog_Print(wst->log, WLOG_DEBUG,
"connecting to %s %d", peerHostname, peerPort);
230 socketBio = BIO_new(BIO_s_simple_socket());
234 closesocket((SOCKET)sockfd);
238 BIO_set_fd(socketBio, sockfd, BIO_CLOSE);
239 bufferedBio = BIO_new(BIO_s_buffered_socket());
243 BIO_free_all(socketBio);
247 bufferedBio = BIO_push(bufferedBio, socketBio);
248 status = BIO_set_nonblock(bufferedBio, TRUE);
250 if (isProxyConnection)
252 if (!proxy_connect(wst->context, bufferedBio, proxyUsername, proxyPassword, wst->gwhostname,
255 BIO_free_all(bufferedBio);
262 BIO_free_all(bufferedBio);
266 tls->hostname = wst->gwhostname;
267 tls->port = MIN(UINT16_MAX, wst->gwport);
268 tls->isGatewayTransport = TRUE;
269 status = freerdp_tls_connect(tls, bufferedBio);
272 rdpContext* context = wst->context;
275 freerdp_set_last_error_if_not(context, FREERDP_ERROR_TLS_CONNECT_FAILED);
279 freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_CANCELLED);
284 return (status >= 1);
287static wStream* wst_build_http_request(rdpWst* wst)
290 HttpRequest* request =
nullptr;
291 const char* uri =
nullptr;
296 uri = http_context_get_uri(wst->http);
297 request = http_request_new();
302 if (!http_request_set_method(request,
"GET") || !http_request_set_uri(request, uri))
305 if (wst->auth_required)
307 if (!wst_set_auth_header(wst->auth, request))
312 if (!http_request_set_auth_scheme(request,
"Bearer"))
314 if (!http_request_set_auth_param(
316 FreeRDP_GatewayHttpExtAuthBearer)))
320 s = http_request_write(wst->http, request);
322 http_request_free(request);
325 Stream_SealLength(s);
330static BOOL wst_send_http_request(rdpWst* wst, rdpTls* tls)
335 wStream* s = wst_build_http_request(wst);
339 const size_t sz = Stream_Length(s);
340 WLog_Print(wst->log, WLOG_TRACE,
"header [%" PRIuz
"]: %s", sz, Stream_Buffer(s));
342 const int status = freerdp_tls_write_all(tls, Stream_Buffer(s), sz);
343 Stream_Free(s, TRUE);
344 return (status >= 0);
347static BOOL wst_handle_ok_or_forbidden(rdpWst* wst, HttpResponse** ppresponse, DWORD timeout,
351 WINPR_ASSERT(ppresponse);
352 WINPR_ASSERT(*ppresponse);
353 WINPR_ASSERT(pStatusCode);
356 const char* affinity = http_response_get_setcookie(*ppresponse,
"ARRAffinity");
357 const char* samesite = http_response_get_setcookie(*ppresponse,
"ARRAffinitySameSite");
358 if ((affinity || samesite) &&
361 WLog_Print(wst->log, WLOG_INFO,
"Got ARRAffinity cookie %s", affinity);
362 WLog_Print(wst->log, WLOG_INFO,
"Got ARRAffinitySameSite cookie %s", samesite);
365 if (!http_context_set_cookie(wst->http,
"ARRAffinity", affinity))
370 if (!http_context_set_cookie(wst->http,
"ARRAffinitySameSite", samesite))
373 http_response_free(*ppresponse);
374 *ppresponse =
nullptr;
376 const long fd = BIO_get_fd(wst->tls->bio,
nullptr);
377 if ((fd >= 0) && (fd <= INT32_MAX))
378 closesocket((SOCKET)fd);
379 freerdp_tls_free(wst->tls);
381 wst->tls = freerdp_tls_new(wst->context);
382 if (!wst_tls_connect(wst, wst->tls, timeout))
388 char* urlWithAuth =
nullptr;
390 char firstParam = (strchr(wst->gwpath,
'?') !=
nullptr) ?
'&' :
'?';
392 FreeRDP_GatewayHttpExtAuthBearer);
395 winpr_asprintf(&urlWithAuth, &urlLen, arm_query_param, wst->gwpath, firstParam, bearer,
400 wst->gwpath = urlWithAuth;
401 if (!utils_str_is_empty(ua))
404 char* uastr =
nullptr;
405 winpr_asprintf(&uastr, &ualen,
"%s&X-MS-User-Agent=%s", wst->gwpath, ua);
411 if (!http_context_set_uri(wst->http, wst->gwpath))
413 if (!http_context_enable_websocket_upgrade(wst->http, TRUE))
417 if (!wst_send_http_request(wst, wst->tls))
419 *ppresponse = http_response_recv(wst->tls, TRUE);
423 (void)http_response_extract_cookies(*ppresponse, wst->http);
424 *pStatusCode = http_response_get_status_code(*ppresponse);
430static BOOL wst_handle_denied(rdpWst* wst, HttpResponse** ppresponse, UINT16* pStatusCode)
433 WINPR_ASSERT(ppresponse);
434 WINPR_ASSERT(*ppresponse);
435 WINPR_ASSERT(pStatusCode);
440 if (!wst_auth_init(wst, wst->tls, AUTH_PKG))
442 if (!wst_send_http_request(wst, wst->tls))
445 http_response_free(*ppresponse);
446 *ppresponse = http_response_recv(wst->tls, TRUE);
450 (void)http_response_extract_cookies(*ppresponse, wst->http);
452 while (!credssp_auth_is_complete(wst->auth))
454 if (!wst_recv_auth_token(wst->auth, *ppresponse))
457 if (credssp_auth_have_output_token(wst->auth))
459 if (!wst_send_http_request(wst, wst->tls))
462 http_response_free(*ppresponse);
463 *ppresponse = http_response_recv(wst->tls, TRUE);
466 (void)http_response_extract_cookies(*ppresponse, wst->http);
469 *pStatusCode = http_response_get_status_code(*ppresponse);
473static BOOL wst_handle_http_code(rdpWst* wst, UINT16 StatusCode)
477 case HTTP_STATUS_PAYMENT_REQ:
478 case HTTP_STATUS_FORBIDDEN:
479 case HTTP_STATUS_DENIED:
480 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);
482 case HTTP_STATUS_MOVED:
483 case HTTP_STATUS_USE_PROXY:
484 case HTTP_STATUS_BAD_REQUEST:
485 case HTTP_STATUS_NOT_FOUND:
486 case HTTP_STATUS_GONE:
487 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
489 case HTTP_STATUS_SERVER_ERROR:
490 case HTTP_STATUS_NOT_SUPPORTED:
491 case HTTP_STATUS_BAD_GATEWAY:
492 case HTTP_STATUS_SERVICE_UNAVAIL:
493 case HTTP_STATUS_VERSION_NOT_SUP:
494 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
496 case HTTP_STATUS_GATEWAY_TIMEOUT:
497 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_ACTIVATION_TIMEOUT);
503 char buffer[64] = WINPR_C_ARRAY_INIT;
504 WLog_Print(wst->log, WLOG_ERROR,
"Unexpected HTTP status: %s",
505 freerdp_http_status_string_format(StatusCode, buffer, ARRAYSIZE(buffer)));
506 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
510BOOL wst_connect(rdpWst* wst, DWORD timeout)
513 WINPR_ASSERT(wst->context);
515 if (!wst_tls_connect(wst, wst->tls, timeout))
517 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
528 if (!http_context_enable_websocket_upgrade(wst->http, FALSE))
530 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
534 if (!wst_send_http_request(wst, wst->tls))
536 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
540 HttpResponse* response = http_response_recv(wst->tls, TRUE);
543 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
546 (void)http_response_extract_cookies(response, wst->http);
548 UINT16 StatusCode = http_response_get_status_code(response);
552 case HTTP_STATUS_FORBIDDEN:
554 success = wst_handle_ok_or_forbidden(wst, &response, timeout, &StatusCode);
557 case HTTP_STATUS_DENIED:
558 success = wst_handle_denied(wst, &response, &StatusCode);
561 http_response_log_error_status(WLog_Get(TAG), WLOG_WARN, response);
565 const BOOL isWebsocket = http_response_is_websocket(wst->http, response);
566 http_response_free(response);
568 return wst_handle_http_code(wst, StatusCode);
571 return websocket_context_reset(wst->wscontext);
573 return wst_handle_http_code(wst, StatusCode);
576DWORD wst_get_event_handles(rdpWst* wst, HANDLE* events, DWORD count)
579 WINPR_ASSERT(wst !=
nullptr);
583 if (events && (nCount < count))
585 BIO_get_event(wst->tls->bio, &events[nCount]);
595static int wst_bio_write(BIO* bio,
const char* buf,
int num)
601 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
603 BIO_clear_flags(bio, BIO_FLAGS_WRITE);
604 EnterCriticalSection(&wst->writeSection);
605 status = websocket_context_write(wst->wscontext, wst->tls->bio, (
const BYTE*)buf, num,
606 WebsocketBinaryOpcode);
607 LeaveCriticalSection(&wst->writeSection);
611 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
614 else if (status < num)
616 BIO_set_flags(bio, BIO_FLAGS_WRITE);
617 WSASetLastError(WSAEWOULDBLOCK);
621 BIO_set_flags(bio, BIO_FLAGS_WRITE);
627static int wst_bio_read(BIO* bio,
char* buf,
int size)
632 WINPR_ASSERT(size >= 0);
634 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
639 status = websocket_context_read(wst->wscontext, wst->tls->bio, (BYTE*)buf, (
size_t)size);
642 if (!BIO_should_retry(wst->tls->bio))
650 BIO_clear_retry_flags(bio);
653 else if (status == 0)
655 BIO_set_retry_read(bio);
656 WSASetLastError(WSAEWOULDBLOCK);
661 BIO_set_flags(bio, BIO_FLAGS_READ);
667static int wst_bio_puts(BIO* bio,
const char* str)
675static int wst_bio_gets(BIO* bio,
char* str,
int size)
683static long wst_bio_ctrl(BIO* bio,
int cmd,
long arg1,
void* arg2)
688 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
690 rdpTls* tls = wst->tls;
692 if (cmd == BIO_CTRL_FLUSH)
694 (void)BIO_flush(tls->bio);
697 else if (cmd == BIO_C_SET_NONBLOCK)
701 else if (cmd == BIO_C_READ_BLOCKED)
703 status = BIO_read_blocked(tls->bio);
705 else if (cmd == BIO_C_WRITE_BLOCKED)
707 status = BIO_write_blocked(tls->bio);
709 else if (cmd == BIO_C_WAIT_READ)
711 int timeout = (int)arg1;
713 if (BIO_read_blocked(tls->bio))
714 return BIO_wait_read(tls->bio, timeout);
717 else if (cmd == BIO_C_WAIT_WRITE)
719 int timeout = (int)arg1;
721 if (BIO_write_blocked(tls->bio))
722 status = BIO_wait_write(tls->bio, timeout);
726 else if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)
728 status = BIO_ctrl(tls->bio, cmd, arg1, arg2);
730#if OPENSSL_VERSION_NUMBER >= 0x30000000L
731 else if (cmd == BIO_CTRL_GET_KTLS_SEND)
739 else if (cmd == BIO_CTRL_GET_KTLS_RECV)
750static int wst_bio_new(BIO* bio)
752 BIO_set_init(bio, 1);
753 BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
757static int wst_bio_free(BIO* bio)
763static BIO_METHOD* BIO_s_wst(
void)
765 static BIO_METHOD* bio_methods =
nullptr;
767 if (bio_methods ==
nullptr)
769 if (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG,
"WSTransport")))
772 BIO_meth_set_write(bio_methods, wst_bio_write);
773 BIO_meth_set_read(bio_methods, wst_bio_read);
774 BIO_meth_set_puts(bio_methods, wst_bio_puts);
775 BIO_meth_set_gets(bio_methods, wst_bio_gets);
776 BIO_meth_set_ctrl(bio_methods, wst_bio_ctrl);
777 BIO_meth_set_create(bio_methods, wst_bio_new);
778 BIO_meth_set_destroy(bio_methods, wst_bio_free);
784static BOOL wst_parse_url(rdpWst* wst,
const char* url)
786 const char* hostStart =
nullptr;
787 const char* pos =
nullptr;
791 free(wst->gwhostname);
792 wst->gwhostname =
nullptr;
794 wst->gwpath =
nullptr;
796 if (strncmp(
"wss://", url, 6) != 0)
798 if (strncmp(
"https://", url, 8) != 0)
800 WLog_Print(wst->log, WLOG_ERROR,
801 "Websocket URL is invalid. Only wss:// or https:// URLs are supported");
811 while (*pos !=
'\0' && *pos !=
':' && *pos !=
'/')
813 free(wst->gwhostname);
814 wst->gwhostname =
nullptr;
815 if (pos - hostStart == 0)
817 wst->gwhostname = strndup(hostStart, WINPR_ASSERTING_INT_CAST(
size_t, (pos - hostStart)));
818 if (!wst->gwhostname)
823 char port[6] = WINPR_C_ARRAY_INIT;
824 char* portNumberEnd =
nullptr;
826 const char* portStart = pos;
827 while (*pos !=
'\0' && *pos !=
'/')
829 if (pos - portStart > 5 || pos - portStart == 0)
831 strncpy(port, portStart, WINPR_ASSERTING_INT_CAST(
size_t, (pos - portStart)));
832 port[pos - portStart] =
'\0';
833 long _p = strtol(port, &portNumberEnd, 10);
834 if (portNumberEnd && (*portNumberEnd ==
'\0') && (_p > 0) && (_p <= UINT16_MAX))
835 wst->gwport = (uint16_t)_p;
841 wst->gwpath = _strdup(pos);
842 return (wst->gwpath !=
nullptr);
845rdpWst* wst_new(rdpContext* context)
850 rdpWst* wst = (rdpWst*)calloc(1,
sizeof(rdpWst));
854 wst->log = WLog_Get(TAG);
855 wst->context = context;
857 wst->gwhostname =
nullptr;
859 wst->gwpath =
nullptr;
861 if (!wst_parse_url(wst, context->settings->GatewayUrl))
862 goto wst_alloc_error;
864 wst->tls = freerdp_tls_new(wst->context);
866 goto wst_alloc_error;
868 wst->http = http_context_new();
871 goto wst_alloc_error;
874 const char* useragent =
876 const char* msuseragent =
878 if (!http_context_set_uri(wst->http, wst->gwpath) ||
879 !http_context_set_accept(wst->http,
"*/*") ||
880 !http_context_set_cache_control(wst->http,
"no-cache") ||
881 !http_context_set_pragma(wst->http,
"no-cache") ||
882 !http_context_set_connection(wst->http,
"Keep-Alive") ||
883 !http_context_set_user_agent(wst->http, useragent) ||
884 !http_context_set_x_ms_user_agent(wst->http, msuseragent) ||
885 !http_context_set_host(wst->http, wst->gwhostname) ||
886 !http_context_enable_websocket_upgrade(wst->http, TRUE))
888 goto wst_alloc_error;
892 wst->frontBio = BIO_new(BIO_s_wst());
895 goto wst_alloc_error;
897 BIO_set_data(wst->frontBio, wst);
898 InitializeCriticalSection(&wst->writeSection);
899 wst->auth = credssp_auth_new(context);
901 goto wst_alloc_error;
903 wst->wscontext = websocket_context_new();
905 goto wst_alloc_error;
909 WINPR_PRAGMA_DIAG_PUSH
910 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
912 WINPR_PRAGMA_DIAG_POP
916void wst_free(rdpWst* wst)
921 freerdp_tls_free(wst->tls);
922 http_context_free(wst->http);
923 credssp_auth_free(wst->auth);
924 free(wst->gwhostname);
928 BIO_free_all(wst->frontBio);
930 DeleteCriticalSection(&wst->writeSection);
932 websocket_context_free(wst->wscontext);
937BIO* wst_get_front_bio_and_take_ownership(rdpWst* wst)
942 wst->attached = TRUE;
943 return wst->frontBio;
WINPR_ATTR_NODISCARD FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.