FreeRDP
Loading...
Searching...
No Matches
rdg.c
1
20#include <stdint.h>
21
22#include <freerdp/config.h>
23
24#include "../settings.h"
25
26#include <winpr/assert.h>
27#include <winpr/cast.h>
28
29#include <winpr/crt.h>
30#include <winpr/synch.h>
31#include <winpr/print.h>
32#include <winpr/stream.h>
33#include <winpr/winsock.h>
34#include <winpr/cred.h>
35
36#include <freerdp/log.h>
37#include <freerdp/error.h>
38#include <freerdp/utils/ringbuffer.h>
39#include <freerdp/utils/smartcardlogon.h>
40
41#include "rdg.h"
42#include "websocket.h"
43#include "../credssp_auth.h"
44#include "../proxy.h"
45#include "../rdp.h"
46#include "../../crypto/opensslcompat.h"
47#include "rpc_fault.h"
48#include "../utils.h"
49
50#define TAG FREERDP_TAG("core.gateway.rdg")
51
52#define AUTH_PKG NEGO_SSP_NAME
53
54/* HTTP channel response fields present flags. */
55#define HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID 0x1
56#define HTTP_CHANNEL_RESPONSE_FIELD_AUTHNCOOKIE 0x2
57#define HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT 0x4
58
59/* HTTP extended auth. */
60#define HTTP_EXTENDED_AUTH_NONE 0x0
61#define HTTP_EXTENDED_AUTH_SC 0x1 /* Smart card authentication. */
62#define HTTP_EXTENDED_AUTH_PAA 0x02 /* Pluggable authentication. */
63#define HTTP_EXTENDED_AUTH_SSPI_NTLM 0x04 /* NTLM extended authentication. */
64#define HTTP_EXTENDED_AUTH_BEARER 0x08 /* HTTP Bearer authentication. */
65
66/* HTTP packet types. */
67typedef enum
68{
69 PKT_TYPE_HANDSHAKE_REQUEST = 0x1,
70 PKT_TYPE_HANDSHAKE_RESPONSE = 0x2,
71 PKT_TYPE_EXTENDED_AUTH_MSG = 0x3,
72 PKT_TYPE_TUNNEL_CREATE = 0x4,
73 PKT_TYPE_TUNNEL_RESPONSE = 0x5,
74 PKT_TYPE_TUNNEL_AUTH = 0x6,
75 PKT_TYPE_TUNNEL_AUTH_RESPONSE = 0x7,
76 PKT_TYPE_CHANNEL_CREATE = 0x8,
77 PKT_TYPE_CHANNEL_RESPONSE = 0x9,
78 PKT_TYPE_DATA = 0xA,
79 PKT_TYPE_SERVICE_MESSAGE = 0xB,
80 PKT_TYPE_REAUTH_MESSAGE = 0xC,
81 PKT_TYPE_KEEPALIVE = 0xD,
82 PKT_TYPE_CLOSE_CHANNEL = 0x10,
83 PKT_TYPE_CLOSE_CHANNEL_RESPONSE = 0x11
84} RdgPktType;
85
86/* HTTP tunnel auth fields present flags. */
87// #define HTTP_TUNNEL_AUTH_FIELD_SOH 0x1
88
89/* HTTP tunnel auth response fields present flags. */
90#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS 0x1
91#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT 0x2
92#define HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE 0x4
93
94/* HTTP tunnel packet fields present flags. */
95#define HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE 0x1
96// #define HTTP_TUNNEL_PACKET_FIELD_REAUTH 0x2
97
98/* HTTP tunnel response fields present flags. */
99#define HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID 0x1
100#define HTTP_TUNNEL_RESPONSE_FIELD_CAPS 0x2
101#define HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ 0x4
102#define HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG 0x10
103
104/* HTTP capability type enumeration. */
105#define HTTP_CAPABILITY_TYPE_QUAR_SOH 0x1
106#define HTTP_CAPABILITY_IDLE_TIMEOUT 0x2
107#define HTTP_CAPABILITY_MESSAGING_CONSENT_SIGN 0x4
108#define HTTP_CAPABILITY_MESSAGING_SERVICE_MSG 0x8
109#define HTTP_CAPABILITY_REAUTH 0x10
110#define HTTP_CAPABILITY_UDP_TRANSPORT 0x20
111
112typedef struct
113{
114 TRANSFER_ENCODING httpTransferEncoding;
115 BOOL isWebsocketTransport;
116 union context
117 {
119 websocket_context* websocket;
120 } context;
121} rdg_http_encoding_context;
122
123struct rdp_rdg
124{
125 rdpContext* context;
126 BOOL attached;
127 BIO* frontBio;
128 rdpTls* tlsIn;
129 rdpTls* tlsOut;
130 rdpCredsspAuth* auth;
131 HttpContext* http;
132 CRITICAL_SECTION writeSection;
133
134 int state;
135 UINT16 packetRemainingCount;
136 UINT16 reserved1;
137 int timeout;
138 UINT16 extAuth;
139 UINT16 reserved2;
140 rdg_http_encoding_context transferEncoding;
141
142 SmartcardCertInfo* smartcard;
143 wLog* log;
144};
145
146enum
147{
148 RDG_CLIENT_STATE_INITIAL,
149 RDG_CLIENT_STATE_HANDSHAKE,
150 RDG_CLIENT_STATE_TUNNEL_CREATE,
151 RDG_CLIENT_STATE_TUNNEL_AUTHORIZE,
152 RDG_CLIENT_STATE_CHANNEL_CREATE,
153 RDG_CLIENT_STATE_OPENED,
154};
155
156#pragma pack(push, 1)
157
158typedef struct rdg_packet_header
159{
160 UINT16 type;
161 UINT16 reserved;
162 UINT32 packetLength;
163} RdgPacketHeader;
164
165#pragma pack(pop)
166
167typedef struct
168{
169 UINT32 code;
170 const char* name;
171} t_flag_mapping;
172
173static const t_flag_mapping tunnel_response_fields_present[] = {
174 { HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID, "HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID" },
175 { HTTP_TUNNEL_RESPONSE_FIELD_CAPS, "HTTP_TUNNEL_RESPONSE_FIELD_CAPS" },
176 { HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ, "HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ" },
177 { HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG, "HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG" }
178};
179
180static const t_flag_mapping channel_response_fields_present[] = {
181 { HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID, "HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID" },
182 { HTTP_CHANNEL_RESPONSE_FIELD_AUTHNCOOKIE, "HTTP_CHANNEL_RESPONSE_FIELD_AUTHNCOOKIE" },
183 { HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT, "HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT" }
184};
185
186static const t_flag_mapping tunnel_authorization_response_fields_present[] = {
187 { HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS, "HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS" },
188 { HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT,
189 "HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT" },
190 { HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE,
191 "HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE" }
192};
193
194static const t_flag_mapping extended_auth[] = {
195 { HTTP_EXTENDED_AUTH_NONE, "HTTP_EXTENDED_AUTH_NONE" },
196 { HTTP_EXTENDED_AUTH_SC, "HTTP_EXTENDED_AUTH_SC" },
197 { HTTP_EXTENDED_AUTH_PAA, "HTTP_EXTENDED_AUTH_PAA" },
198 { HTTP_EXTENDED_AUTH_SSPI_NTLM, "HTTP_EXTENDED_AUTH_SSPI_NTLM" }
199};
200
201static const t_flag_mapping capabilities_enum[] = {
202 { HTTP_CAPABILITY_TYPE_QUAR_SOH, "HTTP_CAPABILITY_TYPE_QUAR_SOH" },
203 { HTTP_CAPABILITY_IDLE_TIMEOUT, "HTTP_CAPABILITY_IDLE_TIMEOUT" },
204 { HTTP_CAPABILITY_MESSAGING_CONSENT_SIGN, "HTTP_CAPABILITY_MESSAGING_CONSENT_SIGN" },
205 { HTTP_CAPABILITY_MESSAGING_SERVICE_MSG, "HTTP_CAPABILITY_MESSAGING_SERVICE_MSG" },
206 { HTTP_CAPABILITY_REAUTH, "HTTP_CAPABILITY_REAUTH" },
207 { HTTP_CAPABILITY_UDP_TRANSPORT, "HTTP_CAPABILITY_UDP_TRANSPORT" }
208};
209
210static const char* rdg_pkt_type_to_string(int type)
211{
212#define ENTRY(x) \
213 case x: \
214 return #x
215
216 switch (type)
217 {
218 ENTRY(PKT_TYPE_HANDSHAKE_REQUEST);
219 ENTRY(PKT_TYPE_HANDSHAKE_RESPONSE);
220 ENTRY(PKT_TYPE_EXTENDED_AUTH_MSG);
221 ENTRY(PKT_TYPE_TUNNEL_CREATE);
222 ENTRY(PKT_TYPE_TUNNEL_RESPONSE);
223 ENTRY(PKT_TYPE_TUNNEL_AUTH);
224 ENTRY(PKT_TYPE_TUNNEL_AUTH_RESPONSE);
225 ENTRY(PKT_TYPE_CHANNEL_CREATE);
226 ENTRY(PKT_TYPE_CHANNEL_RESPONSE);
227 ENTRY(PKT_TYPE_DATA);
228 ENTRY(PKT_TYPE_SERVICE_MESSAGE);
229 ENTRY(PKT_TYPE_REAUTH_MESSAGE);
230 ENTRY(PKT_TYPE_KEEPALIVE);
231 ENTRY(PKT_TYPE_CLOSE_CHANNEL);
232 ENTRY(PKT_TYPE_CLOSE_CHANNEL_RESPONSE);
233 default:
234 return "PKT_TYPE_UNKNOWN";
235 }
236#undef ENTRY
237}
238
239static const char* flags_to_string(UINT32 flags, const t_flag_mapping* map, size_t elements)
240{
241 static char buffer[1024] = WINPR_C_ARRAY_INIT;
242 char fields[12] = WINPR_C_ARRAY_INIT;
243
244 for (size_t x = 0; x < elements; x++)
245 {
246 const t_flag_mapping* cur = &map[x];
247
248 if ((cur->code & flags) != 0)
249 winpr_str_append(cur->name, buffer, sizeof(buffer), "|");
250 }
251
252 (void)sprintf_s(fields, ARRAYSIZE(fields), " [%04" PRIx32 "]", flags);
253 winpr_str_append(fields, buffer, sizeof(buffer), nullptr);
254 return buffer;
255}
256
257static const char* channel_response_fields_present_to_string(UINT16 fieldsPresent)
258{
259 return flags_to_string(fieldsPresent, channel_response_fields_present,
260 ARRAYSIZE(channel_response_fields_present));
261}
262
263static const char* tunnel_response_fields_present_to_string(UINT16 fieldsPresent)
264{
265 return flags_to_string(fieldsPresent, tunnel_response_fields_present,
266 ARRAYSIZE(tunnel_response_fields_present));
267}
268
269static const char* tunnel_authorization_response_fields_present_to_string(UINT16 fieldsPresent)
270{
271 return flags_to_string(fieldsPresent, tunnel_authorization_response_fields_present,
272 ARRAYSIZE(tunnel_authorization_response_fields_present));
273}
274
275static const char* extended_auth_to_string(UINT16 auth)
276{
277 if (auth == HTTP_EXTENDED_AUTH_NONE)
278 return "HTTP_EXTENDED_AUTH_NONE [0x0000]";
279
280 return flags_to_string(auth, extended_auth, ARRAYSIZE(extended_auth));
281}
282
283static const char* capabilities_enum_to_string(UINT32 capabilities)
284{
285 return flags_to_string(capabilities, capabilities_enum, ARRAYSIZE(capabilities_enum));
286}
287
288static BOOL rdg_read_http_unicode_string(wLog* log, wStream* s, const WCHAR** string,
289 UINT16* lengthInBytes)
290{
291 UINT16 strLenBytes = 0;
292 size_t rem = Stream_GetRemainingLength(s);
293
294 /* Read length of the string */
295 if (!Stream_CheckAndLogRequiredLengthWLog(log, s, 4))
296 {
297 WLog_Print(log, WLOG_ERROR, "Could not read stream length, only have %" PRIuz " bytes",
298 rem);
299 return FALSE;
300 }
301 Stream_Read_UINT16(s, strLenBytes);
302
303 /* Remember position of our string */
304 const WCHAR* str = Stream_ConstPointer(s);
305
306 /* seek past the string - if this fails something is wrong */
307 if (!Stream_SafeSeek(s, strLenBytes))
308 {
309 WLog_Print(log, WLOG_ERROR,
310 "Could not read stream data, only have %" PRIuz " bytes, expected %" PRIu16,
311 rem - 4, strLenBytes);
312 return FALSE;
313 }
314
315 /* return the string data (if wanted) */
316 if (string)
317 *string = str;
318 if (lengthInBytes)
319 *lengthInBytes = strLenBytes;
320
321 return TRUE;
322}
323
324static BOOL rdg_write_chunked(BIO* bio, wStream* sPacket)
325{
326 size_t len = 0;
327 int status = 0;
328 wStream* sChunk = nullptr;
329 char chunkSize[11];
330 (void)sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIXz "\r\n", Stream_Length(sPacket));
331 sChunk =
332 Stream_New(nullptr, strnlen(chunkSize, sizeof(chunkSize)) + Stream_Length(sPacket) + 2);
333
334 if (!sChunk)
335 return FALSE;
336
337 Stream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));
338 Stream_Write(sChunk, Stream_Buffer(sPacket), Stream_Length(sPacket));
339 Stream_Write(sChunk, "\r\n", 2);
340 Stream_SealLength(sChunk);
341 len = Stream_Length(sChunk);
342
343 if (len > INT_MAX)
344 {
345 Stream_Free(sChunk, TRUE);
346 return FALSE;
347 }
348
349 ERR_clear_error();
350 status = BIO_write(bio, Stream_Buffer(sChunk), (int)len);
351 Stream_Free(sChunk, TRUE);
352
353 return (status == (SSIZE_T)len);
354}
355
356static BOOL rdg_write_packet(rdpRdg* rdg, wStream* sPacket)
357{
358 if (rdg->transferEncoding.isWebsocketTransport)
359 return websocket_context_write_wstream(rdg->transferEncoding.context.websocket,
360 rdg->tlsOut->bio, sPacket, WebsocketBinaryOpcode);
361
362 return rdg_write_chunked(rdg->tlsIn->bio, sPacket);
363}
364
365static int rdg_socket_read(BIO* bio, BYTE* pBuffer, size_t size,
366 rdg_http_encoding_context* encodingContext)
367{
368 WINPR_ASSERT(encodingContext != nullptr);
369 if (size > INT32_MAX)
370 return -1;
371
372 if (encodingContext->isWebsocketTransport)
373 return websocket_context_read(encodingContext->context.websocket, bio, pBuffer, size);
374
375 switch (encodingContext->httpTransferEncoding)
376 {
377 case TransferEncodingIdentity:
378 ERR_clear_error();
379 return BIO_read(bio, pBuffer, (int)size);
380 case TransferEncodingChunked:
381 return http_chuncked_read(bio, pBuffer, size, &encodingContext->context.chunked);
382 default:
383 return -1;
384 }
385}
386
387static BOOL rdg_shall_abort(rdpRdg* rdg)
388{
389 WINPR_ASSERT(rdg);
390 return freerdp_shall_disconnect_context(rdg->context);
391}
392
393static BOOL rdg_read_all(rdpContext* context, rdpTls* tls, BYTE* buffer, size_t size,
394 rdg_http_encoding_context* transferEncoding)
395{
396 size_t readCount = 0;
397 BYTE* pBuffer = buffer;
398
399 while (readCount < size)
400 {
401 if (freerdp_shall_disconnect_context(context))
402 return FALSE;
403
404 int status = rdg_socket_read(tls->bio, pBuffer, size - readCount, transferEncoding);
405 if (status <= 0)
406 {
407 if (!BIO_should_retry(tls->bio))
408 return FALSE;
409
410 Sleep(10);
411 continue;
412 }
413
414 readCount += WINPR_ASSERTING_INT_CAST(uint32_t, status);
415 pBuffer += WINPR_ASSERTING_INT_CAST(uint32_t, status);
416 }
417
418 return TRUE;
419}
420
421static wStream* rdg_receive_packet(rdpRdg* rdg)
422{
423 const size_t header = sizeof(RdgPacketHeader);
424 size_t packetLength = 0;
425 wStream* s = Stream_New(nullptr, 1024);
426
427 if (!s)
428 return nullptr;
429
430 if (!rdg_read_all(rdg->context, rdg->tlsOut, Stream_Buffer(s), header, &rdg->transferEncoding))
431 goto fail;
432
433 Stream_Seek(s, 4);
434 Stream_Read_UINT32(s, packetLength);
435
436 if ((packetLength > INT_MAX) || !Stream_EnsureCapacity(s, packetLength) ||
437 (packetLength < header))
438 goto fail;
439
440 if (!rdg_read_all(rdg->context, rdg->tlsOut, Stream_Buffer(s) + header, packetLength - header,
441 &rdg->transferEncoding))
442 goto fail;
443
444 if (!Stream_SetLength(s, packetLength))
445 goto fail;
446 return s;
447
448fail:
449 Stream_Free(s, TRUE);
450 return nullptr;
451}
452
453static BOOL rdg_send_handshake(rdpRdg* rdg)
454{
455 BOOL status = FALSE;
456 wStream* s = Stream_New(nullptr, 14);
457
458 if (!s)
459 return FALSE;
460
461 Stream_Write_UINT16(s, PKT_TYPE_HANDSHAKE_REQUEST); /* Type (2 bytes) */
462 Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
463 Stream_Write_UINT32(s, 14); /* PacketLength (4 bytes) */
464 Stream_Write_UINT8(s, 1); /* VersionMajor (1 byte) */
465 Stream_Write_UINT8(s, 0); /* VersionMinor (1 byte) */
466 Stream_Write_UINT16(s, 0); /* ClientVersion (2 bytes), must be 0 */
467 Stream_Write_UINT16(s, rdg->extAuth); /* ExtendedAuthentication (2 bytes) */
468 Stream_SealLength(s);
469 status = rdg_write_packet(rdg, s);
470 Stream_Free(s, TRUE);
471
472 if (status)
473 {
474 rdg->state = RDG_CLIENT_STATE_HANDSHAKE;
475 }
476
477 return status;
478}
479
480static BOOL rdg_send_extauth_sspi(rdpRdg* rdg)
481{
482 wStream* s = nullptr;
483 BOOL status = 0;
484 UINT32 packetSize = 8 + 4 + 2;
485
486 WINPR_ASSERT(rdg);
487
488 const SecBuffer* authToken = credssp_auth_get_output_buffer(rdg->auth);
489 if (!authToken)
490 return FALSE;
491 packetSize += authToken->cbBuffer;
492
493 s = Stream_New(nullptr, packetSize);
494
495 if (!s)
496 return FALSE;
497
498 Stream_Write_UINT16(s, PKT_TYPE_EXTENDED_AUTH_MSG); /* Type (2 bytes) */
499 Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
500 Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */
501 Stream_Write_UINT32(s, ERROR_SUCCESS); /* Error code */
502 Stream_Write_UINT16(s, (UINT16)authToken->cbBuffer);
503 Stream_Write(s, authToken->pvBuffer, authToken->cbBuffer);
504
505 Stream_SealLength(s);
506 status = rdg_write_packet(rdg, s);
507 Stream_Free(s, TRUE);
508
509 return status;
510}
511
512static BOOL rdg_send_tunnel_request(rdpRdg* rdg)
513{
514 wStream* s = nullptr;
515 BOOL status = FALSE;
516 UINT32 packetSize = 16;
517 UINT16 fieldsPresent = 0;
518 WCHAR* PAACookie = nullptr;
519 size_t PAACookieLen = 0;
520 const UINT32 capabilities = HTTP_CAPABILITY_TYPE_QUAR_SOH |
521 HTTP_CAPABILITY_MESSAGING_CONSENT_SIGN |
522 HTTP_CAPABILITY_MESSAGING_SERVICE_MSG;
523
524 if (rdg->extAuth == HTTP_EXTENDED_AUTH_PAA)
525 {
526 PAACookie =
527 ConvertUtf8ToWCharAlloc(rdg->context->settings->GatewayAccessToken, &PAACookieLen);
528
529 if (!PAACookie || (PAACookieLen > UINT16_MAX / sizeof(WCHAR)))
530 goto fail;
531
532 PAACookieLen += 1; /* include \0 */
533 packetSize += 2 + (UINT32)(PAACookieLen) * sizeof(WCHAR);
534 fieldsPresent = HTTP_TUNNEL_PACKET_FIELD_PAA_COOKIE;
535 }
536
537 s = Stream_New(nullptr, packetSize);
538
539 if (!s)
540 goto fail;
541
542 Stream_Write_UINT16(s, PKT_TYPE_TUNNEL_CREATE); /* Type (2 bytes) */
543 Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
544 Stream_Write_UINT32(s, packetSize); /* PacketLength (4 bytes) */
545 Stream_Write_UINT32(s, capabilities); /* CapabilityFlags (4 bytes) */
546 Stream_Write_UINT16(s, fieldsPresent); /* FieldsPresent (2 bytes) */
547 Stream_Write_UINT16(s, 0); /* Reserved (2 bytes), must be 0 */
548
549 if (PAACookie)
550 {
551 Stream_Write_UINT16(s, (UINT16)PAACookieLen * sizeof(WCHAR)); /* PAA cookie string length */
552 if (!Stream_Write_UTF16_String(s, PAACookie, PAACookieLen))
553 goto fail;
554 }
555
556 Stream_SealLength(s);
557 status = rdg_write_packet(rdg, s);
558
559fail:
560 Stream_Free(s, TRUE);
561 free(PAACookie);
562
563 if (status)
564 {
565 rdg->state = RDG_CLIENT_STATE_TUNNEL_CREATE;
566 }
567
568 return status;
569}
570
571static BOOL rdg_send_tunnel_authorization(rdpRdg* rdg)
572{
573 wStream* s = nullptr;
574 BOOL status = FALSE;
575 WINPR_ASSERT(rdg);
576 size_t clientNameLen = 0;
577 WCHAR* clientName = freerdp_settings_get_string_as_utf16(
578 rdg->context->settings, FreeRDP_ClientHostname, &clientNameLen);
579
580 clientNameLen++; // length including terminating '\0'
581
582 const size_t packetSize = 12ull + clientNameLen * sizeof(WCHAR);
583 if (!clientName || (clientNameLen >= UINT16_MAX / sizeof(WCHAR)) || (packetSize > UINT32_MAX))
584 goto fail;
585
586 s = Stream_New(nullptr, packetSize);
587
588 if (!s)
589 goto fail;
590
591 Stream_Write_UINT16(s, PKT_TYPE_TUNNEL_AUTH); /* Type (2 bytes) */
592 Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
593 Stream_Write_UINT32(s, (UINT32)packetSize); /* PacketLength (4 bytes) */
594 Stream_Write_UINT16(s, 0); /* FieldsPresent (2 bytes) */
595 Stream_Write_UINT16(s, (UINT16)clientNameLen * sizeof(WCHAR)); /* Client name string length */
596 if (!Stream_Write_UTF16_String(s, clientName, clientNameLen))
597 goto fail;
598 Stream_SealLength(s);
599 status = rdg_write_packet(rdg, s);
600
601fail:
602 Stream_Free(s, TRUE);
603 free(clientName);
604
605 if (status)
606 rdg->state = RDG_CLIENT_STATE_TUNNEL_AUTHORIZE;
607
608 return status;
609}
610
611static BOOL rdg_send_channel_create(rdpRdg* rdg)
612{
613 wStream* s = nullptr;
614 BOOL status = FALSE;
615 WCHAR* serverName = nullptr;
616 size_t serverNameLen = 0;
617
618 WINPR_ASSERT(rdg);
619 serverName = freerdp_settings_get_string_as_utf16(rdg->context->settings,
620 FreeRDP_ServerHostname, &serverNameLen);
621
622 serverNameLen++; // length including terminating '\0'
623 const size_t packetSize = 16ull + serverNameLen * sizeof(WCHAR);
624 if (!serverName || (serverNameLen >= UINT16_MAX / sizeof(WCHAR)) || (packetSize > UINT32_MAX))
625 goto fail;
626
627 s = Stream_New(nullptr, packetSize);
628
629 if (!s)
630 goto fail;
631
632 Stream_Write_UINT16(s, PKT_TYPE_CHANNEL_CREATE); /* Type (2 bytes) */
633 Stream_Write_UINT16(s, 0); /* Reserved (2 bytes) */
634 Stream_Write_UINT32(s, (UINT32)packetSize); /* PacketLength (4 bytes) */
635 Stream_Write_UINT8(s, 1); /* Number of resources. (1 byte) */
636 Stream_Write_UINT8(s, 0); /* Number of alternative resources (1 byte) */
637 Stream_Write_UINT16(s,
638 (UINT16)rdg->context->settings->ServerPort); /* Resource port (2 bytes) */
639 Stream_Write_UINT16(s, 3); /* Protocol number (2 bytes) */
640 Stream_Write_UINT16(s, (UINT16)serverNameLen * sizeof(WCHAR));
641 if (!Stream_Write_UTF16_String(s, serverName, serverNameLen))
642 goto fail;
643
644 Stream_SealLength(s);
645 status = rdg_write_packet(rdg, s);
646fail:
647 free(serverName);
648 Stream_Free(s, TRUE);
649
650 if (status)
651 rdg->state = RDG_CLIENT_STATE_CHANNEL_CREATE;
652
653 return status;
654}
655
656static BOOL rdg_set_auth_header(rdpCredsspAuth* auth, HttpRequest* request)
657{
658 const SecBuffer* authToken = credssp_auth_get_output_buffer(auth);
659 char* base64AuthToken = nullptr;
660
661 if (authToken)
662 {
663 if (authToken->cbBuffer > INT_MAX)
664 return FALSE;
665
666 base64AuthToken = crypto_base64_encode(authToken->pvBuffer, authToken->cbBuffer);
667 }
668
669 if (base64AuthToken)
670 {
671 BOOL rc = http_request_set_auth_scheme(request, credssp_auth_pkg_name(auth)) &&
672 http_request_set_auth_param(request, base64AuthToken);
673 free(base64AuthToken);
674
675 if (!rc)
676 return FALSE;
677 }
678
679 return TRUE;
680}
681
682static wStream* rdg_build_http_request(rdpRdg* rdg, const char* method,
683 TRANSFER_ENCODING transferEncoding)
684{
685 wStream* s = nullptr;
686 HttpRequest* request = nullptr;
687 const char* uri = nullptr;
688
689 if (!rdg || !method)
690 return nullptr;
691
692 uri = http_context_get_uri(rdg->http);
693 request = http_request_new();
694
695 if (!request)
696 return nullptr;
697
698 if (!http_request_set_method(request, method) || !http_request_set_uri(request, uri))
699 goto out;
700
701 if (rdg->auth)
702 {
703 if (!rdg_set_auth_header(rdg->auth, request))
704 goto out;
705 }
706
707 else if (rdg->extAuth == HTTP_EXTENDED_AUTH_BEARER)
708 {
709 if (!http_request_set_auth_scheme(request, "Bearer"))
710 goto out;
711 if (!http_request_set_auth_param(request, rdg->context->settings->GatewayHttpExtAuthBearer))
712 goto out;
713 }
714
715 if (!http_request_set_transfer_encoding(request, transferEncoding))
716 goto out;
717
718 s = http_request_write(rdg->http, request);
719out:
720 http_request_free(request);
721
722 if (s)
723 Stream_SealLength(s);
724
725 return s;
726}
727
728static BOOL rdg_recv_auth_token(wLog* log, rdpCredsspAuth* auth, HttpResponse* response,
729 BOOL* pHaveToken)
730{
731 size_t len = 0;
732 size_t authTokenLength = 0;
733 BYTE* authTokenData = nullptr;
734 SecBuffer authToken = WINPR_C_ARRAY_INIT;
735 int rc = 0;
736
737 WINPR_ASSERT(pHaveToken);
738 *pHaveToken = FALSE;
739
740 if (!auth || !response)
741 return FALSE;
742
743 const UINT16 StatusCode = http_response_get_status_code(response);
744 switch (StatusCode)
745 {
746 case HTTP_STATUS_DENIED:
747 case HTTP_STATUS_OK:
748 case HTTP_STATUS_SWITCH_PROTOCOLS:
749 break;
750 default:
751 http_response_log_error_status(log, WLOG_WARN, response);
752 return FALSE;
753 }
754
755 const char* token64 = http_response_get_auth_token(response, credssp_auth_pkg_name(auth));
756 if (!token64)
757 {
758 /* Not an error in itself: the server may complete the authentication without returning
759 * a final token. The caller decides what that means from the HTTP status. */
760 return TRUE;
761 }
762
763 *pHaveToken = TRUE;
764
765 len = strlen(token64);
766
767 crypto_base64_decode(token64, len, &authTokenData, &authTokenLength);
768
769 if (authTokenLength && authTokenData && (authTokenLength <= UINT32_MAX))
770 {
771 authToken.pvBuffer = authTokenData;
772 authToken.cbBuffer = (UINT32)authTokenLength;
773 credssp_auth_take_input_buffer(auth, &authToken);
774 }
775 else
776 free(authTokenData);
777
778 rc = credssp_auth_authenticate(auth);
779 return (rc >= 0);
780}
781
782static BOOL rdg_skip_seed_payload(rdpContext* context, rdpTls* tls, size_t lastResponseLength,
783 rdg_http_encoding_context* transferEncoding)
784{
785 BYTE seed_payload[10] = WINPR_C_ARRAY_INIT;
786 const size_t size = sizeof(seed_payload);
787
788 /* Per [MS-TSGU] 3.3.5.1 step 4, after final OK response RDG server sends
789 * random "seed" payload of limited size. In practice it's 10 bytes.
790 */
791 if (lastResponseLength < size)
792 {
793 if (!rdg_read_all(context, tls, seed_payload, size - lastResponseLength, transferEncoding))
794 {
795 return FALSE;
796 }
797 }
798
799 return TRUE;
800}
801
802static BOOL rdg_process_handshake_response(rdpRdg* rdg, wStream* s)
803{
804 UINT32 errorCode = 0;
805 UINT16 serverVersion = 0;
806 UINT16 extendedAuth = 0;
807 BYTE verMajor = 0;
808 BYTE verMinor = 0;
809 const char* error = nullptr;
810 WLog_Print(rdg->log, WLOG_DEBUG, "Handshake response received");
811
812 if (rdg->state != RDG_CLIENT_STATE_HANDSHAKE)
813 {
814 return FALSE;
815 }
816
817 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 10))
818 return FALSE;
819
820 Stream_Read_UINT32(s, errorCode);
821 Stream_Read_UINT8(s, verMajor);
822 Stream_Read_UINT8(s, verMinor);
823 Stream_Read_UINT16(s, serverVersion);
824 Stream_Read_UINT16(s, extendedAuth);
825 error = rpc_error_to_string(errorCode);
826 WLog_Print(rdg->log, WLOG_DEBUG,
827 "errorCode=%s, verMajor=%" PRId8 ", verMinor=%" PRId8 ", serverVersion=%" PRId16
828 ", extendedAuth=%s",
829 error, verMajor, verMinor, serverVersion, extended_auth_to_string(extendedAuth));
830
831 if (FAILED((HRESULT)errorCode))
832 {
833 WLog_Print(rdg->log, WLOG_ERROR, "Handshake error %s", error);
834 freerdp_set_last_error_log(rdg->context, errorCode);
835 return FALSE;
836 }
837
838 if (rdg->extAuth == HTTP_EXTENDED_AUTH_SSPI_NTLM)
839 return rdg_send_extauth_sspi(rdg);
840
841 return rdg_send_tunnel_request(rdg);
842}
843
844static BOOL rdg_process_tunnel_response_optional(rdpRdg* rdg, wStream* s, UINT16 fieldsPresent)
845{
846 if (fieldsPresent & HTTP_TUNNEL_RESPONSE_FIELD_TUNNEL_ID)
847 {
848 /* Seek over tunnelId (4 bytes) */
849 if (!Stream_SafeSeek(s, 4))
850 {
851 WLog_Print(rdg->log, WLOG_ERROR, "Short tunnelId, got %" PRIuz ", expected 4",
852 Stream_GetRemainingLength(s));
853 return FALSE;
854 }
855 }
856
857 if (fieldsPresent & HTTP_TUNNEL_RESPONSE_FIELD_CAPS)
858 {
859 UINT32 caps = 0;
860 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 4))
861 return FALSE;
862
863 Stream_Read_UINT32(s, caps);
864 WLog_Print(rdg->log, WLOG_DEBUG, "capabilities=%s", capabilities_enum_to_string(caps));
865 }
866
867 if (fieldsPresent & HTTP_TUNNEL_RESPONSE_FIELD_SOH_REQ)
868 {
869 /* Seek over nonce (20 bytes) */
870 if (!Stream_SafeSeek(s, 20))
871 {
872 WLog_Print(rdg->log, WLOG_ERROR, "Short nonce, got %" PRIuz ", expected 20",
873 Stream_GetRemainingLength(s));
874 return FALSE;
875 }
876
877 /* Read serverCert */
878 if (!rdg_read_http_unicode_string(rdg->log, s, nullptr, nullptr))
879 {
880 WLog_Print(rdg->log, WLOG_ERROR, "Failed to read server certificate");
881 return FALSE;
882 }
883 }
884
885 if (fieldsPresent & HTTP_TUNNEL_RESPONSE_FIELD_CONSENT_MSG)
886 {
887 const WCHAR* msg = nullptr;
888 UINT16 msgLenBytes = 0;
889 rdpContext* context = rdg->context;
890
891 WINPR_ASSERT(context);
892 WINPR_ASSERT(context->instance);
893
894 /* Read message string and invoke callback */
895 if (!rdg_read_http_unicode_string(rdg->log, s, &msg, &msgLenBytes))
896 {
897 WLog_Print(rdg->log, WLOG_ERROR, "Failed to read consent message");
898 return FALSE;
899 }
900
901 return IFCALLRESULT(TRUE, context->instance->PresentGatewayMessage, context->instance,
902 GATEWAY_MESSAGE_CONSENT, TRUE, TRUE, msgLenBytes, msg);
903 }
904
905 return TRUE;
906}
907
908static BOOL rdg_process_tunnel_response(rdpRdg* rdg, wStream* s)
909{
910 UINT16 serverVersion = 0;
911 UINT16 fieldsPresent = 0;
912 UINT32 errorCode = 0;
913 const char* error = nullptr;
914 WLog_Print(rdg->log, WLOG_DEBUG, "Tunnel response received");
915
916 if (rdg->state != RDG_CLIENT_STATE_TUNNEL_CREATE)
917 {
918 return FALSE;
919 }
920
921 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 10))
922 return FALSE;
923
924 Stream_Read_UINT16(s, serverVersion);
925 Stream_Read_UINT32(s, errorCode);
926 Stream_Read_UINT16(s, fieldsPresent);
927 Stream_Seek_UINT16(s); /* reserved */
928 error = rpc_error_to_string(errorCode);
929 WLog_Print(rdg->log, WLOG_DEBUG, "serverVersion=%" PRId16 ", errorCode=%s, fieldsPresent=%s",
930 serverVersion, error, tunnel_response_fields_present_to_string(fieldsPresent));
931
932 if (FAILED((HRESULT)errorCode))
933 {
934 WLog_Print(rdg->log, WLOG_ERROR, "Tunnel creation error %s", error);
935 freerdp_set_last_error_log(rdg->context, errorCode);
936 return FALSE;
937 }
938
939 if (!rdg_process_tunnel_response_optional(rdg, s, fieldsPresent))
940 return FALSE;
941
942 return rdg_send_tunnel_authorization(rdg);
943}
944
945static BOOL rdg_process_tunnel_authorization_response(rdpRdg* rdg, wStream* s)
946{
947 UINT32 errorCode = 0;
948 UINT16 fieldsPresent = 0;
949 const char* error = nullptr;
950 WLog_Print(rdg->log, WLOG_DEBUG, "Tunnel authorization received");
951
952 if (rdg->state != RDG_CLIENT_STATE_TUNNEL_AUTHORIZE)
953 {
954 return FALSE;
955 }
956
957 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 8))
958 return FALSE;
959
960 Stream_Read_UINT32(s, errorCode);
961 Stream_Read_UINT16(s, fieldsPresent);
962 Stream_Seek_UINT16(s); /* reserved */
963 error = rpc_error_to_string(errorCode);
964 WLog_Print(rdg->log, WLOG_DEBUG, "errorCode=%s, fieldsPresent=%s", error,
965 tunnel_authorization_response_fields_present_to_string(fieldsPresent));
966
967 /* [MS-TSGU] 3.7.5.2.7 */
968 if (errorCode != S_OK && errorCode != E_PROXY_QUARANTINE_ACCESSDENIED)
969 {
970 WLog_Print(rdg->log, WLOG_ERROR, "Tunnel authorization error %s", error);
971 freerdp_set_last_error_log(rdg->context, errorCode);
972 return FALSE;
973 }
974
975 if (fieldsPresent & HTTP_TUNNEL_AUTH_RESPONSE_FIELD_REDIR_FLAGS)
976 {
977 UINT32 redirFlags = 0;
978 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 4))
979 return FALSE;
980 Stream_Read_UINT32(s, redirFlags);
981
982 rdpContext* context = rdg->context;
983 if (!utils_apply_gateway_policy(rdg->log, context, redirFlags, "RDG"))
984 return FALSE;
985 }
986
987 if (fieldsPresent & HTTP_TUNNEL_AUTH_RESPONSE_FIELD_IDLE_TIMEOUT)
988 {
989 UINT32 idleTimeout = 0;
990 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 4))
991 return FALSE;
992 Stream_Read_UINT32(s, idleTimeout);
993 WLog_Print(rdg->log, WLOG_DEBUG, "[IDLE_TIMEOUT] idleTimeout=%" PRIu32 ": TODO: unused",
994 idleTimeout);
995 }
996
997 if (fieldsPresent & HTTP_TUNNEL_AUTH_RESPONSE_FIELD_SOH_RESPONSE)
998 {
999 UINT16 cbLen = 0;
1000 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 2))
1001 return FALSE;
1002 Stream_Read_UINT16(s, cbLen);
1003
1004 WLog_Print(rdg->log, WLOG_DEBUG, "[SOH_RESPONSE] cbLen=%" PRIu16 ": TODO: unused", cbLen);
1005 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, cbLen))
1006 return FALSE;
1007 Stream_Seek(s, cbLen);
1008 }
1009
1010 return rdg_send_channel_create(rdg);
1011}
1012
1013static BOOL rdg_process_extauth_sspi(rdpRdg* rdg, wStream* s)
1014{
1015 INT32 errorCode = 0;
1016 UINT16 authBlobLen = 0;
1017 SecBuffer authToken = WINPR_C_ARRAY_INIT;
1018 BYTE* authTokenData = nullptr;
1019
1020 WINPR_ASSERT(rdg);
1021
1022 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 6))
1023 return FALSE;
1024
1025 Stream_Read_INT32(s, errorCode);
1026 Stream_Read_UINT16(s, authBlobLen);
1027
1028 if (errorCode != ERROR_SUCCESS)
1029 {
1030 WLog_Print(rdg->log, WLOG_ERROR, "EXTAUTH_SSPI_NTLM failed with error %s [0x%08X]",
1031 GetSecurityStatusString(errorCode), WINPR_CXX_COMPAT_CAST(UINT32, errorCode));
1032 return FALSE;
1033 }
1034
1035 if (authBlobLen == 0)
1036 {
1037 if (credssp_auth_is_complete(rdg->auth))
1038 {
1039 credssp_auth_free(rdg->auth);
1040 rdg->auth = nullptr;
1041 return rdg_send_tunnel_request(rdg);
1042 }
1043 return FALSE;
1044 }
1045
1046 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, authBlobLen))
1047 return FALSE;
1048
1049 authTokenData = malloc(authBlobLen);
1050 if (authTokenData == nullptr)
1051 return FALSE;
1052 Stream_Read(s, authTokenData, authBlobLen);
1053
1054 authToken.pvBuffer = authTokenData;
1055 authToken.cbBuffer = authBlobLen;
1056
1057 credssp_auth_take_input_buffer(rdg->auth, &authToken);
1058
1059 if (credssp_auth_authenticate(rdg->auth) < 0)
1060 return FALSE;
1061
1062 if (credssp_auth_have_output_token(rdg->auth))
1063 return rdg_send_extauth_sspi(rdg);
1064
1065 return FALSE;
1066}
1067
1068static BOOL rdg_process_channel_response_optional(rdpRdg* rdg, wStream* s, UINT16 fieldsPresent)
1069{
1070 if ((fieldsPresent & HTTP_CHANNEL_RESPONSE_FIELD_CHANNELID) != 0)
1071 {
1072 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 4))
1073 return FALSE;
1074 const UINT32 channelId = Stream_Get_UINT32(s);
1075 WLog_Print(rdg->log, WLOG_DEBUG, "TODO: Got channelId=%" PRIu32, channelId);
1076 }
1077 if ((fieldsPresent & HTTP_CHANNEL_RESPONSE_FIELD_UDPPORT) != 0)
1078 {
1079 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 2))
1080 return FALSE;
1081 const UINT16 udpPort = Stream_Get_UINT16(s);
1082 WLog_Print(rdg->log, WLOG_DEBUG, "TODO: Got udpPort=%" PRIu32, udpPort);
1083 }
1084 if ((fieldsPresent & HTTP_CHANNEL_RESPONSE_FIELD_AUTHNCOOKIE) != 0)
1085 {
1086 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 2))
1087 return FALSE;
1088 const UINT16 blobLen = Stream_Get_UINT16(s);
1089 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, blobLen))
1090 return FALSE;
1091 WLog_Print(rdg->log, WLOG_DEBUG, "TODO: Got UDP auth blob=%" PRIu32, blobLen);
1092 if (!Stream_SafeSeek(s, blobLen))
1093 return FALSE;
1094 }
1095
1096 return TRUE;
1097}
1098
1099static BOOL rdg_process_channel_response(rdpRdg* rdg, wStream* s)
1100{
1101 UINT16 fieldsPresent = 0;
1102 UINT32 errorCode = 0;
1103 const char* error = nullptr;
1104 WLog_Print(rdg->log, WLOG_DEBUG, "Channel response received");
1105
1106 if (rdg->state != RDG_CLIENT_STATE_CHANNEL_CREATE)
1107 {
1108 return FALSE;
1109 }
1110
1111 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 8))
1112 return FALSE;
1113
1114 Stream_Read_UINT32(s, errorCode);
1115 Stream_Read_UINT16(s, fieldsPresent);
1116 Stream_Seek_UINT16(s); /* reserved */
1117 error = rpc_error_to_string(errorCode);
1118 WLog_Print(rdg->log, WLOG_DEBUG, "channel response errorCode=%s, fieldsPresent=%s", error,
1119 channel_response_fields_present_to_string(fieldsPresent));
1120
1121 if (FAILED((HRESULT)errorCode))
1122 {
1123 WLog_Print(rdg->log, WLOG_ERROR, "channel response errorCode=%s, fieldsPresent=%s", error,
1124 channel_response_fields_present_to_string(fieldsPresent));
1125 freerdp_set_last_error_log(rdg->context, errorCode);
1126 return FALSE;
1127 }
1128
1129 if (!rdg_process_channel_response_optional(rdg, s, fieldsPresent))
1130 return FALSE;
1131
1132 rdg->state = RDG_CLIENT_STATE_OPENED;
1133 return TRUE;
1134}
1135
1136static BOOL rdg_process_packet(rdpRdg* rdg, wStream* s)
1137{
1138 BOOL status = TRUE;
1139 UINT16 type = 0;
1140 UINT32 packetLength = 0;
1141 Stream_ResetPosition(s);
1142
1143 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 8))
1144 return FALSE;
1145
1146 Stream_Read_UINT16(s, type);
1147 Stream_Seek_UINT16(s); /* reserved */
1148 Stream_Read_UINT32(s, packetLength);
1149
1150 if (Stream_Length(s) < packetLength)
1151 {
1152 WLog_Print(rdg->log, WLOG_ERROR, "Short packet %" PRIuz ", expected %" PRIu32,
1153 Stream_Length(s), packetLength);
1154 return FALSE;
1155 }
1156
1157 switch (type)
1158 {
1159 case PKT_TYPE_HANDSHAKE_RESPONSE:
1160 status = rdg_process_handshake_response(rdg, s);
1161 break;
1162
1163 case PKT_TYPE_TUNNEL_RESPONSE:
1164 status = rdg_process_tunnel_response(rdg, s);
1165 break;
1166
1167 case PKT_TYPE_TUNNEL_AUTH_RESPONSE:
1168 status = rdg_process_tunnel_authorization_response(rdg, s);
1169 break;
1170
1171 case PKT_TYPE_CHANNEL_RESPONSE:
1172 status = rdg_process_channel_response(rdg, s);
1173 break;
1174
1175 case PKT_TYPE_DATA:
1176 WLog_Print(rdg->log, WLOG_ERROR, "Unexpected packet type DATA");
1177 status = FALSE;
1178 break;
1179
1180 case PKT_TYPE_EXTENDED_AUTH_MSG:
1181 status = rdg_process_extauth_sspi(rdg, s);
1182 break;
1183
1184 default:
1185 WLog_Print(rdg->log, WLOG_ERROR, "PKG TYPE 0x%x not implemented", type);
1186 status = FALSE;
1187 break;
1188 }
1189
1190 if (status)
1191 {
1192 const size_t rem = Stream_GetRemainingLength(s);
1193 if (rem > 0)
1194 WLog_Print(rdg->log, WLOG_WARN, "[%s] unparsed data detected: %" PRIuz " bytes",
1195 rdg_pkt_type_to_string(type), rem);
1196 }
1197 return status;
1198}
1199
1200DWORD rdg_get_event_handles(rdpRdg* rdg, HANDLE* events, DWORD count)
1201{
1202 DWORD nCount = 0;
1203 WINPR_ASSERT(rdg != nullptr);
1204
1205 if (rdg->tlsOut && rdg->tlsOut->bio)
1206 {
1207 if (events && (nCount < count))
1208 {
1209 BIO_get_event(rdg->tlsOut->bio, &events[nCount]);
1210 nCount++;
1211 }
1212 else
1213 return 0;
1214 }
1215
1216 /* We just need the read event handle even in non-websocket mode. */
1217
1218 return nCount;
1219}
1220
1221static BOOL rdg_get_gateway_credentials(rdpContext* context, rdp_auth_reason reason)
1222{
1223 freerdp* instance = context->instance;
1224
1225 auth_status rc = utils_authenticate_gateway(instance, reason);
1226 switch (rc)
1227 {
1228 case AUTH_SUCCESS:
1229 case AUTH_SKIP:
1230 return TRUE;
1231 case AUTH_CANCELLED:
1232 freerdp_set_last_error_log(instance->context, FREERDP_ERROR_CONNECT_CANCELLED);
1233 return FALSE;
1234 case AUTH_NO_CREDENTIALS:
1235 WLog_INFO(TAG, "No credentials provided - using nullptr identity");
1236 return TRUE;
1237 case AUTH_FAILED:
1238 default:
1239 return FALSE;
1240 }
1241}
1242
1243static BOOL rdg_auth_init(rdpRdg* rdg, rdpTls* tls, TCHAR* authPkg)
1244{
1245 rdpContext* context = rdg->context;
1246 rdpSettings* settings = context->settings;
1247 SEC_WINNT_AUTH_IDENTITY identity = WINPR_C_ARRAY_INIT;
1248 int rc = 0;
1249
1250 rdg->auth = credssp_auth_new(context);
1251 if (!rdg->auth)
1252 return FALSE;
1253
1254 if (!credssp_auth_init(rdg->auth, authPkg, tls->Bindings))
1255 return FALSE;
1256
1257 BOOL doSCLogon = freerdp_settings_get_bool(settings, FreeRDP_SmartcardLogon);
1258 if (doSCLogon)
1259 {
1260 if (!smartcard_getCert(context, &rdg->smartcard, TRUE))
1261 return FALSE;
1262
1263 if (!rdg_get_gateway_credentials(context, AUTH_SMARTCARD_PIN))
1264 return FALSE;
1265 }
1266 else
1267 {
1268 if (!rdg_get_gateway_credentials(context, GW_AUTH_RDG))
1269 return FALSE;
1270
1271 /* Auth callback might changed logon to smartcard so check again */
1272 doSCLogon = freerdp_settings_get_bool(settings, FreeRDP_SmartcardLogon);
1273 if (doSCLogon && !smartcard_getCert(context, &rdg->smartcard, TRUE))
1274 return FALSE;
1275 }
1276
1277 SEC_WINNT_AUTH_IDENTITY* identityArg = &identity;
1278 if (doSCLogon)
1279 {
1280 if (!identity_set_from_smartcard_hash(&identity, settings, FreeRDP_GatewayUsername,
1281 FreeRDP_GatewayDomain, FreeRDP_GatewayPassword,
1282 rdg->smartcard->sha1Hash,
1283 sizeof(rdg->smartcard->sha1Hash)))
1284 return FALSE;
1285 }
1286 else
1287 {
1288 if (!identity_set_from_settings(&identity, settings, FreeRDP_GatewayUsername,
1289 FreeRDP_GatewayDomain, FreeRDP_GatewayPassword))
1290 return FALSE;
1291
1292 if (!settings->GatewayUsername)
1293 identityArg = nullptr;
1294 }
1295
1296 if (!credssp_auth_setup_client(rdg->auth, "HTTP", settings->GatewayHostname, identityArg,
1297 rdg->smartcard ? rdg->smartcard->pkinitArgs : nullptr))
1298 {
1299 sspi_FreeAuthIdentity(&identity);
1300 return FALSE;
1301 }
1302 sspi_FreeAuthIdentity(&identity);
1303
1304 credssp_auth_set_flags(rdg->auth, ISC_REQ_CONFIDENTIALITY | ISC_REQ_MUTUAL_AUTH);
1305
1306 rc = credssp_auth_authenticate(rdg->auth);
1307 return (rc >= 0);
1308}
1309
1310static BOOL rdg_send_http_request(rdpRdg* rdg, rdpTls* tls, const char* method,
1311 TRANSFER_ENCODING transferEncoding)
1312{
1313 int status = -1;
1314 wStream* s = rdg_build_http_request(rdg, method, transferEncoding);
1315
1316 if (!s)
1317 return FALSE;
1318
1319 const size_t sz = Stream_Length(s);
1320 status = freerdp_tls_write_all(tls, Stream_Buffer(s), sz);
1321
1322 Stream_Free(s, TRUE);
1323 return (status >= 0);
1324}
1325
1326static BOOL rdg_tls_connect(rdpRdg* rdg, rdpTls* tls, const char* peerAddress, UINT32 timeout)
1327{
1328 long status = 0;
1329 BIO* layerBio = nullptr;
1330 BIO* bufferedBio = nullptr;
1331 rdpTransportLayer* layer = nullptr;
1332 rdpSettings* settings = rdg->context->settings;
1333 rdpTransport* transport = freerdp_get_transport(rdg->context);
1334 const char* peerHostname = settings->GatewayHostname;
1335 UINT16 peerPort = (UINT16)settings->GatewayPort;
1336 const char* proxyUsername = nullptr;
1337 const char* proxyPassword = nullptr;
1338 BOOL isProxyConnection =
1339 proxy_prepare(settings, &peerHostname, &peerPort, &proxyUsername, &proxyPassword);
1340
1341 if (settings->GatewayPort > UINT16_MAX)
1342 return FALSE;
1343
1344 layer = transport_connect_layer(transport, peerAddress ? peerAddress : peerHostname, peerPort,
1345 timeout);
1346
1347 if (!layer)
1348 {
1349 return FALSE;
1350 }
1351
1352 layerBio = BIO_new(BIO_s_transport_layer());
1353 if (!layerBio)
1354 {
1355 transport_layer_free(layer);
1356 return FALSE;
1357 }
1358 BIO_set_data(layerBio, layer);
1359
1360 bufferedBio = BIO_new(BIO_s_buffered_socket());
1361 if (!bufferedBio)
1362 {
1363 BIO_free_all(layerBio);
1364 return FALSE;
1365 }
1366
1367 bufferedBio = BIO_push(bufferedBio, layerBio);
1368 status = BIO_set_nonblock(bufferedBio, TRUE);
1369
1370 if (isProxyConnection)
1371 {
1372 if (!proxy_connect(rdg->context, bufferedBio, proxyUsername, proxyPassword,
1373 settings->GatewayHostname, (UINT16)settings->GatewayPort))
1374 {
1375 BIO_free_all(bufferedBio);
1376 return FALSE;
1377 }
1378 }
1379
1380 if (!status)
1381 {
1382 BIO_free_all(bufferedBio);
1383 return FALSE;
1384 }
1385
1386 tls->hostname = settings->GatewayHostname;
1387 tls->port = WINPR_ASSERTING_INT_CAST(int32_t, MIN(UINT16_MAX, settings->GatewayPort));
1388 tls->isGatewayTransport = TRUE;
1389 status = freerdp_tls_connect(tls, bufferedBio);
1390 if (status < 1)
1391 {
1392 rdpContext* context = rdg->context;
1393 if (status < 0)
1394 {
1395 freerdp_set_last_error_if_not(context, FREERDP_ERROR_TLS_CONNECT_FAILED);
1396 }
1397 else
1398 {
1399 freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_CANCELLED);
1400 }
1401
1402 return FALSE;
1403 }
1404 return (status >= 1);
1405}
1406
1407static BOOL rdg_establish_data_connection(rdpRdg* rdg, rdpTls* tls, const char* method,
1408 const char* peerAddress, UINT32 timeout,
1409 BOOL* rpcFallback)
1410{
1411 char buffer[64] = WINPR_C_ARRAY_INIT;
1412 HttpResponse* response = nullptr;
1413
1414 if (!rdg_tls_connect(rdg, tls, peerAddress, timeout))
1415 return FALSE;
1416
1417 WINPR_ASSERT(rpcFallback);
1418 if (rdg->context->settings->GatewayHttpExtAuthBearer && rdg->extAuth == HTTP_EXTENDED_AUTH_NONE)
1419 rdg->extAuth = HTTP_EXTENDED_AUTH_BEARER;
1420 if (rdg->extAuth == HTTP_EXTENDED_AUTH_NONE)
1421 {
1422 if (!rdg_auth_init(rdg, tls, AUTH_PKG))
1423 return FALSE;
1424
1425 if (!rdg_send_http_request(rdg, tls, method, TransferEncodingIdentity))
1426 return FALSE;
1427
1428 response = http_response_recv(tls, TRUE);
1429 /* MS RD Gateway seems to just terminate the tls connection without
1430 * sending an answer if it is not happy with the http request */
1431 if (!response)
1432 {
1433 WLog_Print(rdg->log, WLOG_INFO, "RD Gateway HTTP transport broken.");
1434 *rpcFallback = TRUE;
1435 return FALSE;
1436 }
1437
1438 (void)http_response_extract_cookies(response, rdg->http);
1439
1440 const UINT16 StatusCode = http_response_get_status_code(response);
1441 switch (StatusCode)
1442 {
1443 case HTTP_STATUS_GONE:
1444 case HTTP_STATUS_FORBIDDEN:
1445 case HTTP_STATUS_NOT_FOUND:
1446 {
1447 WLog_Print(rdg->log, WLOG_INFO, "RD Gateway does not support HTTP transport.");
1448 http_response_log_error_status(rdg->log, WLOG_DEBUG, response);
1449 *rpcFallback = TRUE;
1450
1451 http_response_free(response);
1452 return FALSE;
1453 }
1454 case HTTP_STATUS_OK:
1455 break;
1456
1457 case HTTP_STATUS_DENIED:
1458 http_response_log_error_status(rdg->log, WLOG_DEBUG, response);
1459 break;
1460
1461 default:
1462 http_response_log_error_status(rdg->log, WLOG_WARN, response);
1463 break;
1464 }
1465
1466 while (!credssp_auth_is_complete(rdg->auth))
1467 {
1468 BOOL haveToken = FALSE;
1469
1470 if (!rdg_recv_auth_token(rdg->log, rdg->auth, response, &haveToken))
1471 {
1472 http_response_free(response);
1473 return FALSE;
1474 }
1475
1476 if (!haveToken)
1477 {
1478 /* The server answered without an authentication token, so there is nothing left
1479 * to negotiate. If it still refuses the request the status handling below reports
1480 * that; otherwise the authentication succeeded as far as the transport is
1481 * concerned, and the security context freed just below is not needed any more.
1482 *
1483 * MS RD Gateway takes this path when it answers the last authentication request
1484 * with the WebSocket upgrade: an HTTP 101 response carries no WWW-Authenticate
1485 * header, so a mechanism still waiting for a final token, such as Kerberos waiting
1486 * for the AP_REP, never reports SEC_E_OK. */
1487 WLog_Print(rdg->log, WLOG_DEBUG,
1488 "No authentication token in the response, ending the exchange");
1489 break;
1490 }
1491
1492 if (credssp_auth_have_output_token(rdg->auth))
1493 {
1494 http_response_free(response);
1495
1496 if (!rdg_send_http_request(rdg, tls, method, TransferEncodingIdentity))
1497 return FALSE;
1498
1499 response = http_response_recv(tls, TRUE);
1500 if (!response)
1501 {
1502 WLog_Print(rdg->log, WLOG_INFO, "RD Gateway HTTP transport broken.");
1503 *rpcFallback = TRUE;
1504 return FALSE;
1505 }
1506 (void)http_response_extract_cookies(response, rdg->http);
1507 }
1508 else
1509 break; /* nothing more to send: do not re-parse the same response */
1510 }
1511 credssp_auth_free(rdg->auth);
1512 rdg->auth = nullptr;
1513 }
1514 else
1515 {
1516 credssp_auth_free(rdg->auth);
1517 rdg->auth = nullptr;
1518
1519 if (!rdg_send_http_request(rdg, tls, method, TransferEncodingIdentity))
1520 return FALSE;
1521
1522 response = http_response_recv(tls, TRUE);
1523
1524 if (!response)
1525 {
1526 WLog_Print(rdg->log, WLOG_INFO, "RD Gateway HTTP transport broken.");
1527 *rpcFallback = TRUE;
1528 return FALSE;
1529 }
1530 (void)http_response_extract_cookies(response, rdg->http);
1531 }
1532
1533 const UINT16 statusCode = http_response_get_status_code(response);
1534 const size_t bodyLength = http_response_get_body_length(response);
1535 const TRANSFER_ENCODING encoding = http_response_get_transfer_encoding(response);
1536 const BOOL isWebsocket = http_response_is_websocket(rdg->http, response);
1537
1538 WLog_Print(rdg->log, WLOG_DEBUG, "%s authorization result: %s", method,
1539 freerdp_http_status_string_format(statusCode, buffer, ARRAYSIZE(buffer)));
1540
1541 switch (statusCode)
1542 {
1543 case HTTP_STATUS_OK:
1544 /* old rdg endpoint without websocket support, don't request websocket for RDG_IN_DATA
1545 */
1546 http_context_enable_websocket_upgrade(rdg->http, FALSE);
1547 http_response_free(response);
1548 break;
1549 case HTTP_STATUS_DENIED:
1550 freerdp_set_last_error_log(rdg->context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);
1551 http_response_free(response);
1552 return FALSE;
1553 case HTTP_STATUS_SWITCH_PROTOCOLS:
1554 http_response_free(response);
1555 if (!isWebsocket)
1556 {
1557 /*
1558 * webserver is broken, a fallback may be possible here
1559 * but only if already tested with oppurtonistic upgrade
1560 */
1561 if (http_context_is_websocket_upgrade_enabled(rdg->http))
1562 {
1563 long fd = BIO_get_fd(tls->bio, nullptr);
1564 if (fd >= 0)
1565 closesocket((SOCKET)fd);
1566 http_context_enable_websocket_upgrade(rdg->http, FALSE);
1567 return rdg_establish_data_connection(rdg, tls, method, peerAddress, timeout,
1568 rpcFallback);
1569 }
1570 return FALSE;
1571 }
1572
1573 rdg->transferEncoding.isWebsocketTransport = TRUE;
1574 if (!websocket_context_reset(rdg->transferEncoding.context.websocket))
1575 return FALSE;
1576
1577 if (rdg->extAuth == HTTP_EXTENDED_AUTH_SSPI_NTLM)
1578 {
1579 /* create a new auth context for SSPI_NTLM. This must be done after the last
1580 * rdg_send_http_request */
1581 if (!rdg_auth_init(rdg, tls, NTLM_SSP_NAME))
1582 return FALSE;
1583 }
1584 return TRUE;
1585 default:
1586 http_response_log_error_status(rdg->log, WLOG_WARN, response);
1587 http_response_free(response);
1588 return FALSE;
1589 }
1590
1591 if (strcmp(method, "RDG_OUT_DATA") == 0)
1592 {
1593 if (encoding == TransferEncodingChunked)
1594 {
1595 rdg->transferEncoding.httpTransferEncoding = TransferEncodingChunked;
1596 rdg->transferEncoding.context.chunked.nextOffset = 0;
1597 rdg->transferEncoding.context.chunked.headerFooterPos = 0;
1598 rdg->transferEncoding.context.chunked.state = ChunkStateLenghHeader;
1599 }
1600 if (!rdg_skip_seed_payload(rdg->context, tls, bodyLength, &rdg->transferEncoding))
1601 {
1602 return FALSE;
1603 }
1604 }
1605 else
1606 {
1607 if (!rdg_send_http_request(rdg, tls, method, TransferEncodingChunked))
1608 return FALSE;
1609
1610 if (rdg->extAuth == HTTP_EXTENDED_AUTH_SSPI_NTLM)
1611 {
1612 /* create a new auth context for SSPI_NTLM. This must be done after the last
1613 * rdg_send_http_request (RDG_IN_DATA is always after RDG_OUT_DATA) */
1614 if (!rdg_auth_init(rdg, tls, NTLM_SSP_NAME))
1615 return FALSE;
1616 }
1617 }
1618
1619 return TRUE;
1620}
1621
1622static BOOL rdg_tunnel_connect(rdpRdg* rdg)
1623{
1624 BOOL status = 0;
1625 wStream* s = nullptr;
1626 rdg_send_handshake(rdg);
1627
1628 while (rdg->state < RDG_CLIENT_STATE_OPENED)
1629 {
1630 status = FALSE;
1631 s = rdg_receive_packet(rdg);
1632
1633 if (s)
1634 {
1635 status = rdg_process_packet(rdg, s);
1636 Stream_Free(s, TRUE);
1637 }
1638
1639 if (!status)
1640 {
1641 WINPR_ASSERT(rdg);
1642 WINPR_ASSERT(rdg->context);
1643 WINPR_ASSERT(rdg->context->rdp);
1644 transport_set_layer(rdg->context->rdp->transport, TRANSPORT_LAYER_CLOSED);
1645 return FALSE;
1646 }
1647 }
1648
1649 return TRUE;
1650}
1651
1652BOOL rdg_connect(rdpRdg* rdg, DWORD timeout, BOOL* rpcFallback)
1653{
1654 BOOL status = 0;
1655 SOCKET outConnSocket = 0;
1656 char* peerAddress = nullptr;
1657 BOOL rpcFallbackLocal = FALSE;
1658
1659 WINPR_ASSERT(rdg != nullptr);
1660 freerdp_set_last_error(rdg->context, ERROR_SUCCESS);
1661 status = rdg_establish_data_connection(rdg, rdg->tlsOut, "RDG_OUT_DATA", nullptr, timeout,
1662 &rpcFallbackLocal);
1663
1664 if (status)
1665 {
1666 if (rdg->transferEncoding.isWebsocketTransport)
1667 {
1668 WLog_Print(rdg->log, WLOG_DEBUG, "Upgraded to websocket. RDG_IN_DATA not required");
1669 }
1670 else
1671 {
1672 /* Establish IN connection with the same peer/server as OUT connection,
1673 * even when server hostname resolves to different IP addresses.
1674 */
1675 BIO_get_socket(rdg->tlsOut->underlying, &outConnSocket);
1676 peerAddress = freerdp_tcp_get_peer_address(outConnSocket);
1677 status = rdg_establish_data_connection(rdg, rdg->tlsIn, "RDG_IN_DATA", peerAddress,
1678 timeout, &rpcFallbackLocal);
1679 free(peerAddress);
1680 }
1681 }
1682
1683 if (rpcFallback)
1684 *rpcFallback = rpcFallbackLocal;
1685
1686 if (!status)
1687 {
1688 WINPR_ASSERT(rdg);
1689 WINPR_ASSERT(rdg->context);
1690 WINPR_ASSERT(rdg->context->rdp);
1691 if (rpcFallbackLocal)
1692 {
1693 http_context_enable_websocket_upgrade(rdg->http, FALSE);
1694 credssp_auth_free(rdg->auth);
1695 rdg->auth = nullptr;
1696 }
1697
1698 transport_set_layer(rdg->context->rdp->transport, TRANSPORT_LAYER_CLOSED);
1699 return FALSE;
1700 }
1701
1702 status = rdg_tunnel_connect(rdg);
1703
1704 return (status);
1705}
1706
1707static int rdg_write_websocket_data_packet(rdpRdg* rdg, const BYTE* buf, int isize)
1708{
1709 WINPR_ASSERT(rdg);
1710 if (isize < 0)
1711 return -1;
1712
1713 const size_t payloadSize = (size_t)isize + 10;
1714 union
1715 {
1716 UINT32 u32;
1717 UINT8 u8[4];
1718 } maskingKey;
1719
1720 wStream* sWS =
1721 websocket_context_packet_new(payloadSize, WebsocketBinaryOpcode, &maskingKey.u32);
1722 if (!sWS)
1723 return -1;
1724
1725 Stream_Write_UINT16(
1726 sWS, WINPR_ASSERTING_INT_CAST(
1727 uint16_t, PKT_TYPE_DATA ^ (maskingKey.u8[0] | maskingKey.u8[1] << 8))); /* Type */
1728 Stream_Write_UINT16(
1729 sWS, WINPR_ASSERTING_INT_CAST(
1730 uint16_t, 0 ^ (maskingKey.u8[2] | maskingKey.u8[3] << 8))); /* Reserved */
1731 Stream_Write_UINT32(
1732 sWS, WINPR_ASSERTING_INT_CAST(uint32_t, payloadSize ^ maskingKey.u32)); /* Packet length */
1733 Stream_Write_UINT16(
1734 sWS, WINPR_ASSERTING_INT_CAST(
1735 uint16_t, isize ^ (maskingKey.u8[0] | maskingKey.u8[1] << 8))); /* Data size */
1736
1737 /* masking key is now off by 2 bytes. fix that */
1738 maskingKey.u32 = (maskingKey.u32 & 0xffff) << 16 | (maskingKey.u32 >> 16);
1739
1740 WINPR_ASSERT(rdg->tlsOut);
1741 wStream sPacket = WINPR_C_ARRAY_INIT;
1742 Stream_StaticConstInit(&sPacket, buf, (size_t)isize);
1743 if (!websocket_context_mask_and_send(rdg->tlsOut->bio, sWS, &sPacket, maskingKey.u32))
1744 return -1;
1745
1746 return isize;
1747}
1748
1749static int rdg_write_chunked_data_packet(rdpRdg* rdg, const BYTE* buf, int isize)
1750{
1751 int status = 0;
1752 size_t len = 0;
1753 wStream* sChunk = nullptr;
1754
1755 if (isize > UINT16_MAX)
1756 return -1;
1757
1758 const size_t size = (size_t)isize;
1759 if (size < 1)
1760 return 0;
1761
1762 const size_t packetSize = size + 10;
1763 char chunkSize[11] = WINPR_C_ARRAY_INIT;
1764 (void)sprintf_s(chunkSize, sizeof(chunkSize), "%" PRIxz "\r\n", packetSize);
1765 sChunk = Stream_New(nullptr, strnlen(chunkSize, sizeof(chunkSize)) + packetSize + 2);
1766
1767 if (!sChunk)
1768 return -1;
1769
1770 Stream_Write(sChunk, chunkSize, strnlen(chunkSize, sizeof(chunkSize)));
1771 Stream_Write_UINT16(sChunk, PKT_TYPE_DATA); /* Type */
1772 Stream_Write_UINT16(sChunk, 0); /* Reserved */
1773 Stream_Write_UINT32(sChunk, (UINT32)packetSize); /* Packet length */
1774 Stream_Write_UINT16(sChunk, (UINT16)size); /* Data size */
1775 Stream_Write(sChunk, buf, size); /* Data */
1776 Stream_Write(sChunk, "\r\n", 2);
1777 Stream_SealLength(sChunk);
1778 len = Stream_Length(sChunk);
1779
1780 status = freerdp_tls_write_all(rdg->tlsIn, Stream_Buffer(sChunk), len);
1781 Stream_Free(sChunk, TRUE);
1782
1783 if (status < 0)
1784 return -1;
1785
1786 return (int)size;
1787}
1788
1789static int rdg_write_data_packet(rdpRdg* rdg, const BYTE* buf, int isize)
1790{
1791 WINPR_ASSERT(rdg);
1792 if (rdg->transferEncoding.isWebsocketTransport)
1793 return rdg_write_websocket_data_packet(rdg, buf, isize);
1794 else
1795 return rdg_write_chunked_data_packet(rdg, buf, isize);
1796}
1797
1798static BOOL rdg_process_close_packet(rdpRdg* rdg, wStream* s)
1799{
1800 int status = -1;
1801 wStream* sClose = nullptr;
1802 UINT32 errorCode = 0;
1803 UINT32 packetSize = 12;
1804
1805 /* Read error code */
1806 if (!Stream_CheckAndLogRequiredLengthWLog(rdg->log, s, 4))
1807 return FALSE;
1808 Stream_Read_UINT32(s, errorCode);
1809
1810 if (errorCode != 0)
1811 freerdp_set_last_error_log(rdg->context, errorCode);
1812
1813 sClose = Stream_New(nullptr, packetSize);
1814 if (!sClose)
1815 return FALSE;
1816
1817 Stream_Write_UINT16(sClose, PKT_TYPE_CLOSE_CHANNEL_RESPONSE); /* Type */
1818 Stream_Write_UINT16(sClose, 0); /* Reserved */
1819 Stream_Write_UINT32(sClose, packetSize); /* Packet length */
1820 Stream_Write_UINT32(sClose, 0); /* Status code */
1821 Stream_SealLength(sClose);
1822 status = rdg_write_packet(rdg, sClose);
1823 Stream_Free(sClose, TRUE);
1824
1825 return ((status >= 0));
1826}
1827
1828static BOOL rdg_process_keep_alive_packet(rdpRdg* rdg)
1829{
1830 int status = -1;
1831 wStream* sKeepAlive = nullptr;
1832 size_t packetSize = 8;
1833
1834 sKeepAlive = Stream_New(nullptr, packetSize);
1835
1836 if (!sKeepAlive)
1837 return FALSE;
1838
1839 Stream_Write_UINT16(sKeepAlive, PKT_TYPE_KEEPALIVE); /* Type */
1840 Stream_Write_UINT16(sKeepAlive, 0); /* Reserved */
1841 Stream_Write_UINT32(sKeepAlive, (UINT32)packetSize); /* Packet length */
1842 Stream_SealLength(sKeepAlive);
1843 status = rdg_write_packet(rdg, sKeepAlive);
1844 Stream_Free(sKeepAlive, TRUE);
1845
1846 return ((status >= 0));
1847}
1848
1849static BOOL rdg_process_service_message(rdpRdg* rdg, wStream* s)
1850{
1851 const WCHAR* msg = nullptr;
1852 UINT16 msgLenBytes = 0;
1853 rdpContext* context = rdg->context;
1854 WINPR_ASSERT(context);
1855 WINPR_ASSERT(context->instance);
1856
1857 /* Read message string */
1858 if (!rdg_read_http_unicode_string(rdg->log, s, &msg, &msgLenBytes))
1859 {
1860 WLog_Print(rdg->log, WLOG_ERROR, "Failed to read string");
1861 return FALSE;
1862 }
1863
1864 return IFCALLRESULT(TRUE, context->instance->PresentGatewayMessage, context->instance,
1865 GATEWAY_MESSAGE_SERVICE, TRUE, FALSE, msgLenBytes, msg);
1866}
1867
1868static BOOL rdg_process_unknown_packet(rdpRdg* rdg, int type)
1869{
1870 WINPR_UNUSED(rdg);
1871 WINPR_UNUSED(type);
1872 WLog_Print(rdg->log, WLOG_WARN, "Unknown Control Packet received: %" PRIX32,
1873 WINPR_CXX_COMPAT_CAST(UINT32, type));
1874 return TRUE;
1875}
1876
1877static BOOL rdg_process_control_packet(rdpRdg* rdg, int type, size_t packetLength)
1878{
1879 wStream* s = nullptr;
1880 size_t readCount = 0;
1881 int status = 0;
1882 size_t payloadSize = packetLength - sizeof(RdgPacketHeader);
1883
1884 if (packetLength < sizeof(RdgPacketHeader))
1885 return FALSE;
1886
1887 // NOLINTNEXTLINE(bugprone-sizeof-expression)
1888 WINPR_ASSERT(sizeof(RdgPacketHeader) < INT_MAX);
1889
1890 if (payloadSize)
1891 {
1892 s = Stream_New(nullptr, payloadSize);
1893
1894 if (!s)
1895 return FALSE;
1896
1897 while (readCount < payloadSize)
1898 {
1899 if (rdg_shall_abort(rdg))
1900 {
1901 Stream_Free(s, TRUE);
1902 return FALSE;
1903 }
1904 status = rdg_socket_read(rdg->tlsOut->bio, Stream_Pointer(s), payloadSize - readCount,
1905 &rdg->transferEncoding);
1906
1907 if (status <= 0)
1908 {
1909 if (!BIO_should_retry(rdg->tlsOut->bio))
1910 {
1911 Stream_Free(s, TRUE);
1912 return FALSE;
1913 }
1914
1915 continue;
1916 }
1917
1918 Stream_Seek(s, (size_t)status);
1919 readCount += (size_t)status;
1920
1921 if (readCount > INT_MAX)
1922 {
1923 Stream_Free(s, TRUE);
1924 return FALSE;
1925 }
1926 }
1927
1928 Stream_ResetPosition(s);
1929 }
1930
1931 switch (type)
1932 {
1933 case PKT_TYPE_CLOSE_CHANNEL:
1934 EnterCriticalSection(&rdg->writeSection);
1935 status = rdg_process_close_packet(rdg, s);
1936 LeaveCriticalSection(&rdg->writeSection);
1937 break;
1938
1939 case PKT_TYPE_KEEPALIVE:
1940 EnterCriticalSection(&rdg->writeSection);
1941 status = rdg_process_keep_alive_packet(rdg);
1942 LeaveCriticalSection(&rdg->writeSection);
1943 break;
1944
1945 case PKT_TYPE_SERVICE_MESSAGE:
1946 if (!s)
1947 {
1948 WLog_Print(rdg->log, WLOG_ERROR,
1949 "PKT_TYPE_SERVICE_MESSAGE requires payload but none was sent");
1950 return FALSE;
1951 }
1952 status = rdg_process_service_message(rdg, s);
1953 break;
1954
1955 case PKT_TYPE_REAUTH_MESSAGE:
1956 default:
1957 status = rdg_process_unknown_packet(rdg, type);
1958 break;
1959 }
1960
1961 Stream_Free(s, TRUE);
1962 return status;
1963}
1964
1965static int rdg_read_data_packet(rdpRdg* rdg, BYTE* buffer, size_t size)
1966{
1967 RdgPacketHeader header = WINPR_C_ARRAY_INIT;
1968 size_t readCount = 0;
1969 size_t readSize = 0;
1970 int status = 0;
1971
1972 if (!rdg->packetRemainingCount)
1973 {
1974 // NOLINTNEXTLINE(bugprone-sizeof-expression)
1975 WINPR_ASSERT(sizeof(RdgPacketHeader) < INT_MAX);
1976
1977 while (readCount < sizeof(RdgPacketHeader))
1978 {
1979 if (rdg_shall_abort(rdg))
1980 return -1;
1981
1982 status = rdg_socket_read(rdg->tlsOut->bio, (BYTE*)(&header) + readCount,
1983 sizeof(RdgPacketHeader) - readCount, &rdg->transferEncoding);
1984
1985 if (status <= 0)
1986 {
1987 if (!BIO_should_retry(rdg->tlsOut->bio))
1988 return -1;
1989
1990 if (!readCount)
1991 return 0;
1992
1993 BIO_wait_read(rdg->tlsOut->bio, 50);
1994 continue;
1995 }
1996
1997 readCount += (size_t)status;
1998
1999 if (readCount > INT_MAX)
2000 return -1;
2001 }
2002
2003 if (header.type != PKT_TYPE_DATA)
2004 {
2005 status = rdg_process_control_packet(rdg, header.type, header.packetLength);
2006
2007 if (!status)
2008 return -1;
2009
2010 return 0;
2011 }
2012
2013 readCount = 0;
2014
2015 while (readCount < 2)
2016 {
2017 if (rdg_shall_abort(rdg))
2018 return -1;
2019 status =
2020 rdg_socket_read(rdg->tlsOut->bio, (BYTE*)(&rdg->packetRemainingCount) + readCount,
2021 2 - readCount, &rdg->transferEncoding);
2022
2023 if (status < 0)
2024 {
2025 if (!BIO_should_retry(rdg->tlsOut->bio))
2026 return -1;
2027
2028 BIO_wait_read(rdg->tlsOut->bio, 50);
2029 continue;
2030 }
2031
2032 readCount += (size_t)status;
2033 }
2034 }
2035
2036 readSize = (rdg->packetRemainingCount < size) ? rdg->packetRemainingCount : size;
2037 status = rdg_socket_read(rdg->tlsOut->bio, buffer, readSize, &rdg->transferEncoding);
2038
2039 if (status <= 0)
2040 {
2041 if (!BIO_should_retry(rdg->tlsOut->bio))
2042 {
2043 return -1;
2044 }
2045
2046 return 0;
2047 }
2048
2049 rdg->packetRemainingCount -= status;
2050 return status;
2051}
2052
2053static int rdg_bio_write(BIO* bio, const char* buf, int num)
2054{
2055 int status = 0;
2056 rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);
2057 if (num < 0)
2058 return num;
2059
2060 BIO_clear_flags(bio, BIO_FLAGS_WRITE);
2061 EnterCriticalSection(&rdg->writeSection);
2062 status = rdg_write_data_packet(rdg, (const BYTE*)buf, num);
2063 LeaveCriticalSection(&rdg->writeSection);
2064
2065 if (status < 0)
2066 {
2067 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
2068 return -1;
2069 }
2070 else if (status < num)
2071 {
2072 BIO_set_flags(bio, BIO_FLAGS_WRITE);
2073 WSASetLastError(WSAEWOULDBLOCK);
2074 }
2075 else
2076 {
2077 BIO_set_flags(bio, BIO_FLAGS_WRITE);
2078 }
2079
2080 return status;
2081}
2082
2083static int rdg_bio_read(BIO* bio, char* buf, int size)
2084{
2085 int status = 0;
2086 rdpRdg* rdg = (rdpRdg*)BIO_get_data(bio);
2087 if (size < 0)
2088 return size;
2089 status = rdg_read_data_packet(rdg, (BYTE*)buf, (size_t)size);
2090
2091 if (status < 0)
2092 {
2093 BIO_clear_retry_flags(bio);
2094 return -1;
2095 }
2096 else if (status == 0)
2097 {
2098 BIO_set_retry_read(bio);
2099 WSASetLastError(WSAEWOULDBLOCK);
2100 return -1;
2101 }
2102 else
2103 {
2104 BIO_set_flags(bio, BIO_FLAGS_READ);
2105 }
2106
2107 return status;
2108}
2109
2110static int rdg_bio_puts(BIO* bio, const char* str)
2111{
2112 WINPR_UNUSED(bio);
2113 WINPR_UNUSED(str);
2114 return -2;
2115}
2116
2117// NOLINTNEXTLINE(readability-non-const-parameter)
2118static int rdg_bio_gets(BIO* bio, char* str, int size)
2119{
2120 WINPR_UNUSED(bio);
2121 WINPR_UNUSED(str);
2122 WINPR_UNUSED(size);
2123 return -2;
2124}
2125
2126static long rdg_bio_ctrl(BIO* in_bio, int cmd, long arg1, void* arg2)
2127{
2128 long status = -1;
2129 rdpRdg* rdg = (rdpRdg*)BIO_get_data(in_bio);
2130 rdpTls* tlsOut = rdg->tlsOut;
2131 rdpTls* tlsIn = rdg->tlsIn;
2132
2133 if (cmd == BIO_CTRL_FLUSH)
2134 {
2135 (void)BIO_flush(tlsOut->bio);
2136 if (!rdg->transferEncoding.isWebsocketTransport)
2137 (void)BIO_flush(tlsIn->bio);
2138 status = 1;
2139 }
2140 else if (cmd == BIO_C_SET_NONBLOCK)
2141 {
2142 status = 1;
2143 }
2144 else if (cmd == BIO_C_READ_BLOCKED)
2145 {
2146 BIO* cbio = tlsOut->bio;
2147 status = BIO_read_blocked(cbio);
2148 }
2149 else if (cmd == BIO_C_WRITE_BLOCKED)
2150 {
2151 BIO* cbio = tlsIn->bio;
2152
2153 if (rdg->transferEncoding.isWebsocketTransport)
2154 cbio = tlsOut->bio;
2155
2156 status = BIO_write_blocked(cbio);
2157 }
2158 else if (cmd == BIO_C_WAIT_READ)
2159 {
2160 int timeout = (int)arg1;
2161 BIO* cbio = tlsOut->bio;
2162
2163 if (BIO_read_blocked(cbio))
2164 return BIO_wait_read(cbio, timeout);
2165 else if (BIO_write_blocked(cbio))
2166 return BIO_wait_write(cbio, timeout);
2167 else
2168 status = 1;
2169 }
2170 else if (cmd == BIO_C_WAIT_WRITE)
2171 {
2172 int timeout = (int)arg1;
2173 BIO* cbio = tlsIn->bio;
2174
2175 if (rdg->transferEncoding.isWebsocketTransport)
2176 cbio = tlsOut->bio;
2177
2178 if (BIO_write_blocked(cbio))
2179 status = BIO_wait_write(cbio, timeout);
2180 else if (BIO_read_blocked(cbio))
2181 status = BIO_wait_read(cbio, timeout);
2182 else
2183 status = 1;
2184 }
2185 else if (cmd == BIO_C_GET_EVENT || cmd == BIO_C_GET_FD)
2186 {
2187 /*
2188 * A note about BIO_C_GET_FD:
2189 * Even if two FDs are part of RDG, only one FD can be returned here.
2190 *
2191 * In FreeRDP, BIO FDs are only used for polling, so it is safe to use the outgoing FD only
2192 *
2193 * See issue #3602
2194 */
2195 status = BIO_ctrl(tlsOut->bio, cmd, arg1, arg2);
2196 }
2197#if OPENSSL_VERSION_NUMBER >= 0x30000000L
2198 else if (cmd == BIO_CTRL_GET_KTLS_SEND)
2199 {
2200 /* Even though BIO_get_ktls_send says that returning negative values is valid
2201 * openssl internal sources are full of if(!BIO_get_ktls_send && ) stuff. This has some
2202 * nasty sideeffects. return 0 as proper no KTLS offloading flag
2203 */
2204 status = 0;
2205 }
2206 else if (cmd == BIO_CTRL_GET_KTLS_RECV)
2207 {
2208 /* Even though BIO_get_ktls_recv says that returning negative values is valid
2209 * there is no reason to trust trust negative values are implemented right everywhere
2210 */
2211 status = 0;
2212 }
2213#endif
2214 return status;
2215}
2216
2217static int rdg_bio_new(BIO* bio)
2218{
2219 BIO_set_init(bio, 1);
2220 BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
2221 return 1;
2222}
2223
2224static int rdg_bio_free(BIO* bio)
2225{
2226 WINPR_UNUSED(bio);
2227 return 1;
2228}
2229
2230static BIO_METHOD* BIO_s_rdg(void)
2231{
2232 static BIO_METHOD* bio_methods = nullptr;
2233
2234 if (bio_methods == nullptr)
2235 {
2236 if (!(bio_methods = BIO_meth_new(BIO_TYPE_TSG, "RDGateway")))
2237 return nullptr;
2238
2239 BIO_meth_set_write(bio_methods, rdg_bio_write);
2240 BIO_meth_set_read(bio_methods, rdg_bio_read);
2241 BIO_meth_set_puts(bio_methods, rdg_bio_puts);
2242 BIO_meth_set_gets(bio_methods, rdg_bio_gets);
2243 BIO_meth_set_ctrl(bio_methods, rdg_bio_ctrl);
2244 BIO_meth_set_create(bio_methods, rdg_bio_new);
2245 BIO_meth_set_destroy(bio_methods, rdg_bio_free);
2246 }
2247
2248 return bio_methods;
2249}
2250
2251rdpRdg* rdg_new(rdpContext* context)
2252{
2253 if (!context)
2254 return nullptr;
2255
2256 rdpRdg* rdg = (rdpRdg*)calloc(1, sizeof(rdpRdg));
2257 if (!rdg)
2258 return nullptr;
2259
2260 rdg->log = WLog_Get(TAG);
2261 rdg->state = RDG_CLIENT_STATE_INITIAL;
2262 rdg->context = context;
2263 rdpSettings* settings = rdg->context->settings;
2264 rdg->extAuth = (settings->GatewayHttpExtAuthSspiNtlm ? HTTP_EXTENDED_AUTH_SSPI_NTLM
2265 : HTTP_EXTENDED_AUTH_NONE);
2266
2267 if (settings->GatewayAccessToken)
2268 rdg->extAuth = HTTP_EXTENDED_AUTH_PAA;
2269
2270 rdg->tlsOut = freerdp_tls_new(rdg->context);
2271
2272 if (!rdg->tlsOut)
2273 goto rdg_alloc_error;
2274
2275 rdg->tlsIn = freerdp_tls_new(rdg->context);
2276
2277 if (!rdg->tlsIn)
2278 goto rdg_alloc_error;
2279
2280 rdg->http = http_context_new();
2281
2282 if (!rdg->http)
2283 goto rdg_alloc_error;
2284
2285 GUID guid = WINPR_C_ARRAY_INIT;
2286 if (UuidFromStringA(settings->CorrelationId, &guid) != RPC_S_OK)
2287 goto rdg_alloc_error;
2288
2289 if (!http_context_set_uri(rdg->http, "/remoteDesktopGateway/") ||
2290 !http_context_set_accept(rdg->http, "*/*") ||
2291 !http_context_set_cache_control(rdg->http, "no-cache") ||
2292 !http_context_set_pragma(rdg->http, "no-cache") ||
2293 !http_context_set_connection(rdg->http, "Keep-Alive") ||
2294 !http_context_set_user_agent(rdg->http, "MS-RDGateway/1.0") ||
2295 !http_context_set_host(rdg->http, rdg->context->settings->GatewayHostname) ||
2296 !http_context_set_rdg_connection_id(rdg->http) ||
2297 !http_context_set_rdg_correlation_id(rdg->http, &guid) ||
2298 !http_context_enable_websocket_upgrade(
2299 rdg->http,
2300 freerdp_settings_get_bool(rdg->context->settings, FreeRDP_GatewayHttpUseWebsockets)))
2301 {
2302 goto rdg_alloc_error;
2303 }
2304
2305 if (rdg->extAuth != HTTP_EXTENDED_AUTH_NONE)
2306 {
2307 switch (rdg->extAuth)
2308 {
2309 case HTTP_EXTENDED_AUTH_PAA:
2310 if (!http_context_set_rdg_auth_scheme(rdg->http, "PAA"))
2311 goto rdg_alloc_error;
2312
2313 break;
2314
2315 case HTTP_EXTENDED_AUTH_SSPI_NTLM:
2316 if (!http_context_set_rdg_auth_scheme(rdg->http, "SSPI_NTLM"))
2317 goto rdg_alloc_error;
2318
2319 break;
2320
2321 default:
2322 WLog_Print(rdg->log, WLOG_DEBUG,
2323 "RDG extended authentication method %d not supported", rdg->extAuth);
2324 }
2325 }
2326
2327 rdg->frontBio = BIO_new(BIO_s_rdg());
2328
2329 if (!rdg->frontBio)
2330 goto rdg_alloc_error;
2331
2332 BIO_set_data(rdg->frontBio, rdg);
2333 InitializeCriticalSection(&rdg->writeSection);
2334
2335 rdg->transferEncoding.httpTransferEncoding = TransferEncodingIdentity;
2336 rdg->transferEncoding.isWebsocketTransport = FALSE;
2337
2338 rdg->transferEncoding.context.websocket = websocket_context_new();
2339 if (!rdg->transferEncoding.context.websocket)
2340 goto rdg_alloc_error;
2341
2342 return rdg;
2343rdg_alloc_error:
2344 WINPR_PRAGMA_DIAG_PUSH
2345 WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
2346 rdg_free(rdg);
2347 WINPR_PRAGMA_DIAG_POP
2348 return nullptr;
2349}
2350
2351void rdg_free(rdpRdg* rdg)
2352{
2353 if (!rdg)
2354 return;
2355
2356 freerdp_tls_free(rdg->tlsOut);
2357 freerdp_tls_free(rdg->tlsIn);
2358 http_context_free(rdg->http);
2359 credssp_auth_free(rdg->auth);
2360
2361 if (!rdg->attached)
2362 BIO_free_all(rdg->frontBio);
2363
2364 DeleteCriticalSection(&rdg->writeSection);
2365
2366 smartcardCertInfo_Free(rdg->smartcard);
2367
2368 websocket_context_free(rdg->transferEncoding.context.websocket);
2369
2370 free(rdg);
2371}
2372
2373BIO* rdg_get_front_bio_and_take_ownership(rdpRdg* rdg)
2374{
2375 if (!rdg)
2376 return nullptr;
2377
2378 rdg->attached = TRUE;
2379 return rdg->frontBio;
2380}
FREERDP_API WCHAR * freerdp_settings_get_string_as_utf16(const rdpSettings *settings, FreeRDP_Settings_Keys_String id, size_t *pCharLen)
Return an allocated UTF16 string.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.