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