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";
75static BOOL wst_uri_has_clmtk_bearer(
const char* uri)
79 for (
const char* p = uri; *p; p++)
81 if (_strnicmp(p,
"ClmTk=", 6) == 0)
87static BOOL wst_get_gateway_credentials(wLog* log, rdpContext* context, rdp_auth_reason reason)
89 WINPR_ASSERT(context);
90 freerdp* instance = context->instance;
92 auth_status rc = utils_authenticate_gateway(instance, reason);
99 freerdp_set_last_error_log(instance->context, FREERDP_ERROR_CONNECT_CANCELLED);
101 case AUTH_NO_CREDENTIALS:
102 WLog_Print(log, WLOG_INFO,
"No credentials provided - using nullptr identity");
110static BOOL wst_auth_init(rdpWst* wst, rdpTls* tls, TCHAR* authPkg)
114 WINPR_ASSERT(authPkg);
116 rdpContext* context = wst->context;
117 rdpSettings* settings = context->settings;
118 SEC_WINNT_AUTH_IDENTITY identity = WINPR_C_ARRAY_INIT;
121 wst->auth_required = TRUE;
122 if (!credssp_auth_init(wst->auth, authPkg, tls->Bindings))
125 if (!wst_get_gateway_credentials(wst->log, context, GW_AUTH_RDG))
128 if (!identity_set_from_settings(&identity, settings, FreeRDP_GatewayUsername,
129 FreeRDP_GatewayDomain, FreeRDP_GatewayPassword))
133 SEC_WINNT_AUTH_IDENTITY* identityArg = (GatewayUsername ? &identity :
nullptr);
134 if (!credssp_auth_setup_client(wst->auth,
"HTTP", wst->gwhostname, identityArg,
nullptr))
136 sspi_FreeAuthIdentity(&identity);
139 sspi_FreeAuthIdentity(&identity);
141 credssp_auth_set_flags(wst->auth, ISC_REQ_CONFIDENTIALITY | ISC_REQ_MUTUAL_AUTH);
143 rc = credssp_auth_authenticate(wst->auth);
147static BOOL wst_set_auth_header(rdpCredsspAuth* auth, HttpRequest* request)
150 WINPR_ASSERT(request);
152 const SecBuffer* authToken = credssp_auth_get_output_buffer(auth);
153 char* base64AuthToken =
nullptr;
157 if (authToken->cbBuffer > INT_MAX)
160 base64AuthToken = crypto_base64_encode(authToken->pvBuffer, authToken->cbBuffer);
165 BOOL rc = http_request_set_auth_scheme(request, credssp_auth_pkg_name(auth)) &&
166 http_request_set_auth_param(request, base64AuthToken);
167 free(base64AuthToken);
176static BOOL wst_recv_auth_token(rdpCredsspAuth* auth, HttpResponse* response, BOOL* pHaveToken)
179 size_t authTokenLength = 0;
180 BYTE* authTokenData =
nullptr;
181 SecBuffer authToken = WINPR_C_ARRAY_INIT;
184 WINPR_ASSERT(pHaveToken);
187 if (!auth || !response)
190 const UINT16 StatusCode = http_response_get_status_code(response);
193 case HTTP_STATUS_DENIED:
197 http_response_log_error_status(WLog_Get(TAG), WLOG_WARN, response);
201 const char* token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth));
211 len = strlen(token64);
213 crypto_base64_decode(token64, len, &authTokenData, &authTokenLength);
215 if (authTokenLength && (authTokenLength <= UINT32_MAX) && authTokenData)
217 authToken.pvBuffer = authTokenData;
218 authToken.cbBuffer = (UINT32)authTokenLength;
219 credssp_auth_take_input_buffer(auth, &authToken);
224 rc = credssp_auth_authenticate(auth);
228static BOOL wst_tls_connect(rdpWst* wst, rdpTls* tls, UINT32 timeout)
233 const char* peerHostname = wst->gwhostname;
234 UINT16 peerPort = wst->gwport;
236 tls->hostname = wst->gwhostname;
237 tls->port = peerPort;
238 tls->isGatewayTransport = TRUE;
239 return utils_tls_connect(wst->context, tls, wst->log, peerHostname, peerPort, FALSE, timeout);
242static wStream* wst_build_http_request(rdpWst* wst)
249 const char* uri = http_context_get_uri(wst->http);
250 HttpRequest* request = http_request_new();
255 if (!http_request_set_method(request,
"GET") || !http_request_set_uri(request, uri))
258 if (wst->auth_required)
260 if (!wst_set_auth_header(wst->auth, request))
267 if (!wst_uri_has_clmtk_bearer(uri))
269 if (!http_request_set_auth_scheme(request,
"Bearer"))
271 if (!http_request_set_auth_param(
273 FreeRDP_GatewayHttpExtAuthBearer)))
278 s = http_request_write(wst->http, request);
280 http_request_free(request);
283 Stream_SealLength(s);
288static BOOL wst_send_http_request(rdpWst* wst, rdpTls* tls)
293 wStream* s = wst_build_http_request(wst);
297 const size_t sz = Stream_Length(s);
298 WLog_Print(wst->log, WLOG_TRACE,
"header [%" PRIuz
"]: %s", sz, Stream_Buffer(s));
300 const int status = freerdp_tls_write_all(tls, Stream_Buffer(s), sz);
301 Stream_Free(s, TRUE);
302 return (status >= 0);
305static BOOL wst_handle_ok_or_forbidden(rdpWst* wst, HttpResponse** ppresponse, DWORD timeout,
309 WINPR_ASSERT(ppresponse);
310 WINPR_ASSERT(*ppresponse);
311 WINPR_ASSERT(pStatusCode);
314 const char* affinity = http_response_get_setcookie(*ppresponse,
"ARRAffinity");
315 const char* samesite = http_response_get_setcookie(*ppresponse,
"ARRAffinitySameSite");
316 if ((affinity || samesite) &&
319 WLog_Print(wst->log, WLOG_INFO,
"Got ARRAffinity cookie %s", affinity);
320 WLog_Print(wst->log, WLOG_INFO,
"Got ARRAffinitySameSite cookie %s", samesite);
323 if (!http_context_set_cookie(wst->http,
"ARRAffinity", affinity))
328 if (!http_context_set_cookie(wst->http,
"ARRAffinitySameSite", samesite))
331 http_response_free(*ppresponse);
332 *ppresponse =
nullptr;
334 const long fd = BIO_get_fd(wst->tls->bio,
nullptr);
335 if ((fd >= 0) && (fd <= INT32_MAX))
336 closesocket((SOCKET)fd);
337 freerdp_tls_free(wst->tls);
339 wst->tls = freerdp_tls_new(wst->context);
340 if (!wst_tls_connect(wst, wst->tls, timeout))
346 char* urlWithAuth =
nullptr;
348 char firstParam = (strchr(wst->gwpath,
'?') !=
nullptr) ?
'&' :
'?';
350 FreeRDP_GatewayHttpExtAuthBearer);
351 if (winpr_asprintf(&urlWithAuth, &urlLen, arm_query_param, wst->gwpath, firstParam,
356 wst->gwpath = urlWithAuth;
359 if (!http_context_set_uri(wst->http, wst->gwpath))
361 if (!http_context_enable_websocket_upgrade(wst->http, TRUE))
365 if (!wst_send_http_request(wst, wst->tls))
367 *ppresponse = http_response_recv(wst->tls, TRUE);
371 (void)http_response_extract_cookies(*ppresponse, wst->http);
372 *pStatusCode = http_response_get_status_code(*ppresponse);
378static BOOL wst_handle_denied(rdpWst* wst, HttpResponse** ppresponse, UINT16* pStatusCode)
381 WINPR_ASSERT(ppresponse);
382 WINPR_ASSERT(*ppresponse);
383 WINPR_ASSERT(pStatusCode);
388 if (!wst_auth_init(wst, wst->tls, AUTH_PKG))
390 if (!wst_send_http_request(wst, wst->tls))
393 http_response_free(*ppresponse);
394 *ppresponse = http_response_recv(wst->tls, TRUE);
398 (void)http_response_extract_cookies(*ppresponse, wst->http);
400 while (!credssp_auth_is_complete(wst->auth))
402 BOOL haveToken = FALSE;
404 if (!wst_recv_auth_token(wst->auth, *ppresponse, &haveToken))
409 WLog_Print(wst->log, WLOG_DEBUG,
410 "No authentication token in the response, ending the exchange");
414 if (credssp_auth_have_output_token(wst->auth))
416 if (!wst_send_http_request(wst, wst->tls))
419 http_response_free(*ppresponse);
420 *ppresponse = http_response_recv(wst->tls, TRUE);
423 (void)http_response_extract_cookies(*ppresponse, wst->http);
428 *pStatusCode = http_response_get_status_code(*ppresponse);
432static BOOL wst_handle_http_code(rdpWst* wst, UINT16 StatusCode)
436 case HTTP_STATUS_PAYMENT_REQ:
437 case HTTP_STATUS_FORBIDDEN:
438 case HTTP_STATUS_DENIED:
439 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);
441 case HTTP_STATUS_MOVED:
442 case HTTP_STATUS_USE_PROXY:
443 case HTTP_STATUS_BAD_REQUEST:
444 case HTTP_STATUS_NOT_FOUND:
445 case HTTP_STATUS_GONE:
446 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
448 case HTTP_STATUS_SERVER_ERROR:
449 case HTTP_STATUS_NOT_SUPPORTED:
450 case HTTP_STATUS_BAD_GATEWAY:
451 case HTTP_STATUS_SERVICE_UNAVAIL:
452 case HTTP_STATUS_VERSION_NOT_SUP:
453 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
455 case HTTP_STATUS_GATEWAY_TIMEOUT:
456 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_ACTIVATION_TIMEOUT);
462 char buffer[64] = WINPR_C_ARRAY_INIT;
463 WLog_Print(wst->log, WLOG_ERROR,
"Unexpected HTTP status: %s",
464 freerdp_http_status_string_format(StatusCode, buffer, ARRAYSIZE(buffer)));
465 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
469BOOL wst_connect(rdpWst* wst, DWORD timeout)
472 WINPR_ASSERT(wst->context);
474 if (!wst_tls_connect(wst, wst->tls, timeout))
476 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
487 if (!http_context_enable_websocket_upgrade(wst->http, FALSE))
489 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
493 if (!wst_send_http_request(wst, wst->tls))
495 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
499 HttpResponse* response = http_response_recv(wst->tls, TRUE);
502 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
505 (void)http_response_extract_cookies(response, wst->http);
507 UINT16 StatusCode = http_response_get_status_code(response);
511 case HTTP_STATUS_FORBIDDEN:
513 success = wst_handle_ok_or_forbidden(wst, &response, timeout, &StatusCode);
516 case HTTP_STATUS_DENIED:
517 success = wst_handle_denied(wst, &response, &StatusCode);
520 http_response_log_error_status(WLog_Get(TAG), WLOG_WARN, response);
524 const BOOL isWebsocket = http_response_is_websocket(wst->http, response);
525 http_response_free(response);
527 return wst_handle_http_code(wst, StatusCode);
530 return websocket_context_reset(wst->wscontext);
532 return wst_handle_http_code(wst, StatusCode);
535DWORD wst_get_event_handles(rdpWst* wst, HANDLE* events, DWORD count)
538 WINPR_ASSERT(wst !=
nullptr);
542 if (events && (nCount < count))
544 BIO_get_event(wst->tls->bio, &events[nCount]);
554static int wst_bio_write(BIO* bio,
const char* buf,
int num)
560 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
562 BIO_clear_flags(bio, BIO_FLAGS_WRITE);
563 EnterCriticalSection(&wst->writeSection);
564 status = websocket_context_write(wst->wscontext, wst->tls->bio, (
const BYTE*)buf, num,
565 WebsocketBinaryOpcode);
566 LeaveCriticalSection(&wst->writeSection);
570 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
573 else if (status < num)
575 BIO_set_flags(bio, BIO_FLAGS_WRITE);
576 WSASetLastError(WSAEWOULDBLOCK);
580 BIO_set_flags(bio, BIO_FLAGS_WRITE);
586static int wst_bio_read(BIO* bio,
char* buf,
int size)
591 WINPR_ASSERT(size >= 0);
593 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
598 status = websocket_context_read(wst->wscontext, wst->tls->bio, (BYTE*)buf, (
size_t)size);
601 if (!BIO_should_retry(wst->tls->bio))
609 BIO_clear_retry_flags(bio);
612 else if (status == 0)
614 BIO_set_retry_read(bio);
615 WSASetLastError(WSAEWOULDBLOCK);
620 BIO_set_flags(bio, BIO_FLAGS_READ);
626static int wst_bio_puts(BIO* bio,
const char* str)
634static int wst_bio_gets(BIO* bio,
char* str,
int size)
642static long wst_bio_ctrl(BIO* bio,
int cmd,
long arg1,
void* arg2)
647 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
649 rdpTls* tls = wst->tls;
651 if (cmd == BIO_CTRL_FLUSH)
653 (void)BIO_flush(tls->bio);
656 else if (cmd == BIO_C_SET_NONBLOCK)
660 else if (cmd == BIO_C_READ_BLOCKED)
662 status = BIO_read_blocked(tls->bio);
664 else if (cmd == BIO_C_WRITE_BLOCKED)
666 status = BIO_write_blocked(tls->bio);
668 else if (cmd == BIO_C_WAIT_READ)
670 int timeout = (int)arg1;
672 if (BIO_read_blocked(tls->bio))
673 return BIO_wait_read(tls->bio, timeout);
676 else if (cmd == BIO_C_WAIT_WRITE)
678 int timeout = (int)arg1;
680 if (BIO_write_blocked(tls->bio))
681 status = BIO_wait_write(tls->bio, timeout);
685 else if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)
687 status = BIO_ctrl(tls->bio, cmd, arg1, arg2);
689#if OPENSSL_VERSION_NUMBER >= 0x30000000L
690 else if (cmd == BIO_CTRL_GET_KTLS_SEND)
698 else if (cmd == BIO_CTRL_GET_KTLS_RECV)
709static int wst_bio_new(BIO* bio)
711 BIO_set_init(bio, 1);
712 BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
716static int wst_bio_free(BIO* bio)
722static BIO_METHOD* BIO_s_wst(
void)
724 static BIO_METHOD* bio_methods =
nullptr;
726 if (bio_methods ==
nullptr)
728 if (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG,
"WSTransport")))
731 BIO_meth_set_write(bio_methods, wst_bio_write);
732 BIO_meth_set_read(bio_methods, wst_bio_read);
733 BIO_meth_set_puts(bio_methods, wst_bio_puts);
734 BIO_meth_set_gets(bio_methods, wst_bio_gets);
735 BIO_meth_set_ctrl(bio_methods, wst_bio_ctrl);
736 BIO_meth_set_create(bio_methods, wst_bio_new);
737 BIO_meth_set_destroy(bio_methods, wst_bio_free);
743static BOOL wst_parse_url(rdpWst* wst,
const char* url)
745 const char* hostStart =
nullptr;
746 const char* pos =
nullptr;
750 free(wst->gwhostname);
751 wst->gwhostname =
nullptr;
753 wst->gwpath =
nullptr;
755 if (strncmp(
"wss://", url, 6) != 0)
757 if (strncmp(
"https://", url, 8) != 0)
759 WLog_Print(wst->log, WLOG_ERROR,
760 "Websocket URL is invalid. Only wss:// or https:// URLs are supported");
770 while (*pos !=
'\0' && *pos !=
':' && *pos !=
'/')
772 free(wst->gwhostname);
773 wst->gwhostname =
nullptr;
774 if (pos - hostStart == 0)
776 wst->gwhostname = strndup(hostStart, WINPR_ASSERTING_INT_CAST(
size_t, (pos - hostStart)));
777 if (!wst->gwhostname)
782 char port[6] = WINPR_C_ARRAY_INIT;
783 char* portNumberEnd =
nullptr;
785 const char* portStart = pos;
786 while (*pos !=
'\0' && *pos !=
'/')
788 if (pos - portStart > 5 || pos - portStart == 0)
790 strncpy(port, portStart, WINPR_ASSERTING_INT_CAST(
size_t, (pos - portStart)));
791 port[pos - portStart] =
'\0';
792 long _p = strtol(port, &portNumberEnd, 10);
793 if (portNumberEnd && (*portNumberEnd ==
'\0') && (_p > 0) && (_p <= UINT16_MAX))
794 wst->gwport = (uint16_t)_p;
800 wst->gwpath = _strdup(pos);
801 return (wst->gwpath !=
nullptr);
804rdpWst* wst_new(rdpContext* context)
809 rdpWst* wst = (rdpWst*)calloc(1,
sizeof(rdpWst));
813 wst->log = WLog_Get(TAG);
814 wst->context = context;
816 wst->gwhostname =
nullptr;
818 wst->gwpath =
nullptr;
821 if (!wst_parse_url(wst, GatewayUrl))
822 goto wst_alloc_error;
824 wst->tls = freerdp_tls_new(wst->context);
826 goto wst_alloc_error;
828 wst->http = http_context_new();
831 goto wst_alloc_error;
834 const char* useragent =
836 const char* msuseragent =
838 if (!http_context_set_uri(wst->http, wst->gwpath) ||
839 !http_context_set_accept(wst->http,
"*/*") ||
840 !http_context_set_cache_control(wst->http,
"no-cache") ||
841 !http_context_set_pragma(wst->http,
"no-cache") ||
842 !http_context_set_connection(wst->http,
"Keep-Alive") ||
843 !http_context_set_user_agent(wst->http, useragent) ||
844 !http_context_set_x_ms_user_agent(wst->http, msuseragent) ||
845 !http_context_set_host(wst->http, wst->gwhostname) ||
846 !http_context_enable_websocket_upgrade(wst->http, TRUE))
848 goto wst_alloc_error;
852 wst->frontBio = BIO_new(BIO_s_wst());
855 goto wst_alloc_error;
857 BIO_set_data(wst->frontBio, wst);
858 InitializeCriticalSection(&wst->writeSection);
859 wst->auth = credssp_auth_new(context);
861 goto wst_alloc_error;
863 wst->wscontext = websocket_context_new();
865 goto wst_alloc_error;
869 WINPR_PRAGMA_DIAG_PUSH
870 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
872 WINPR_PRAGMA_DIAG_POP
876void wst_free(rdpWst* wst)
881 freerdp_tls_free(wst->tls);
882 http_context_free(wst->http);
883 credssp_auth_free(wst->auth);
884 free(wst->gwhostname);
888 BIO_free_all(wst->frontBio);
890 DeleteCriticalSection(&wst->writeSection);
892 websocket_context_free(wst->wscontext);
897BIO* wst_get_front_bio_and_take_ownership(rdpWst* wst)
902 wst->attached = TRUE;
903 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.