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))
120 SEC_WINNT_AUTH_IDENTITY* identityArg = (GatewayUsername ? &identity :
nullptr);
121 if (!credssp_auth_setup_client(wst->auth,
"HTTP", wst->gwhostname, identityArg,
nullptr))
123 sspi_FreeAuthIdentity(&identity);
126 sspi_FreeAuthIdentity(&identity);
128 credssp_auth_set_flags(wst->auth, ISC_REQ_CONFIDENTIALITY | ISC_REQ_MUTUAL_AUTH);
130 rc = credssp_auth_authenticate(wst->auth);
134static BOOL wst_set_auth_header(rdpCredsspAuth* auth, HttpRequest* request)
137 WINPR_ASSERT(request);
139 const SecBuffer* authToken = credssp_auth_get_output_buffer(auth);
140 char* base64AuthToken =
nullptr;
144 if (authToken->cbBuffer > INT_MAX)
147 base64AuthToken = crypto_base64_encode(authToken->pvBuffer, authToken->cbBuffer);
152 BOOL rc = http_request_set_auth_scheme(request, credssp_auth_pkg_name(auth)) &&
153 http_request_set_auth_param(request, base64AuthToken);
154 free(base64AuthToken);
163static BOOL wst_recv_auth_token(rdpCredsspAuth* auth, HttpResponse* response)
166 size_t authTokenLength = 0;
167 BYTE* authTokenData =
nullptr;
168 SecBuffer authToken = WINPR_C_ARRAY_INIT;
171 if (!auth || !response)
174 const UINT16 StatusCode = http_response_get_status_code(response);
177 case HTTP_STATUS_DENIED:
181 http_response_log_error_status(WLog_Get(TAG), WLOG_WARN, response);
185 const char* token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth));
190 len = strlen(token64);
192 crypto_base64_decode(token64, len, &authTokenData, &authTokenLength);
194 if (authTokenLength && (authTokenLength <= UINT32_MAX) && authTokenData)
196 authToken.pvBuffer = authTokenData;
197 authToken.cbBuffer = (UINT32)authTokenLength;
198 credssp_auth_take_input_buffer(auth, &authToken);
203 rc = credssp_auth_authenticate(auth);
207static BOOL wst_tls_connect(rdpWst* wst, rdpTls* tls, UINT32 timeout)
213 BIO* socketBio =
nullptr;
214 BIO* bufferedBio =
nullptr;
215 rdpSettings* settings = wst->context->settings;
216 const char* peerHostname = wst->gwhostname;
217 UINT16 peerPort = wst->gwport;
218 const char* proxyUsername =
nullptr;
219 const char* proxyPassword =
nullptr;
220 BOOL isProxyConnection =
221 proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);
223 sockfd = freerdp_tcp_connect(wst->context, peerHostname, peerPort, timeout);
225 WLog_Print(wst->log, WLOG_DEBUG,
"connecting to %s %d", peerHostname, peerPort);
231 socketBio = BIO_new(BIO_s_simple_socket());
235 closesocket((SOCKET)sockfd);
239 BIO_set_fd(socketBio, sockfd, BIO_CLOSE);
240 bufferedBio = BIO_new(BIO_s_buffered_socket());
244 BIO_free_all(socketBio);
248 bufferedBio = BIO_push(bufferedBio, socketBio);
249 status = BIO_set_nonblock(bufferedBio, TRUE);
251 if (isProxyConnection)
253 if (!proxy_connect(wst->context, bufferedBio, proxyUsername, proxyPassword, wst->gwhostname,
256 BIO_free_all(bufferedBio);
263 BIO_free_all(bufferedBio);
267 tls->hostname = wst->gwhostname;
268 tls->port = MIN(UINT16_MAX, wst->gwport);
269 tls->isGatewayTransport = TRUE;
270 status = freerdp_tls_connect(tls, bufferedBio);
273 rdpContext* context = wst->context;
276 freerdp_set_last_error_if_not(context, FREERDP_ERROR_TLS_CONNECT_FAILED);
280 freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_CANCELLED);
285 return (status >= 1);
288static wStream* wst_build_http_request(rdpWst* wst)
291 HttpRequest* request =
nullptr;
292 const char* uri =
nullptr;
297 uri = http_context_get_uri(wst->http);
298 request = http_request_new();
303 if (!http_request_set_method(request,
"GET") || !http_request_set_uri(request, uri))
306 if (wst->auth_required)
308 if (!wst_set_auth_header(wst->auth, request))
313 if (!http_request_set_auth_scheme(request,
"Bearer"))
315 if (!http_request_set_auth_param(
317 FreeRDP_GatewayHttpExtAuthBearer)))
321 s = http_request_write(wst->http, request);
323 http_request_free(request);
326 Stream_SealLength(s);
331static BOOL wst_send_http_request(rdpWst* wst, rdpTls* tls)
336 wStream* s = wst_build_http_request(wst);
340 const size_t sz = Stream_Length(s);
341 WLog_Print(wst->log, WLOG_TRACE,
"header [%" PRIuz
"]: %s", sz, Stream_Buffer(s));
343 const int status = freerdp_tls_write_all(tls, Stream_Buffer(s), sz);
344 Stream_Free(s, TRUE);
345 return (status >= 0);
348static BOOL wst_handle_ok_or_forbidden(rdpWst* wst, HttpResponse** ppresponse, DWORD timeout,
352 WINPR_ASSERT(ppresponse);
353 WINPR_ASSERT(*ppresponse);
354 WINPR_ASSERT(pStatusCode);
357 const char* affinity = http_response_get_setcookie(*ppresponse,
"ARRAffinity");
358 const char* samesite = http_response_get_setcookie(*ppresponse,
"ARRAffinitySameSite");
359 if ((affinity || samesite) &&
362 WLog_Print(wst->log, WLOG_INFO,
"Got ARRAffinity cookie %s", affinity);
363 WLog_Print(wst->log, WLOG_INFO,
"Got ARRAffinitySameSite cookie %s", samesite);
366 if (!http_context_set_cookie(wst->http,
"ARRAffinity", affinity))
371 if (!http_context_set_cookie(wst->http,
"ARRAffinitySameSite", samesite))
374 http_response_free(*ppresponse);
375 *ppresponse =
nullptr;
377 const long fd = BIO_get_fd(wst->tls->bio,
nullptr);
378 if ((fd >= 0) && (fd <= INT32_MAX))
379 closesocket((SOCKET)fd);
380 freerdp_tls_free(wst->tls);
382 wst->tls = freerdp_tls_new(wst->context);
383 if (!wst_tls_connect(wst, wst->tls, timeout))
389 char* urlWithAuth =
nullptr;
391 char firstParam = (strchr(wst->gwpath,
'?') !=
nullptr) ?
'&' :
'?';
393 FreeRDP_GatewayHttpExtAuthBearer);
396 winpr_asprintf(&urlWithAuth, &urlLen, arm_query_param, wst->gwpath, firstParam, bearer,
401 wst->gwpath = urlWithAuth;
402 if (!utils_str_is_empty(ua))
405 char* uastr =
nullptr;
406 winpr_asprintf(&uastr, &ualen,
"%s&X-MS-User-Agent=%s", wst->gwpath, ua);
412 if (!http_context_set_uri(wst->http, wst->gwpath))
414 if (!http_context_enable_websocket_upgrade(wst->http, TRUE))
418 if (!wst_send_http_request(wst, wst->tls))
420 *ppresponse = http_response_recv(wst->tls, TRUE);
424 (void)http_response_extract_cookies(*ppresponse, wst->http);
425 *pStatusCode = http_response_get_status_code(*ppresponse);
431static BOOL wst_handle_denied(rdpWst* wst, HttpResponse** ppresponse, UINT16* pStatusCode)
434 WINPR_ASSERT(ppresponse);
435 WINPR_ASSERT(*ppresponse);
436 WINPR_ASSERT(pStatusCode);
441 if (!wst_auth_init(wst, wst->tls, AUTH_PKG))
443 if (!wst_send_http_request(wst, wst->tls))
446 http_response_free(*ppresponse);
447 *ppresponse = http_response_recv(wst->tls, TRUE);
451 (void)http_response_extract_cookies(*ppresponse, wst->http);
453 while (!credssp_auth_is_complete(wst->auth))
455 if (!wst_recv_auth_token(wst->auth, *ppresponse))
458 if (credssp_auth_have_output_token(wst->auth))
460 if (!wst_send_http_request(wst, wst->tls))
463 http_response_free(*ppresponse);
464 *ppresponse = http_response_recv(wst->tls, TRUE);
467 (void)http_response_extract_cookies(*ppresponse, wst->http);
470 *pStatusCode = http_response_get_status_code(*ppresponse);
474static BOOL wst_handle_http_code(rdpWst* wst, UINT16 StatusCode)
478 case HTTP_STATUS_PAYMENT_REQ:
479 case HTTP_STATUS_FORBIDDEN:
480 case HTTP_STATUS_DENIED:
481 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);
483 case HTTP_STATUS_MOVED:
484 case HTTP_STATUS_USE_PROXY:
485 case HTTP_STATUS_BAD_REQUEST:
486 case HTTP_STATUS_NOT_FOUND:
487 case HTTP_STATUS_GONE:
488 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
490 case HTTP_STATUS_SERVER_ERROR:
491 case HTTP_STATUS_NOT_SUPPORTED:
492 case HTTP_STATUS_BAD_GATEWAY:
493 case HTTP_STATUS_SERVICE_UNAVAIL:
494 case HTTP_STATUS_VERSION_NOT_SUP:
495 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
497 case HTTP_STATUS_GATEWAY_TIMEOUT:
498 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_ACTIVATION_TIMEOUT);
504 char buffer[64] = WINPR_C_ARRAY_INIT;
505 WLog_Print(wst->log, WLOG_ERROR,
"Unexpected HTTP status: %s",
506 freerdp_http_status_string_format(StatusCode, buffer, ARRAYSIZE(buffer)));
507 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
511BOOL wst_connect(rdpWst* wst, DWORD timeout)
514 WINPR_ASSERT(wst->context);
516 if (!wst_tls_connect(wst, wst->tls, timeout))
518 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
529 if (!http_context_enable_websocket_upgrade(wst->http, FALSE))
531 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
535 if (!wst_send_http_request(wst, wst->tls))
537 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
541 HttpResponse* response = http_response_recv(wst->tls, TRUE);
544 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
547 (void)http_response_extract_cookies(response, wst->http);
549 UINT16 StatusCode = http_response_get_status_code(response);
553 case HTTP_STATUS_FORBIDDEN:
555 success = wst_handle_ok_or_forbidden(wst, &response, timeout, &StatusCode);
558 case HTTP_STATUS_DENIED:
559 success = wst_handle_denied(wst, &response, &StatusCode);
562 http_response_log_error_status(WLog_Get(TAG), WLOG_WARN, response);
566 const BOOL isWebsocket = http_response_is_websocket(wst->http, response);
567 http_response_free(response);
569 return wst_handle_http_code(wst, StatusCode);
572 return websocket_context_reset(wst->wscontext);
574 return wst_handle_http_code(wst, StatusCode);
577DWORD wst_get_event_handles(rdpWst* wst, HANDLE* events, DWORD count)
580 WINPR_ASSERT(wst !=
nullptr);
584 if (events && (nCount < count))
586 BIO_get_event(wst->tls->bio, &events[nCount]);
596static int wst_bio_write(BIO* bio,
const char* buf,
int num)
602 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
604 BIO_clear_flags(bio, BIO_FLAGS_WRITE);
605 EnterCriticalSection(&wst->writeSection);
606 status = websocket_context_write(wst->wscontext, wst->tls->bio, (
const BYTE*)buf, num,
607 WebsocketBinaryOpcode);
608 LeaveCriticalSection(&wst->writeSection);
612 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
615 else if (status < num)
617 BIO_set_flags(bio, BIO_FLAGS_WRITE);
618 WSASetLastError(WSAEWOULDBLOCK);
622 BIO_set_flags(bio, BIO_FLAGS_WRITE);
628static int wst_bio_read(BIO* bio,
char* buf,
int size)
633 WINPR_ASSERT(size >= 0);
635 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
640 status = websocket_context_read(wst->wscontext, wst->tls->bio, (BYTE*)buf, (
size_t)size);
643 if (!BIO_should_retry(wst->tls->bio))
651 BIO_clear_retry_flags(bio);
654 else if (status == 0)
656 BIO_set_retry_read(bio);
657 WSASetLastError(WSAEWOULDBLOCK);
662 BIO_set_flags(bio, BIO_FLAGS_READ);
668static int wst_bio_puts(BIO* bio,
const char* str)
676static int wst_bio_gets(BIO* bio,
char* str,
int size)
684static long wst_bio_ctrl(BIO* bio,
int cmd,
long arg1,
void* arg2)
689 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
691 rdpTls* tls = wst->tls;
693 if (cmd == BIO_CTRL_FLUSH)
695 (void)BIO_flush(tls->bio);
698 else if (cmd == BIO_C_SET_NONBLOCK)
702 else if (cmd == BIO_C_READ_BLOCKED)
704 status = BIO_read_blocked(tls->bio);
706 else if (cmd == BIO_C_WRITE_BLOCKED)
708 status = BIO_write_blocked(tls->bio);
710 else if (cmd == BIO_C_WAIT_READ)
712 int timeout = (int)arg1;
714 if (BIO_read_blocked(tls->bio))
715 return BIO_wait_read(tls->bio, timeout);
718 else if (cmd == BIO_C_WAIT_WRITE)
720 int timeout = (int)arg1;
722 if (BIO_write_blocked(tls->bio))
723 status = BIO_wait_write(tls->bio, timeout);
727 else if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)
729 status = BIO_ctrl(tls->bio, cmd, arg1, arg2);
731#if OPENSSL_VERSION_NUMBER >= 0x30000000L
732 else if (cmd == BIO_CTRL_GET_KTLS_SEND)
740 else if (cmd == BIO_CTRL_GET_KTLS_RECV)
751static int wst_bio_new(BIO* bio)
753 BIO_set_init(bio, 1);
754 BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
758static int wst_bio_free(BIO* bio)
764static BIO_METHOD* BIO_s_wst(
void)
766 static BIO_METHOD* bio_methods =
nullptr;
768 if (bio_methods ==
nullptr)
770 if (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG,
"WSTransport")))
773 BIO_meth_set_write(bio_methods, wst_bio_write);
774 BIO_meth_set_read(bio_methods, wst_bio_read);
775 BIO_meth_set_puts(bio_methods, wst_bio_puts);
776 BIO_meth_set_gets(bio_methods, wst_bio_gets);
777 BIO_meth_set_ctrl(bio_methods, wst_bio_ctrl);
778 BIO_meth_set_create(bio_methods, wst_bio_new);
779 BIO_meth_set_destroy(bio_methods, wst_bio_free);
785static BOOL wst_parse_url(rdpWst* wst,
const char* url)
787 const char* hostStart =
nullptr;
788 const char* pos =
nullptr;
792 free(wst->gwhostname);
793 wst->gwhostname =
nullptr;
795 wst->gwpath =
nullptr;
797 if (strncmp(
"wss://", url, 6) != 0)
799 if (strncmp(
"https://", url, 8) != 0)
801 WLog_Print(wst->log, WLOG_ERROR,
802 "Websocket URL is invalid. Only wss:// or https:// URLs are supported");
812 while (*pos !=
'\0' && *pos !=
':' && *pos !=
'/')
814 free(wst->gwhostname);
815 wst->gwhostname =
nullptr;
816 if (pos - hostStart == 0)
818 wst->gwhostname = strndup(hostStart, WINPR_ASSERTING_INT_CAST(
size_t, (pos - hostStart)));
819 if (!wst->gwhostname)
824 char port[6] = WINPR_C_ARRAY_INIT;
825 char* portNumberEnd =
nullptr;
827 const char* portStart = pos;
828 while (*pos !=
'\0' && *pos !=
'/')
830 if (pos - portStart > 5 || pos - portStart == 0)
832 strncpy(port, portStart, WINPR_ASSERTING_INT_CAST(
size_t, (pos - portStart)));
833 port[pos - portStart] =
'\0';
834 long _p = strtol(port, &portNumberEnd, 10);
835 if (portNumberEnd && (*portNumberEnd ==
'\0') && (_p > 0) && (_p <= UINT16_MAX))
836 wst->gwport = (uint16_t)_p;
842 wst->gwpath = _strdup(pos);
843 return (wst->gwpath !=
nullptr);
846rdpWst* wst_new(rdpContext* context)
851 rdpWst* wst = (rdpWst*)calloc(1,
sizeof(rdpWst));
855 wst->log = WLog_Get(TAG);
856 wst->context = context;
858 wst->gwhostname =
nullptr;
860 wst->gwpath =
nullptr;
863 if (!wst_parse_url(wst, GatewayUrl))
864 goto wst_alloc_error;
866 wst->tls = freerdp_tls_new(wst->context);
868 goto wst_alloc_error;
870 wst->http = http_context_new();
873 goto wst_alloc_error;
876 const char* useragent =
878 const char* msuseragent =
880 if (!http_context_set_uri(wst->http, wst->gwpath) ||
881 !http_context_set_accept(wst->http,
"*/*") ||
882 !http_context_set_cache_control(wst->http,
"no-cache") ||
883 !http_context_set_pragma(wst->http,
"no-cache") ||
884 !http_context_set_connection(wst->http,
"Keep-Alive") ||
885 !http_context_set_user_agent(wst->http, useragent) ||
886 !http_context_set_x_ms_user_agent(wst->http, msuseragent) ||
887 !http_context_set_host(wst->http, wst->gwhostname) ||
888 !http_context_enable_websocket_upgrade(wst->http, TRUE))
890 goto wst_alloc_error;
894 wst->frontBio = BIO_new(BIO_s_wst());
897 goto wst_alloc_error;
899 BIO_set_data(wst->frontBio, wst);
900 InitializeCriticalSection(&wst->writeSection);
901 wst->auth = credssp_auth_new(context);
903 goto wst_alloc_error;
905 wst->wscontext = websocket_context_new();
907 goto wst_alloc_error;
911 WINPR_PRAGMA_DIAG_PUSH
912 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
914 WINPR_PRAGMA_DIAG_POP
918void wst_free(rdpWst* wst)
923 freerdp_tls_free(wst->tls);
924 http_context_free(wst->http);
925 credssp_auth_free(wst->auth);
926 free(wst->gwhostname);
930 BIO_free_all(wst->frontBio);
932 DeleteCriticalSection(&wst->writeSection);
934 websocket_context_free(wst->wscontext);
939BIO* wst_get_front_bio_and_take_ownership(rdpWst* wst)
944 wst->attached = TRUE;
945 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.