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 NULL 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 = { 0 };
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 : NULL);
120 if (!credssp_auth_setup_client(wst->auth,
"HTTP", wst->gwhostname, identityArg, NULL))
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);
136static BOOL wst_set_auth_header(rdpCredsspAuth* auth, HttpRequest* request)
139 WINPR_ASSERT(request);
141 const SecBuffer* authToken = credssp_auth_get_output_buffer(auth);
142 char* base64AuthToken = NULL;
146 if (authToken->cbBuffer > INT_MAX)
149 base64AuthToken = crypto_base64_encode(authToken->pvBuffer, authToken->cbBuffer);
154 BOOL rc = http_request_set_auth_scheme(request, credssp_auth_pkg_name(auth)) &&
155 http_request_set_auth_param(request, base64AuthToken);
156 free(base64AuthToken);
165static BOOL wst_recv_auth_token(rdpCredsspAuth* auth, HttpResponse* response)
168 size_t authTokenLength = 0;
169 BYTE* authTokenData = NULL;
173 if (!auth || !response)
176 const UINT16 StatusCode = http_response_get_status_code(response);
179 case HTTP_STATUS_DENIED:
183 http_response_log_error_status(WLog_Get(TAG), WLOG_WARN, response);
187 const char* token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth));
192 len = strlen(token64);
194 crypto_base64_decode(token64, len, &authTokenData, &authTokenLength);
196 if (authTokenLength && (authTokenLength <= UINT32_MAX) && authTokenData)
198 authToken.pvBuffer = authTokenData;
199 authToken.cbBuffer = (UINT32)authTokenLength;
200 credssp_auth_take_input_buffer(auth, &authToken);
205 rc = credssp_auth_authenticate(auth);
212static BOOL wst_tls_connect(rdpWst* wst, rdpTls* tls, UINT32 timeout)
218 BIO* socketBio = NULL;
219 BIO* bufferedBio = NULL;
220 rdpSettings* settings = wst->context->settings;
221 const char* peerHostname = wst->gwhostname;
222 UINT16 peerPort = wst->gwport;
223 const char* proxyUsername = NULL;
224 const char* proxyPassword = NULL;
225 BOOL isProxyConnection =
226 proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);
228 sockfd = freerdp_tcp_connect(wst->context, peerHostname, peerPort, timeout);
230 WLog_Print(wst->log, WLOG_DEBUG,
"connecting to %s %d", peerHostname, peerPort);
236 socketBio = BIO_new(BIO_s_simple_socket());
240 closesocket((SOCKET)sockfd);
244 BIO_set_fd(socketBio, sockfd, BIO_CLOSE);
245 bufferedBio = BIO_new(BIO_s_buffered_socket());
249 BIO_free_all(socketBio);
253 bufferedBio = BIO_push(bufferedBio, socketBio);
254 status = BIO_set_nonblock(bufferedBio, TRUE);
256 if (isProxyConnection)
258 if (!proxy_connect(wst->context, bufferedBio, proxyUsername, proxyPassword, wst->gwhostname,
261 BIO_free_all(bufferedBio);
268 BIO_free_all(bufferedBio);
272 tls->hostname = wst->gwhostname;
273 tls->port = MIN(UINT16_MAX, wst->gwport);
274 tls->isGatewayTransport = TRUE;
275 status = freerdp_tls_connect(tls, bufferedBio);
278 rdpContext* context = wst->context;
281 freerdp_set_last_error_if_not(context, FREERDP_ERROR_TLS_CONNECT_FAILED);
285 freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_CANCELLED);
290 return (status >= 1);
293static wStream* wst_build_http_request(rdpWst* wst)
296 HttpRequest* request = NULL;
297 const char* uri = NULL;
302 uri = http_context_get_uri(wst->http);
303 request = http_request_new();
308 if (!http_request_set_method(request,
"GET") || !http_request_set_uri(request, uri))
311 if (wst->auth_required)
313 if (!wst_set_auth_header(wst->auth, request))
318 http_request_set_auth_scheme(request,
"Bearer");
319 http_request_set_auth_param(
324 s = http_request_write(wst->http, request);
326 http_request_free(request);
329 Stream_SealLength(s);
334static BOOL wst_send_http_request(rdpWst* wst, rdpTls* tls)
339 wStream* s = wst_build_http_request(wst);
343 const size_t sz = Stream_Length(s);
344 WLog_Print(wst->log, WLOG_TRACE,
"header [%" PRIuz
"]: %s", sz, Stream_Buffer(s));
346 const int status = freerdp_tls_write_all(tls, Stream_Buffer(s), sz);
347 Stream_Free(s, TRUE);
348 return (status >= 0);
351static BOOL wst_handle_ok_or_forbidden(rdpWst* wst, HttpResponse** ppresponse, DWORD timeout,
355 WINPR_ASSERT(ppresponse);
356 WINPR_ASSERT(*ppresponse);
357 WINPR_ASSERT(pStatusCode);
360 const char* affinity = http_response_get_setcookie(*ppresponse,
"ARRAffinity");
361 const char* samesite = http_response_get_setcookie(*ppresponse,
"ARRAffinitySameSite");
362 if ((affinity || samesite) &&
365 WLog_Print(wst->log, WLOG_INFO,
"Got ARRAffinity cookie %s", affinity);
366 WLog_Print(wst->log, WLOG_INFO,
"Got ARRAffinitySameSite cookie %s", samesite);
368 http_context_set_cookie(wst->http,
"ARRAffinity", affinity);
370 http_context_set_cookie(wst->http,
"ARRAffinitySameSite", samesite);
371 http_response_free(*ppresponse);
374 const long fd = BIO_get_fd(wst->tls->bio, NULL);
375 if ((fd >= 0) && (fd <= INT32_MAX))
376 closesocket((SOCKET)fd);
377 freerdp_tls_free(wst->tls);
379 wst->tls = freerdp_tls_new(wst->context);
380 if (!wst_tls_connect(wst, wst->tls, timeout))
386 char* urlWithAuth = NULL;
388 char firstParam = (strchr(wst->gwpath,
'?') != NULL) ?
'&' :
'?';
390 FreeRDP_GatewayHttpExtAuthBearer);
393 winpr_asprintf(&urlWithAuth, &urlLen, arm_query_param, wst->gwpath, firstParam, bearer,
398 wst->gwpath = urlWithAuth;
399 if (!utils_str_is_empty(ua))
403 winpr_asprintf(&uastr, &ualen,
"%s&X-MS-User-Agent=%s", wst->gwpath, ua);
409 if (!http_context_set_uri(wst->http, wst->gwpath))
411 if (!http_context_enable_websocket_upgrade(wst->http, TRUE))
415 if (!wst_send_http_request(wst, wst->tls))
417 *ppresponse = http_response_recv(wst->tls, TRUE);
421 (void)http_response_extract_cookies(*ppresponse, wst->http);
422 *pStatusCode = http_response_get_status_code(*ppresponse);
428static BOOL wst_handle_denied(rdpWst* wst, HttpResponse** ppresponse, UINT16* pStatusCode)
431 WINPR_ASSERT(ppresponse);
432 WINPR_ASSERT(*ppresponse);
433 WINPR_ASSERT(pStatusCode);
438 if (!wst_auth_init(wst, wst->tls, AUTH_PKG))
440 if (!wst_send_http_request(wst, wst->tls))
443 http_response_free(*ppresponse);
444 *ppresponse = http_response_recv(wst->tls, TRUE);
448 (void)http_response_extract_cookies(*ppresponse, wst->http);
450 while (!credssp_auth_is_complete(wst->auth))
452 if (!wst_recv_auth_token(wst->auth, *ppresponse))
455 if (credssp_auth_have_output_token(wst->auth))
457 if (!wst_send_http_request(wst, wst->tls))
460 http_response_free(*ppresponse);
461 *ppresponse = http_response_recv(wst->tls, TRUE);
464 (void)http_response_extract_cookies(*ppresponse, wst->http);
467 *pStatusCode = http_response_get_status_code(*ppresponse);
471static BOOL wst_handle_http_code(rdpWst* wst, UINT16 StatusCode)
475 case HTTP_STATUS_PAYMENT_REQ:
476 case HTTP_STATUS_FORBIDDEN:
477 case HTTP_STATUS_DENIED:
478 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);
480 case HTTP_STATUS_MOVED:
481 case HTTP_STATUS_USE_PROXY:
482 case HTTP_STATUS_BAD_REQUEST:
483 case HTTP_STATUS_NOT_FOUND:
484 case HTTP_STATUS_GONE:
485 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
487 case HTTP_STATUS_SERVER_ERROR:
488 case HTTP_STATUS_NOT_SUPPORTED:
489 case HTTP_STATUS_BAD_GATEWAY:
490 case HTTP_STATUS_SERVICE_UNAVAIL:
491 case HTTP_STATUS_VERSION_NOT_SUP:
492 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
494 case HTTP_STATUS_GATEWAY_TIMEOUT:
495 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_ACTIVATION_TIMEOUT);
501 char buffer[64] = { 0 };
502 WLog_Print(wst->log, WLOG_ERROR,
"Unexpected HTTP status: %s",
503 freerdp_http_status_string_format(StatusCode, buffer, ARRAYSIZE(buffer)));
504 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
508BOOL wst_connect(rdpWst* wst, DWORD timeout)
511 WINPR_ASSERT(wst->context);
513 if (!wst_tls_connect(wst, wst->tls, timeout))
515 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
526 http_context_enable_websocket_upgrade(wst->http, FALSE);
528 if (!wst_send_http_request(wst, wst->tls))
530 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
534 HttpResponse* response = http_response_recv(wst->tls, TRUE);
537 freerdp_set_last_error_if_not(wst->context, FREERDP_ERROR_CONNECT_FAILED);
540 (void)http_response_extract_cookies(response, wst->http);
542 UINT16 StatusCode = http_response_get_status_code(response);
546 case HTTP_STATUS_FORBIDDEN:
548 success = wst_handle_ok_or_forbidden(wst, &response, timeout, &StatusCode);
551 case HTTP_STATUS_DENIED:
552 success = wst_handle_denied(wst, &response, &StatusCode);
555 http_response_log_error_status(WLog_Get(TAG), WLOG_WARN, response);
559 const BOOL isWebsocket = http_response_is_websocket(wst->http, response);
560 http_response_free(response);
562 return wst_handle_http_code(wst, StatusCode);
565 return websocket_context_reset(wst->wscontext);
567 return wst_handle_http_code(wst, StatusCode);
570DWORD wst_get_event_handles(rdpWst* wst, HANDLE* events, DWORD count)
573 WINPR_ASSERT(wst != NULL);
577 if (events && (nCount < count))
579 BIO_get_event(wst->tls->bio, &events[nCount]);
589static int wst_bio_write(BIO* bio,
const char* buf,
int num)
595 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
597 BIO_clear_flags(bio, BIO_FLAGS_WRITE);
598 EnterCriticalSection(&wst->writeSection);
599 status = websocket_context_write(wst->wscontext, wst->tls->bio, (
const BYTE*)buf, num,
600 WebsocketBinaryOpcode);
601 LeaveCriticalSection(&wst->writeSection);
605 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
608 else if (status < num)
610 BIO_set_flags(bio, BIO_FLAGS_WRITE);
611 WSASetLastError(WSAEWOULDBLOCK);
615 BIO_set_flags(bio, BIO_FLAGS_WRITE);
621static int wst_bio_read(BIO* bio,
char* buf,
int size)
626 WINPR_ASSERT(size >= 0);
628 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
633 status = websocket_context_read(wst->wscontext, wst->tls->bio, (BYTE*)buf, (
size_t)size);
636 if (!BIO_should_retry(wst->tls->bio))
644 BIO_clear_retry_flags(bio);
647 else if (status == 0)
649 BIO_set_retry_read(bio);
650 WSASetLastError(WSAEWOULDBLOCK);
655 BIO_set_flags(bio, BIO_FLAGS_READ);
661static int wst_bio_puts(BIO* bio,
const char* str)
669static int wst_bio_gets(BIO* bio,
char* str,
int size)
677static long wst_bio_ctrl(BIO* bio,
int cmd,
long arg1,
void* arg2)
682 rdpWst* wst = (rdpWst*)BIO_get_data(bio);
684 rdpTls* tls = wst->tls;
686 if (cmd == BIO_CTRL_FLUSH)
688 (void)BIO_flush(tls->bio);
691 else if (cmd == BIO_C_SET_NONBLOCK)
695 else if (cmd == BIO_C_READ_BLOCKED)
697 status = BIO_read_blocked(tls->bio);
699 else if (cmd == BIO_C_WRITE_BLOCKED)
701 status = BIO_write_blocked(tls->bio);
703 else if (cmd == BIO_C_WAIT_READ)
705 int timeout = (int)arg1;
707 if (BIO_read_blocked(tls->bio))
708 return BIO_wait_read(tls->bio, timeout);
711 else if (cmd == BIO_C_WAIT_WRITE)
713 int timeout = (int)arg1;
715 if (BIO_write_blocked(tls->bio))
716 status = BIO_wait_write(tls->bio, timeout);
720 else if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)
722 status = BIO_ctrl(tls->bio, cmd, arg1, arg2);
724#if OPENSSL_VERSION_NUMBER >= 0x30000000L
725 else if (cmd == BIO_CTRL_GET_KTLS_SEND)
733 else if (cmd == BIO_CTRL_GET_KTLS_RECV)
744static int wst_bio_new(BIO* bio)
746 BIO_set_init(bio, 1);
747 BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
751static int wst_bio_free(BIO* bio)
757static BIO_METHOD* BIO_s_wst(
void)
759 static BIO_METHOD* bio_methods = NULL;
761 if (bio_methods == NULL)
763 if (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG,
"WSTransport")))
766 BIO_meth_set_write(bio_methods, wst_bio_write);
767 BIO_meth_set_read(bio_methods, wst_bio_read);
768 BIO_meth_set_puts(bio_methods, wst_bio_puts);
769 BIO_meth_set_gets(bio_methods, wst_bio_gets);
770 BIO_meth_set_ctrl(bio_methods, wst_bio_ctrl);
771 BIO_meth_set_create(bio_methods, wst_bio_new);
772 BIO_meth_set_destroy(bio_methods, wst_bio_free);
778static BOOL wst_parse_url(rdpWst* wst,
const char* url)
780 const char* hostStart = NULL;
781 const char* pos = NULL;
785 free(wst->gwhostname);
786 wst->gwhostname = NULL;
790 if (strncmp(
"wss://", url, 6) != 0)
792 if (strncmp(
"https://", url, 8) != 0)
794 WLog_Print(wst->log, WLOG_ERROR,
795 "Websocket URL is invalid. Only wss:// or https:// URLs are supported");
805 while (*pos !=
'\0' && *pos !=
':' && *pos !=
'/')
807 free(wst->gwhostname);
808 wst->gwhostname = NULL;
809 if (pos - hostStart == 0)
811 wst->gwhostname = strndup(hostStart, WINPR_ASSERTING_INT_CAST(
size_t, (pos - hostStart)));
812 if (!wst->gwhostname)
817 char port[6] = { 0 };
818 char* portNumberEnd = NULL;
820 const char* portStart = pos;
821 while (*pos !=
'\0' && *pos !=
'/')
823 if (pos - portStart > 5 || pos - portStart == 0)
825 strncpy(port, portStart, WINPR_ASSERTING_INT_CAST(
size_t, (pos - portStart)));
826 port[pos - portStart] =
'\0';
827 long _p = strtol(port, &portNumberEnd, 10);
828 if (portNumberEnd && (*portNumberEnd ==
'\0') && (_p > 0) && (_p <= UINT16_MAX))
829 wst->gwport = (uint16_t)_p;
835 wst->gwpath = _strdup(pos);
841rdpWst* wst_new(rdpContext* context)
846 rdpWst* wst = (rdpWst*)calloc(1,
sizeof(rdpWst));
850 wst->log = WLog_Get(TAG);
851 wst->context = context;
853 wst->gwhostname = NULL;
857 if (!wst_parse_url(wst, context->settings->GatewayUrl))
858 goto wst_alloc_error;
860 wst->tls = freerdp_tls_new(wst->context);
862 goto wst_alloc_error;
864 wst->http = http_context_new();
867 goto wst_alloc_error;
869 const char* useragent =
871 const char* msuseragent =
873 if (!http_context_set_uri(wst->http, wst->gwpath) ||
874 !http_context_set_accept(wst->http,
"*/*") ||
875 !http_context_set_cache_control(wst->http,
"no-cache") ||
876 !http_context_set_pragma(wst->http,
"no-cache") ||
877 !http_context_set_connection(wst->http,
"Keep-Alive") ||
878 !http_context_set_user_agent(wst->http, useragent) ||
879 !http_context_set_x_ms_user_agent(wst->http, msuseragent) ||
880 !http_context_set_host(wst->http, wst->gwhostname) ||
881 !http_context_enable_websocket_upgrade(wst->http, TRUE))
883 goto wst_alloc_error;
886 wst->frontBio = BIO_new(BIO_s_wst());
889 goto wst_alloc_error;
891 BIO_set_data(wst->frontBio, wst);
892 InitializeCriticalSection(&wst->writeSection);
893 wst->auth = credssp_auth_new(context);
895 goto wst_alloc_error;
897 wst->wscontext = websocket_context_new();
899 goto wst_alloc_error;
903 WINPR_PRAGMA_DIAG_PUSH
904 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
906 WINPR_PRAGMA_DIAG_POP
910void wst_free(rdpWst* wst)
915 freerdp_tls_free(wst->tls);
916 http_context_free(wst->http);
917 credssp_auth_free(wst->auth);
918 free(wst->gwhostname);
922 BIO_free_all(wst->frontBio);
924 DeleteCriticalSection(&wst->writeSection);
926 websocket_context_free(wst->wscontext);
931BIO* wst_get_front_bio_and_take_ownership(rdpWst* wst)
936 wst->attached = TRUE;
937 return wst->frontBio;
FREERDP_API BOOL freerdp_settings_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.
FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.