Coverage Report

Created: 2026-11-10 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/libfreerdp/core/connection.c
Line
Count
Source
1
/*
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Connection Sequence
4
 *
5
 * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2015 Thincast Technologies GmbH
7
 * Copyright 2015 DI (FH) Martin Haimberger <martin.haimberger@thincast.com>
8
 * Copyright 2023 Armin Novak <anovak@thincast.com>
9
 * Copyright 2023 Thincast Technologies GmbH
10
 *
11
 * Licensed under the Apache License, Version 2.0 (the "License");
12
 * you may not use this file except in compliance with the License.
13
 * You may obtain a copy of the License at
14
 *
15
 *     http://www.apache.org/licenses/LICENSE-2.0
16
 *
17
 * Unless required by applicable law or agreed to in writing, software
18
 * distributed under the License is distributed on an "AS IS" BASIS,
19
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
 * See the License for the specific language governing permissions and
21
 * limitations under the License.
22
 */
23
24
#include <freerdp/config.h>
25
26
#include "settings.h"
27
28
#include "info.h"
29
#include "input.h"
30
#include "rdp.h"
31
#include "peer.h"
32
33
#include "connection.h"
34
#include "transport.h"
35
36
#include <winpr/crt.h>
37
#include <winpr/crypto.h>
38
#include <winpr/ssl.h>
39
40
#include <freerdp/log.h>
41
#include <freerdp/error.h>
42
#include <freerdp/listener.h>
43
44
#include "../cache/cache.h"
45
#include "../cache/pointer.h"
46
#include "../crypto/crypto.h"
47
#include "../crypto/privatekey.h"
48
#include "../crypto/certificate.h"
49
#include "gateway/arm.h"
50
51
#include "utils.h"
52
53
0
#define TAG FREERDP_TAG("core.connection")
54
55
/**
56
 *                                      Connection Sequence
57
 *     client                                                                    server
58
 *        |                                                                         |
59
 *        |-----------------------X.224 Connection Request PDU--------------------->|
60
 *        |<----------------------X.224 Connection Confirm PDU----------------------|
61
 *        |-------MCS Connect-Initial PDU with GCC Conference Create Request------->|
62
 *        |<-----MCS Connect-Response PDU with GCC Conference Create Response-------|
63
 *        |------------------------MCS Erect Domain Request PDU-------------------->|
64
 *        |------------------------MCS Attach User Request PDU--------------------->|
65
 *        |<-----------------------MCS Attach User Confirm PDU----------------------|
66
 *        |------------------------MCS Channel Join Request PDU-------------------->|
67
 *        |<-----------------------MCS Channel Join Confirm PDU---------------------|
68
 *        |----------------------------Security Exchange PDU----------------------->|
69
 *        |-------------------------------Client Info PDU-------------------------->|
70
 *        |<---------------------License Error PDU - Valid Client-------------------|
71
 *        |<-----------------------------Demand Active PDU--------------------------|
72
 *        |------------------------------Confirm Active PDU------------------------>|
73
 *        |-------------------------------Synchronize PDU-------------------------->|
74
 *        |---------------------------Control PDU - Cooperate---------------------->|
75
 *        |------------------------Control PDU - Request Control------------------->|
76
 *        |--------------------------Persistent Key List PDU(s)-------------------->|
77
 *        |--------------------------------Font List PDU--------------------------->|
78
 *        |<------------------------------Synchronize PDU---------------------------|
79
 *        |<--------------------------Control PDU - Cooperate-----------------------|
80
 *        |<-----------------------Control PDU - Granted Control--------------------|
81
 *        |<-------------------------------Font Map PDU-----------------------------|
82
 *
83
 */
84
85
/**
86
 *
87
 * Connection Sequence
88
 *
89
 * 1. Connection Initiation: The client initiates the connection by sending the server a
90
 *  Class 0 X.224 Connection Request PDU (section 2.2.1.1). The server responds with a
91
 *  Class 0 X.224 Connection Confirm PDU (section 2.2.1.2). From this point, all subsequent
92
 *  data sent between client and server is wrapped in an X.224 Data Protocol Data Unit (PDU).
93
 *
94
 * 2. Basic Settings Exchange: Basic settings are exchanged between the client and server by
95
 *  using the MCS Connect Initial PDU (section 2.2.1.3) and MCS Connect Response PDU
96
 *(section 2.2.1.4). The Connect Initial PDU contains a Generic Conference Control (GCC) Conference
97
 *Create Request, while the Connect Response PDU contains a GCC Conference Create Response. These
98
 *two GCC packets contain concatenated blocks of settings data (such as core data, security data,
99
 *and network data) which are read by client and server.
100
 *
101
 * 3. Channel Connection: The client sends an MCS Erect Domain Request PDU (section 2.2.1.5),
102
 *  followed by an MCS Attach User Request PDU (section 2.2.1.6) to attach the primary user identity
103
 *  to the MCS domain. The server responds with an MCS Attach User Confirm PDU (section 2.2.1.7)
104
 *  containing the User Channel ID. The client then proceeds to join the user channel, the
105
 *  input/output (I/O) channel, and all of the static virtual channels (the I/O and static virtual
106
 *  channel IDs are obtained from the data embedded in the GCC packets) by using multiple MCS
107
 *Channel Join Request PDUs (section 2.2.1.8). The server confirms each channel with an MCS Channel
108
 *Join Confirm PDU (section 2.2.1.9). (The client only sends a Channel Join Request after it has
109
 *received the Channel Join Confirm for the previously sent request.)
110
 *
111
 *  From this point, all subsequent data sent from the client to the server is wrapped in an MCS
112
 *Send Data Request PDU, while data sent from the server to the client is wrapped in an MCS Send
113
 *Data Indication PDU. This is in addition to the data being wrapped by an X.224 Data PDU.
114
 *
115
 * 4. RDP Security Commencement: If Standard RDP Security mechanisms (section 5.3) are being
116
 *employed and encryption is in force (this is determined by examining the data embedded in the GCC
117
 *Conference Create Response packet) then the client sends a Security Exchange PDU
118
 *(section 2.2.1.10) containing an encrypted 32-byte random number to the server. This random number
119
 *is encrypted with the public key of the server as described in section 5.3.4.1 (the server's
120
 *public key, as well as a 32-byte server-generated random number, are both obtained from the data
121
 *embedded in the GCC Conference Create Response packet). The client and server then utilize the two
122
 *32-byte random numbers to generate session keys which are used to encrypt and validate the
123
 *integrity of subsequent RDP traffic.
124
 *
125
 *  From this point, all subsequent RDP traffic can be encrypted and a security header is included
126
 *with the data if encryption is in force. (The Client Info PDU (section 2.2.1.11) and licensing
127
 *PDUs ([MS-RDPELE] section 2.2.2) are an exception in that they always have a security header). The
128
 *Security Header follows the X.224 and MCS Headers and indicates whether the attached data is
129
 *encrypted. Even if encryption is in force, server-to-client traffic may not always be encrypted,
130
 *while client-to-server traffic must always be encrypted (encryption of licensing PDUs is optional,
131
 *however).
132
 *
133
 * 5. Secure Settings Exchange: Secure client data (such as the username, password, and
134
 *auto-reconnect cookie) is sent to the server by using the Client Info PDU (section 2.2.1.11).
135
 *
136
 * 6. Optional Connect-Time Auto-Detection: During the optional connect-time auto-detect phase the
137
 *goal is to determine characteristics of the network, such as the round-trip latency time and the
138
 *bandwidth of the link between the server and client. This is accomplished by exchanging a
139
 *collection of PDUs (specified in section 2.2.1.4) over a predetermined period of time with enough
140
 *data to ensure that the results are statistically relevant.
141
 *
142
 * 7. Licensing: The goal of the licensing exchange is to transfer a license from the server to
143
 *the client. The client stores this license and on subsequent connections sends the license to the
144
 *server for validation. However, in some situations the client may not be issued a license to
145
 *store. In effect, the packets exchanged during this phase of the protocol depend on the licensing
146
 *mechanisms employed by the server. Within the context of this document, it is assumed that the
147
 *client will not be issued a license to store. For details regarding more advanced licensing
148
 *scenarios that take place during the Licensing Phase, see [MS-RDPELE] section 1.3.
149
 *
150
 * 8. Optional Multitransport Bootstrapping: After the connection has been secured and the
151
 *Licensing Phase has run to completion, the server can choose to initiate multitransport
152
 *connections ([MS-RDPEMT] section 1.3). The Initiate Multitransport Request PDU (section 2.2.15.1)
153
 *is sent by the server to the client and results in the out-of-band creation of a multitransport
154
 *connection using messages from the RDP-UDP, TLS, DTLS, and multitransport protocols ([MS-RDPEMT]
155
 *section 1.3.1).
156
 *
157
 * 9. Capabilities Exchange: The server sends the set of capabilities it supports to the client in
158
 *a Demand Active PDU (section 2.2.1.13.1). The client responds with its capabilities by sending a
159
 *Confirm Active PDU (section 2.2.1.13.2).
160
 *
161
 * 10.  Connection Finalization: The client and server exchange PDUs to finalize the connection
162
 *details. The client-to-server PDUs sent during this phase have no dependencies on any of the
163
 *server-to-client PDUs; they may be sent as a single batch, provided that sequencing is maintained.
164
 *
165
 *  - The Client Synchronize PDU (section 2.2.1.14) is sent after transmitting the Confirm Active
166
 *PDU.
167
 *  - The Client Control (Cooperate) PDU (section 2.2.1.15) is sent after transmitting the Client
168
 *Synchronize PDU.
169
 *  - The Client Control (Request Control) PDU (section 2.2.1.16) is sent after transmitting the
170
 *Client Control (Cooperate) PDU.
171
 *  - The optional Persistent Key List PDUs (section 2.2.1.17) are sent after transmitting the
172
 *Client Control (Request Control) PDU.
173
 *  - The Font List PDU (section 2.2.1.18) is sent after transmitting the Persistent Key List PDUs
174
 *or, if the Persistent Key List PDUs were not sent, it is sent after transmitting the Client
175
 *Control (Request Control) PDU (section 2.2.1.16).
176
 *
177
 *  The server-to-client PDUs sent during the Connection Finalization Phase have dependencies on the
178
 *client-to-server PDUs.
179
 *
180
 *  - The optional Monitor Layout PDU (section 2.2.12.1) has no dependency on any client-to-server
181
 *PDUs and is sent after the Demand Active PDU.
182
 *  - The Server Synchronize PDU (section 2.2.1.19) is sent in response to the Confirm Active PDU.
183
 *  - The Server Control (Cooperate) PDU (section 2.2.1.20) is sent after transmitting the Server
184
 *Synchronize PDU.
185
 *  - The Server Control (Granted Control) PDU (section 2.2.1.21) is sent in response to the Client
186
 *Control (Request Control) PDU.
187
 *  - The Font Map PDU (section 2.2.1.22) is sent in response to the Font List PDU.
188
 *
189
 *  Once the client has sent the Confirm Active PDU, it can start sending mouse and keyboard input
190
 *to the server, and upon receipt of the Font List PDU the server can start sending graphics output
191
 *to the client.
192
 *
193
 *  Besides input and graphics data, other data that can be exchanged between client and server
194
 *after the connection has been finalized includes connection management information and virtual
195
 *channel messages (exchanged between client-side plug-ins and server-side applications).
196
 */
197
198
static BOOL rdp_set_state(rdpRdp* rdp, CONNECTION_STATE state);
199
200
static BOOL rdp_client_reset_codecs(rdpContext* context)
201
0
{
202
0
  rdpSettings* settings = nullptr;
203
204
0
  if (!context || !context->settings)
205
0
    return FALSE;
206
207
0
  settings = context->settings;
208
209
0
  if (!freerdp_settings_get_bool(settings, FreeRDP_DeactivateClientDecoding))
210
0
  {
211
0
    const UINT32 flags = freerdp_settings_get_uint32(settings, FreeRDP_ThreadingFlags);
212
0
    freerdp_client_codecs_free(context->codecs);
213
0
    context->codecs = freerdp_client_codecs_new(flags);
214
215
0
    if (!context->codecs)
216
0
      return FALSE;
217
218
0
    if (!freerdp_client_codecs_prepare(context->codecs,
219
0
                                       freerdp_settings_get_codecs_flags(settings),
220
0
                                       settings->DesktopWidth, settings->DesktopHeight))
221
0
      return FALSE;
222
223
/* Runtime H264 detection. (only available if dynamic backend loading is defined, or
224
 * in the browser, which might not decode H.264)
225
 * If no backend is available disable it before the channel is loaded.
226
 */
227
#if defined(WITH_GFX_H264) && (defined(WITH_OPENH264_LOADING) || defined(WITH_H264_WEBCODECS))
228
    if (!context->codecs->h264)
229
    {
230
      settings->GfxH264 = FALSE;
231
      settings->GfxAVC444 = FALSE;
232
      settings->GfxAVC444v2 = FALSE;
233
    }
234
#endif
235
0
  }
236
237
0
  return TRUE;
238
0
}
239
240
static BOOL rdp_client_wait_for_activation(rdpRdp* rdp)
241
0
{
242
0
  BOOL timedout = FALSE;
243
0
  WINPR_ASSERT(rdp);
244
245
0
  const rdpSettings* settings = rdp->settings;
246
0
  WINPR_ASSERT(settings);
247
248
0
  UINT64 now = GetTickCount64();
249
0
  UINT64 dueDate = now + freerdp_settings_get_uint32(settings, FreeRDP_TcpAckTimeout);
250
251
0
  for (; (now < dueDate) && !timedout; now = GetTickCount64())
252
0
  {
253
0
    HANDLE events[MAXIMUM_WAIT_OBJECTS] = WINPR_C_ARRAY_INIT;
254
0
    DWORD wstatus = 0;
255
0
    DWORD nevents = freerdp_get_event_handles(rdp->context, events, ARRAYSIZE(events));
256
0
    if (!nevents)
257
0
    {
258
0
      WLog_ERR(TAG, "error retrieving connection events");
259
0
      return FALSE;
260
0
    }
261
262
0
    const UINT64 timeout = (dueDate - now);
263
0
    WINPR_ASSERT(timeout <= UINT32_MAX);
264
0
    wstatus = WaitForMultipleObjectsEx(nevents, events, FALSE, (UINT32)timeout, TRUE);
265
0
    switch (wstatus)
266
0
    {
267
0
      case WAIT_TIMEOUT:
268
        /* will make us quit with a timeout */
269
0
        timedout = TRUE;
270
0
        break;
271
0
      case WAIT_ABANDONED:
272
0
      case WAIT_FAILED:
273
0
        return FALSE;
274
0
      case WAIT_IO_COMPLETION:
275
0
        break;
276
0
      case WAIT_OBJECT_0:
277
0
      default:
278
        /* handles all WAIT_OBJECT_0 + [0 .. MAXIMUM_WAIT_OBJECTS-1] cases */
279
0
        if (rdp_check_fds(rdp) < 0)
280
0
        {
281
0
          freerdp_set_last_error_if_not(rdp->context,
282
0
                                        FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
283
0
          return FALSE;
284
0
        }
285
0
        break;
286
0
    }
287
288
0
    if (rdp_is_active_state(rdp))
289
0
      return TRUE;
290
0
  }
291
292
0
  WLog_ERR(TAG, "Timeout waiting for activation");
293
0
  freerdp_set_last_error_if_not(rdp->context, FREERDP_ERROR_CONNECT_ACTIVATION_TIMEOUT);
294
0
  return FALSE;
295
0
}
296
/**
297
 * Establish RDP Connection based on the settings given in the 'rdp' parameter.
298
 * msdn{cc240452}
299
 * @param rdp RDP module
300
 * @return true if the connection succeeded. FALSE otherwise.
301
 */
302
303
BOOL rdp_client_connect(rdpRdp* rdp)
304
0
{
305
0
  UINT32 SelectedProtocol = 0;
306
0
  BOOL status = 0;
307
  /* make sure SSL is initialize for earlier enough for crypto, by taking advantage of winpr SSL
308
   * FIPS flag for openssl initialization */
309
0
  DWORD flags = WINPR_SSL_INIT_DEFAULT;
310
311
0
  WINPR_ASSERT(rdp);
312
313
0
  rdpSettings* settings = rdp->settings;
314
0
  WINPR_ASSERT(settings);
315
316
0
  if (!rdp_client_reset_codecs(rdp->context))
317
0
    return FALSE;
318
319
0
  if (settings->FIPSMode)
320
0
    flags |= WINPR_SSL_INIT_ENABLE_FIPS;
321
322
0
  if (!winpr_InitializeSSL(flags))
323
0
    return FALSE;
324
325
0
  rdp_log_build_warnings(rdp);
326
327
  /* FIPS Mode forces the following and overrides the following(by happening later
328
   * in the command line processing):
329
   * 1. Forces the only supported RDP encryption method to be FIPS.
330
   * 2. Disables NTLM authentication (not FIPS compliant due to MD4/RC4).
331
   * 3. Disables RDP Security if 3DES is not available in the crypto provider. */
332
0
  if (settings->FIPSMode || winpr_FIPSMode())
333
0
  {
334
335
0
    settings->EncryptionMethods = ENCRYPTION_METHOD_FIPS;
336
337
0
    if (!settings->AuthenticationPackageList)
338
0
    {
339
0
      if (!freerdp_settings_set_string(settings, FreeRDP_AuthenticationPackageList, "!ntlm"))
340
0
        return FALSE;
341
0
    }
342
343
0
    const BYTE key[WINPR_CIPHER_MAX_KEY_LENGTH] = WINPR_C_ARRAY_INIT;
344
0
    const BYTE iv[WINPR_CIPHER_MAX_IV_LENGTH] = WINPR_C_ARRAY_INIT;
345
0
    WINPR_CIPHER_CTX* ctx = winpr_Cipher_NewEx(WINPR_CIPHER_DES_EDE3_CBC, WINPR_ENCRYPT, key,
346
0
                                               sizeof(key), iv, sizeof(iv));
347
0
    if (ctx)
348
0
    {
349
0
      winpr_Cipher_Free(ctx);
350
0
    }
351
0
    else
352
0
    {
353
0
      settings->RdpSecurity = FALSE;
354
0
    }
355
0
  }
356
357
0
  UINT32 TcpConnectTimeout = freerdp_settings_get_uint32(settings, FreeRDP_TcpConnectTimeout);
358
0
  if (settings->GatewayArmTransport)
359
0
  {
360
0
    if (!arm_resolve_endpoint(rdp->log, rdp->context, TcpConnectTimeout))
361
0
    {
362
0
      WLog_ERR(TAG, "error retrieving ARM configuration");
363
0
      return FALSE;
364
0
    }
365
0
  }
366
367
0
  const char* hostname = settings->ServerHostname;
368
0
  if (!hostname)
369
0
  {
370
0
    WLog_ERR(TAG, "Missing hostname, can not connect to nullptr target");
371
0
    return FALSE;
372
0
  }
373
374
0
  const UINT32 port = settings->ServerPort;
375
0
  WINPR_ASSERT(port <= UINT32_MAX);
376
377
0
  if (!rdp->nego)
378
0
    return FALSE;
379
380
0
  nego_init(rdp->nego);
381
0
  nego_set_target(rdp->nego, hostname, (UINT16)port);
382
383
0
  if (settings->GatewayEnabled)
384
0
  {
385
0
    char* user = nullptr;
386
0
    char* domain = nullptr;
387
0
    size_t user_length = 0;
388
389
0
    if (settings->Username)
390
0
    {
391
0
      user = settings->Username;
392
0
      user_length = strlen(settings->Username);
393
0
    }
394
395
0
    if (settings->Domain)
396
0
      domain = settings->Domain;
397
0
    else
398
0
      domain = settings->ComputerName;
399
400
0
    const size_t domain_length = strlen(domain);
401
0
    const size_t cookie_length = domain_length + 1 + user_length;
402
0
    char* cookie = malloc(cookie_length + 1);
403
404
0
    if (!cookie)
405
0
      return FALSE;
406
407
0
    CopyMemory(cookie, domain, domain_length);
408
0
    WINPR_ASSERT(domain_length <= UINT32_MAX);
409
0
    CharUpperBuffA(cookie, (UINT32)domain_length);
410
0
    cookie[domain_length] = '\\';
411
412
0
    if (settings->Username)
413
0
      CopyMemory(&cookie[domain_length + 1], user, user_length);
414
415
0
    cookie[cookie_length] = '\0';
416
0
    status = nego_set_cookie(rdp->nego, cookie);
417
0
    free(cookie);
418
0
  }
419
0
  else
420
0
  {
421
0
    status = nego_set_cookie(rdp->nego, settings->Username);
422
0
  }
423
424
0
  if (!status)
425
0
    return FALSE;
426
427
0
  nego_set_childsession_enabled(rdp->nego, settings->ConnectChildSession);
428
0
  nego_set_send_preconnection_pdu(rdp->nego, settings->SendPreconnectionPdu);
429
0
  nego_set_preconnection_id(rdp->nego, settings->PreconnectionId);
430
0
  nego_set_preconnection_blob(rdp->nego, settings->PreconnectionBlob);
431
0
  nego_set_negotiation_enabled(rdp->nego, settings->NegotiateSecurityLayer);
432
0
  nego_set_restricted_admin_mode_required(rdp->nego, settings->RestrictedAdminModeRequired);
433
0
  nego_set_RCG_required(rdp->nego, settings->RemoteCredentialGuard);
434
0
  nego_set_gateway_enabled(rdp->nego, settings->GatewayEnabled);
435
0
  nego_set_gateway_bypass_local(rdp->nego, settings->GatewayBypassLocal);
436
0
  nego_enable_rdp(rdp->nego, settings->RdpSecurity);
437
0
  nego_enable_tls(rdp->nego, settings->TlsSecurity);
438
0
  nego_enable_nla(rdp->nego, settings->NlaSecurity);
439
0
  nego_enable_ext(rdp->nego, settings->ExtSecurity);
440
0
  nego_enable_rdstls(rdp->nego, settings->RdstlsSecurity);
441
0
  nego_enable_aad(rdp->nego, settings->AadSecurity);
442
443
0
  if (settings->MstscCookieMode)
444
0
    settings->CookieMaxLength = MSTSC_COOKIE_MAX_LENGTH;
445
446
0
  nego_set_cookie_max_length(rdp->nego, settings->CookieMaxLength);
447
448
0
  if (settings->LoadBalanceInfo && (settings->LoadBalanceInfoLength > 0))
449
0
  {
450
0
    if (!nego_set_routing_token(rdp->nego, settings->LoadBalanceInfo,
451
0
                                settings->LoadBalanceInfoLength))
452
0
      return FALSE;
453
0
  }
454
455
0
  if (!freerdp_settings_get_bool(settings, FreeRDP_TransportDumpReplay))
456
0
  {
457
0
    if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_NEGO))
458
0
      return FALSE;
459
460
0
    if (!nego_connect(rdp->nego))
461
0
    {
462
0
      if (!freerdp_get_last_error(rdp->context))
463
0
      {
464
0
        freerdp_set_last_error_log(rdp->context,
465
0
                                   FREERDP_ERROR_SECURITY_NEGO_CONNECT_FAILED);
466
0
        WLog_ERR(TAG, "Error: protocol security negotiation or connection failure");
467
0
      }
468
469
0
      return FALSE;
470
0
    }
471
472
0
    SelectedProtocol = nego_get_selected_protocol(rdp->nego);
473
474
0
    if ((SelectedProtocol & PROTOCOL_SSL) || (SelectedProtocol == PROTOCOL_RDP) ||
475
0
        (SelectedProtocol == PROTOCOL_RDSTLS))
476
0
    {
477
0
      wStream s = WINPR_C_ARRAY_INIT;
478
479
0
      if ((settings->Username != nullptr) &&
480
0
          ((freerdp_settings_get_string(settings, FreeRDP_Password) != nullptr) ||
481
0
           (settings->RedirectionPassword != nullptr &&
482
0
            settings->RedirectionPasswordLength > 0)))
483
0
        settings->AutoLogonEnabled = TRUE;
484
485
0
      if (rdp_recv_callback(rdp->transport, &s, rdp) < 0)
486
0
        return FALSE;
487
0
    }
488
489
0
    if (!transport_set_blocking_mode(rdp->transport, FALSE))
490
0
      return FALSE;
491
0
  }
492
0
  else
493
0
  {
494
0
    if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_CREATE_REQUEST))
495
0
      return FALSE;
496
0
  }
497
498
  /* everything beyond this point is event-driven and non blocking */
499
0
  if (!transport_set_recv_callbacks(rdp->transport, rdp_recv_callback, rdp))
500
0
    return FALSE;
501
502
  /* A tunnel the server asked for during the connection sequence is of no use when the
503
   * sequence fails. It is stopped now: the next disconnect, which would stop it too, can be a
504
   * long way off, an auto-reconnect waits between attempts. */
505
0
  const BOOL activated = rdp_client_wait_for_activation(rdp);
506
0
  if (!activated)
507
0
    multitransport_reset(rdp->multitransport);
508
0
  return activated;
509
0
}
510
511
BOOL rdp_client_disconnect(rdpRdp* rdp)
512
0
{
513
0
  rdpContext* context = nullptr;
514
515
0
  if (!rdp || !rdp->settings || !rdp->context)
516
0
    return FALSE;
517
518
0
  context = rdp->context;
519
520
  /* Leave the active state before the transport goes away: input functions are called from
521
   * other threads and only check the state, so they must stop before rdp_reset() frees the
522
   * transport and fastpath they use. */
523
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_INITIAL))
524
0
    return FALSE;
525
526
0
  if (rdp->nego)
527
0
  {
528
0
    if (!nego_disconnect(rdp->nego))
529
0
      return FALSE;
530
0
  }
531
532
0
  if (!transport_disconnect(rdp->transport))
533
0
    return FALSE;
534
535
0
  if (!rdp_reset(rdp))
536
0
    return FALSE;
537
538
0
  if (context->channels)
539
0
  {
540
0
    if (freerdp_channels_disconnect(context->channels, context->instance) != CHANNEL_RC_OK)
541
0
      return FALSE;
542
0
  }
543
544
0
  freerdp_client_codecs_free(context->codecs);
545
0
  context->codecs = nullptr;
546
0
  return TRUE;
547
0
}
548
549
BOOL rdp_client_disconnect_and_clear(rdpRdp* rdp)
550
0
{
551
0
  rdpContext* context = nullptr;
552
553
0
  if (!rdp_client_disconnect(rdp))
554
0
    return FALSE;
555
556
0
  WINPR_ASSERT(rdp);
557
558
0
  context = rdp->context;
559
0
  WINPR_ASSERT(context);
560
561
0
  if (freerdp_get_last_error(context) == FREERDP_ERROR_CONNECT_CANCELLED)
562
0
    return FALSE;
563
564
0
  context->LastError = FREERDP_ERROR_SUCCESS;
565
0
  clearChannelError(context);
566
0
  return utils_reset_abort(rdp);
567
0
}
568
569
static BOOL rdp_client_reconnect_channels(rdpRdp* rdp, BOOL redirect)
570
0
{
571
0
  BOOL status = FALSE;
572
0
  rdpContext* context = nullptr;
573
574
0
  if (!rdp || !rdp->context || !rdp->context->channels)
575
0
    return FALSE;
576
577
0
  context = rdp->context;
578
579
0
  if (context->instance->ConnectionCallbackState == CLIENT_STATE_INITIAL)
580
0
    return FALSE;
581
582
0
  if (context->instance->ConnectionCallbackState == CLIENT_STATE_PRECONNECT_PASSED)
583
0
  {
584
0
    if (redirect)
585
0
      return TRUE;
586
587
0
    pointer_cache_register_callbacks(context->update);
588
589
0
    if (!cache_resize(context))
590
0
      return FALSE;
591
592
0
    if (!IFCALLRESULT(FALSE, context->instance->PostConnect, context->instance))
593
0
      return FALSE;
594
595
0
    context->instance->ConnectionCallbackState = CLIENT_STATE_POSTCONNECT_PASSED;
596
0
  }
597
598
0
  if (context->instance->ConnectionCallbackState == CLIENT_STATE_POSTCONNECT_PASSED)
599
0
    status =
600
0
        (freerdp_channels_post_connect(context->channels, context->instance) == CHANNEL_RC_OK);
601
602
0
  return status;
603
0
}
604
605
static BOOL rdp_client_redirect_resolvable(const char* host)
606
0
{
607
0
  struct addrinfo* result = freerdp_tcp_resolve_host(host, -1, 0);
608
609
0
  if (!result)
610
0
    return FALSE;
611
612
0
  freeaddrinfo(result);
613
0
  return TRUE;
614
0
}
615
616
static BOOL rdp_client_redirect_try_fqdn(rdpSettings* settings)
617
0
{
618
0
  if (settings->RedirectionFlags & LB_TARGET_FQDN)
619
0
  {
620
0
    if (settings->GatewayEnabled ||
621
0
        rdp_client_redirect_resolvable(settings->RedirectionTargetFQDN))
622
0
    {
623
0
      return (freerdp_settings_set_string(settings, FreeRDP_ServerHostname,
624
0
                                          settings->RedirectionTargetFQDN));
625
0
    }
626
0
  }
627
628
0
  return FALSE;
629
0
}
630
631
static BOOL rdp_client_redirect_try_ip(rdpSettings* settings)
632
0
{
633
0
  if (settings->RedirectionFlags & LB_TARGET_NET_ADDRESS)
634
0
  {
635
0
    return (freerdp_settings_set_string(settings, FreeRDP_ServerHostname,
636
0
                                        settings->TargetNetAddress));
637
0
  }
638
639
0
  return FALSE;
640
0
}
641
642
static BOOL rdp_client_redirect_try_netbios(rdpSettings* settings)
643
0
{
644
0
  if (settings->RedirectionFlags & LB_TARGET_NETBIOS_NAME)
645
0
  {
646
0
    if (settings->GatewayEnabled ||
647
0
        rdp_client_redirect_resolvable(settings->RedirectionTargetNetBiosName))
648
0
    {
649
0
      return (freerdp_settings_set_string(settings, FreeRDP_ServerHostname,
650
0
                                          settings->RedirectionTargetNetBiosName));
651
0
    }
652
0
  }
653
654
0
  return FALSE;
655
0
}
656
657
BOOL rdp_client_redirect(rdpRdp* rdp)
658
0
{
659
0
  BOOL status = 0;
660
0
  rdpSettings* settings = nullptr;
661
662
0
  if (!rdp_client_disconnect_and_clear(rdp))
663
0
    return FALSE;
664
665
  /* Only disconnect & close the channels here.
666
   * they will be discarded and recreated after the new settings have been applied. */
667
0
  freerdp_channels_disconnect(rdp->context->channels, rdp->context->instance);
668
0
  freerdp_channels_close(rdp->context->channels, rdp->context->instance);
669
670
0
  if (rdp_redirection_apply_settings(rdp) != 0)
671
0
    return FALSE;
672
673
0
  WINPR_ASSERT(rdp);
674
675
0
  settings = rdp->settings;
676
0
  WINPR_ASSERT(settings);
677
678
0
  if ((settings->RedirectionFlags & LB_LOAD_BALANCE_INFO) == 0)
679
0
  {
680
0
    BOOL haveRedirectAddress = FALSE;
681
0
    UINT32 redirectionMask = settings->RedirectionPreferType;
682
683
0
    do
684
0
    {
685
0
      const BOOL tryFQDN = (redirectionMask & 0x01) == 0;
686
0
      const BOOL tryNetAddress = (redirectionMask & 0x02) == 0;
687
0
      const BOOL tryNetbios = (redirectionMask & 0x04) == 0;
688
689
0
      if (tryFQDN && !haveRedirectAddress)
690
0
        haveRedirectAddress = rdp_client_redirect_try_fqdn(settings);
691
692
0
      if (tryNetAddress && !haveRedirectAddress)
693
0
        haveRedirectAddress = rdp_client_redirect_try_ip(settings);
694
695
0
      if (tryNetbios && !haveRedirectAddress)
696
0
        haveRedirectAddress = rdp_client_redirect_try_netbios(settings);
697
698
0
      redirectionMask >>= 3;
699
0
    } while (!haveRedirectAddress && (redirectionMask != 0));
700
0
  }
701
702
0
  if (settings->RedirectionFlags & LB_USERNAME)
703
0
  {
704
0
    if (!freerdp_settings_set_string(
705
0
            settings, FreeRDP_Username,
706
0
            freerdp_settings_get_string(settings, FreeRDP_RedirectionUsername)))
707
0
      return FALSE;
708
0
  }
709
710
0
  if (settings->RedirectionFlags & LB_DOMAIN)
711
0
  {
712
0
    if (!freerdp_settings_set_string(
713
0
            settings, FreeRDP_Domain,
714
0
            freerdp_settings_get_string(settings, FreeRDP_RedirectionDomain)))
715
0
      return FALSE;
716
0
  }
717
718
0
  settings->RdstlsSecurity = ((settings->RedirectionFlags & LB_PASSWORD_IS_PK_ENCRYPTED) != 0);
719
720
0
  WINPR_ASSERT(rdp->context);
721
0
  WINPR_ASSERT(rdp->context->instance);
722
0
  if (!IFCALLRESULT(TRUE, rdp->context->instance->Redirect, rdp->context->instance))
723
0
    return FALSE;
724
725
0
  BOOL ok = utils_reload_channels(rdp->context);
726
0
  if (!ok)
727
0
    return FALSE;
728
729
0
  rdp->redirectionCount++;
730
0
  status = rdp_client_connect(rdp);
731
732
0
  if (status)
733
0
    status = rdp_client_reconnect_channels(rdp, TRUE);
734
735
0
  return status;
736
0
}
737
738
/* A redirection that carried a one-time RDSTLS token (LB_PASSWORD_IS_PK_ENCRYPTED) cannot be
739
 * replayed: reconnecting straight to the redirected host is refused with SEC_E_INVALID_TOKEN.
740
 * Go back to the server the connection was originally made to (the RD Connection Broker), which
741
 * redirects again to the same session with a fresh token. Everything the redirection changed
742
 * (host, load balance info, user, redirected session id, auto-reconnect cookie) has to go, so
743
 * start again from the settings the connection began with, the way rdp_client_redirect() does:
744
 * the channels are closed before the settings they use are freed, and loaded again after. */
745
WINPR_ATTR_NODISCARD
746
static BOOL rdp_client_reconnect_via_broker(rdpRdp* rdp, BOOL* viaBroker)
747
0
{
748
0
  WINPR_ASSERT(rdp);
749
0
  WINPR_ASSERT(viaBroker);
750
0
  *viaBroker = FALSE;
751
0
  const rdpSettings* settings = rdp->settings;
752
0
  WINPR_ASSERT(settings);
753
754
0
  if (!rdp->originalSettings || !freerdp_settings_get_bool(settings, FreeRDP_RdstlsSecurity))
755
0
    return TRUE;
756
0
  if ((freerdp_settings_get_uint32(settings, FreeRDP_RedirectionFlags) &
757
0
       LB_PASSWORD_IS_PK_ENCRYPTED) == 0)
758
0
    return TRUE;
759
760
0
  WINPR_ASSERT(rdp->context);
761
0
  WINPR_ASSERT(rdp->context->instance);
762
0
  WLog_INFO(TAG, "the redirection used a one-time RDSTLS token, reconnecting through %s",
763
0
            freerdp_settings_get_string(rdp->originalSettings, FreeRDP_ServerHostname));
764
765
0
  freerdp_channels_disconnect(rdp->context->channels, rdp->context->instance);
766
0
  freerdp_channels_close(rdp->context->channels, rdp->context->instance);
767
768
0
  if (!rdp_reset_runtime_settings(rdp))
769
0
    return FALSE;
770
0
  if (!freerdp_settings_set_bool(rdp->settings, FreeRDP_SessionHasBeenReconnected, TRUE))
771
0
    return FALSE;
772
0
  if (!IFCALLRESULT(TRUE, rdp->context->instance->Redirect, rdp->context->instance))
773
0
    return FALSE;
774
0
  if (!utils_reload_channels(rdp->context))
775
0
    return FALSE;
776
777
0
  *viaBroker = TRUE;
778
0
  return TRUE;
779
0
}
780
781
/* Pause before reconnecting a connection that its UDP tunnel ended, see rdp_client_reconnect. */
782
0
#define TUNNEL_RECONNECT_PAUSE_MS 2000
783
784
BOOL rdp_client_reconnect(rdpRdp* rdp)
785
0
{
786
  /* A connection ended by its UDP tunnel closes TCP cleanly, and the server starts tearing
787
   * the session down at once. Windows drops a reconnect that arrives during that teardown,
788
   * and the auto-reconnect then waits out its whole retry delay. */
789
0
  const BOOL tunnelEnded = multitransport_ended_connection(rdp->multitransport);
790
791
0
  if (!rdp_client_disconnect_and_clear(rdp))
792
0
    return FALSE;
793
794
0
  if (tunnelEnded)
795
0
  {
796
0
    WLog_DBG(TAG, "the UDP tunnel ended the connection, reconnecting in %d ms",
797
0
             TUNNEL_RECONNECT_PAUSE_MS);
798
0
    if (WaitForSingleObject(utils_get_abort_event(rdp), TUNNEL_RECONNECT_PAUSE_MS) ==
799
0
        WAIT_OBJECT_0)
800
0
      return FALSE;
801
0
  }
802
803
0
  if (!freerdp_settings_set_bool(rdp->settings, FreeRDP_SessionHasBeenReconnected, TRUE))
804
0
    return FALSE;
805
806
0
  BOOL viaBroker = FALSE;
807
0
  if (!rdp_client_reconnect_via_broker(rdp, &viaBroker))
808
0
    return FALSE;
809
810
0
  const UINT32 redirectionCount = rdp->redirectionCount;
811
0
  BOOL status = rdp_client_connect(rdp);
812
813
  /* When the broker redirected us, rdp_client_redirect() already reloaded and reconnected the
814
   * channels (rdp_check_fds() runs it from inside rdp_client_connect()); doing it a second time
815
   * fails with CHANNEL_RC_ALREADY_OPEN and makes the whole attempt fail. RedirectionFlags can't
816
   * tell: ARM sets them during the connect without any redirection. */
817
0
  const BOOL redirected = rdp->redirectionCount != redirectionCount;
818
0
  if (status && !redirected)
819
0
    status = rdp_client_reconnect_channels(rdp, viaBroker);
820
821
0
  return status;
822
0
}
823
824
static const BYTE fips_ivec[8] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
825
826
static BOOL rdp_client_establish_keys(rdpRdp* rdp)
827
0
{
828
0
  wStream* s = nullptr;
829
0
  BOOL ret = FALSE;
830
831
0
  WINPR_ASSERT(rdp);
832
0
  rdpSettings* settings = rdp->settings;
833
0
  BYTE* crypt_client_random = nullptr;
834
835
0
  WINPR_ASSERT(settings);
836
0
  if (!settings->UseRdpSecurityLayer)
837
0
  {
838
    /* no RDP encryption */
839
0
    return TRUE;
840
0
  }
841
842
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT))
843
0
    return FALSE;
844
845
  /* encrypt client random */
846
0
  if (!freerdp_settings_set_pointer_len(settings, FreeRDP_ClientRandom, nullptr,
847
0
                                        CLIENT_RANDOM_LENGTH))
848
0
    return FALSE;
849
0
  if (winpr_RAND(settings->ClientRandom, settings->ClientRandomLength) < 0)
850
0
    return FALSE;
851
852
0
  const rdpCertInfo* info = freerdp_certificate_get_info(settings->RdpServerCertificate);
853
0
  if (!info)
854
0
  {
855
0
    WLog_ERR(TAG, "Failed to get rdpCertInfo from RdpServerCertificate");
856
0
    return FALSE;
857
0
  }
858
859
  /*
860
   * client random must be (bitlen / 8) + 8 - see [MS-RDPBCGR] 5.3.4.1
861
   * for details
862
   */
863
0
  crypt_client_random = calloc(info->ModulusLength, 1);
864
865
0
  if (!crypt_client_random)
866
0
    return FALSE;
867
868
0
  if (crypto_rsa_public_encrypt(settings->ClientRandom, settings->ClientRandomLength, info,
869
0
                                crypt_client_random, info->ModulusLength) < 0)
870
0
    goto end;
871
  /* send crypt client random to server */
872
0
  const size_t length = RDP_PACKET_HEADER_MAX_LENGTH + RDP_SECURITY_HEADER_LENGTH + 4ULL +
873
0
                        info->ModulusLength + 8ULL;
874
0
  if (length > UINT16_MAX)
875
0
    goto end;
876
877
0
  s = Stream_New(nullptr, length);
878
879
0
  if (!s)
880
0
  {
881
0
    WLog_ERR(TAG, "Stream_New failed!");
882
0
    goto end;
883
0
  }
884
885
0
  {
886
0
    const UINT16 sec_flags = SEC_EXCHANGE_PKT | SEC_LICENSE_ENCRYPT_SC;
887
0
    if (!rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID, sec_flags))
888
0
      goto end;
889
0
    if (!rdp_write_security_header(rdp, s, sec_flags))
890
0
      goto end;
891
0
  }
892
893
0
  Stream_Write_UINT32(s, info->ModulusLength + 8);
894
0
  Stream_Write(s, crypt_client_random, info->ModulusLength);
895
0
  Stream_Zero(s, 8);
896
0
  Stream_SealLength(s);
897
898
0
  {
899
0
    rdpTransport* transport = freerdp_get_transport(rdp->context);
900
0
    const int status = transport_write(transport, s);
901
902
0
    if (status < 0)
903
0
      goto end;
904
0
  }
905
906
0
  rdp->do_crypt_license = TRUE;
907
908
  /* now calculate encrypt / decrypt and update keys */
909
0
  if (!security_establish_keys(rdp))
910
0
    goto end;
911
912
0
  rdp->do_crypt = TRUE;
913
914
0
  if (settings->SaltedChecksum)
915
0
    rdp->do_secure_checksum = TRUE;
916
917
0
  if (settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
918
0
  {
919
0
    rdp->fips_encrypt =
920
0
        winpr_Cipher_NewEx(WINPR_CIPHER_DES_EDE3_CBC, WINPR_ENCRYPT, rdp->fips_encrypt_key,
921
0
                           sizeof(rdp->fips_encrypt_key), fips_ivec, sizeof(fips_ivec));
922
923
0
    if (!rdp->fips_encrypt)
924
0
    {
925
0
      WLog_ERR(TAG, "unable to allocate des3 encrypt key");
926
0
      goto end;
927
0
    }
928
929
0
    rdp->fips_decrypt =
930
0
        winpr_Cipher_NewEx(WINPR_CIPHER_DES_EDE3_CBC, WINPR_DECRYPT, rdp->fips_decrypt_key,
931
0
                           sizeof(rdp->fips_decrypt_key), fips_ivec, sizeof(fips_ivec));
932
933
0
    if (!rdp->fips_decrypt)
934
0
    {
935
0
      WLog_ERR(TAG, "unable to allocate des3 decrypt key");
936
0
      goto end;
937
0
    }
938
939
0
    ret = TRUE;
940
0
    goto end;
941
0
  }
942
943
0
  if (!rdp_reset_rc4_encrypt_keys(rdp))
944
0
    goto end;
945
0
  if (!rdp_reset_rc4_decrypt_keys(rdp))
946
0
    goto end;
947
948
0
  ret = TRUE;
949
0
end:
950
0
  Stream_Free(s, TRUE);
951
0
  free(crypt_client_random);
952
953
0
  if (!ret)
954
0
  {
955
0
    winpr_Cipher_Free(rdp->fips_decrypt);
956
0
    winpr_Cipher_Free(rdp->fips_encrypt);
957
0
    rdp->fips_decrypt = nullptr;
958
0
    rdp->fips_encrypt = nullptr;
959
960
0
    rdp_free_rc4_decrypt_keys(rdp);
961
0
    rdp_free_rc4_encrypt_keys(rdp);
962
0
  }
963
964
0
  return ret;
965
0
}
966
967
static BOOL rdp_update_client_random(rdpSettings* settings, const BYTE* crypt_random,
968
                                     size_t crypt_random_len)
969
0
{
970
0
  const size_t length = 32;
971
0
  WINPR_ASSERT(settings);
972
973
0
  const rdpPrivateKey* rsa = freerdp_settings_get_pointer(settings, FreeRDP_RdpServerRsaKey);
974
0
  WINPR_ASSERT(rsa);
975
976
0
  const rdpCertInfo* cinfo = freerdp_key_get_info(rsa);
977
0
  WINPR_ASSERT(cinfo);
978
979
0
  if (crypt_random_len != cinfo->ModulusLength + 8)
980
0
  {
981
0
    WLog_ERR(TAG, "invalid encrypted client random length");
982
0
    return FALSE;
983
0
  }
984
0
  if (!freerdp_settings_set_pointer_len(settings, FreeRDP_ClientRandom, nullptr, length))
985
0
    return FALSE;
986
987
0
  BYTE* client_random = freerdp_settings_get_pointer_writable(settings, FreeRDP_ClientRandom);
988
0
  WINPR_ASSERT(client_random);
989
0
  return crypto_rsa_private_decrypt(crypt_random, crypt_random_len - 8, rsa, client_random,
990
0
                                    length) > 0;
991
0
}
992
993
BOOL rdp_server_establish_keys(rdpRdp* rdp, wStream* s)
994
0
{
995
0
  UINT32 rand_len = 0;
996
0
  UINT16 channel_id = 0;
997
0
  UINT16 length = 0;
998
0
  UINT16 sec_flags = 0;
999
0
  BOOL ret = FALSE;
1000
1001
0
  WINPR_ASSERT(rdp);
1002
1003
0
  if (!rdp->settings->UseRdpSecurityLayer)
1004
0
  {
1005
    /* No RDP Security. */
1006
0
    return TRUE;
1007
0
  }
1008
1009
0
  if (!rdp_read_header(rdp, s, &length, &channel_id))
1010
0
    return FALSE;
1011
1012
0
  if (freerdp_shall_disconnect_context(rdp->context))
1013
0
    return TRUE;
1014
1015
0
  if (!rdp_read_security_header(rdp, s, &sec_flags, nullptr))
1016
0
  {
1017
0
    WLog_Print(rdp->log, WLOG_ERROR, "invalid security header");
1018
0
    return FALSE;
1019
0
  }
1020
1021
0
  if ((sec_flags & SEC_EXCHANGE_PKT) == 0)
1022
0
  {
1023
0
    WLog_Print(rdp->log, WLOG_ERROR, "missing SEC_EXCHANGE_PKT in security header");
1024
0
    return FALSE;
1025
0
  }
1026
1027
0
  rdp->do_crypt_license = ((sec_flags & SEC_LICENSE_ENCRYPT_SC) != 0);
1028
1029
0
  if (!Stream_CheckAndLogRequiredLengthWLog(rdp->log, s, 4))
1030
0
    return FALSE;
1031
1032
0
  Stream_Read_UINT32(s, rand_len);
1033
1034
  /* rand_len already includes 8 bytes of padding */
1035
0
  if (!Stream_CheckAndLogRequiredLengthWLog(rdp->log, s, rand_len))
1036
0
    return FALSE;
1037
1038
0
  const BYTE* crypt_random = Stream_ConstPointer(s);
1039
0
  if (!Stream_SafeSeek(s, rand_len))
1040
0
    goto end;
1041
0
  if (!rdp_update_client_random(rdp->settings, crypt_random, rand_len))
1042
0
    goto end;
1043
1044
  /* now calculate encrypt / decrypt and update keys */
1045
0
  if (!security_establish_keys(rdp))
1046
0
    goto end;
1047
1048
0
  rdp->do_crypt = TRUE;
1049
1050
0
  if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
1051
0
  {
1052
0
    rdp->fips_encrypt =
1053
0
        winpr_Cipher_NewEx(WINPR_CIPHER_DES_EDE3_CBC, WINPR_ENCRYPT, rdp->fips_encrypt_key,
1054
0
                           sizeof(rdp->fips_encrypt_key), fips_ivec, sizeof(fips_ivec));
1055
1056
0
    if (!rdp->fips_encrypt)
1057
0
    {
1058
0
      WLog_Print(rdp->log, WLOG_ERROR, "unable to allocate des3 encrypt key");
1059
0
      goto end;
1060
0
    }
1061
1062
0
    rdp->fips_decrypt =
1063
0
        winpr_Cipher_NewEx(WINPR_CIPHER_DES_EDE3_CBC, WINPR_DECRYPT, rdp->fips_decrypt_key,
1064
0
                           sizeof(rdp->fips_decrypt_key), fips_ivec, sizeof(fips_ivec));
1065
1066
0
    if (!rdp->fips_decrypt)
1067
0
    {
1068
0
      WLog_Print(rdp->log, WLOG_ERROR, "unable to allocate des3 decrypt key");
1069
0
      goto end;
1070
0
    }
1071
1072
0
    ret = TRUE;
1073
0
    goto end;
1074
0
  }
1075
1076
0
  if (!rdp_reset_rc4_encrypt_keys(rdp))
1077
0
    goto end;
1078
1079
0
  if (!rdp_reset_rc4_decrypt_keys(rdp))
1080
0
    goto end;
1081
1082
0
  ret = tpkt_ensure_stream_consumed(rdp->log, s, length);
1083
0
end:
1084
1085
0
  if (!ret)
1086
0
  {
1087
0
    winpr_Cipher_Free(rdp->fips_encrypt);
1088
0
    winpr_Cipher_Free(rdp->fips_decrypt);
1089
0
    rdp->fips_encrypt = nullptr;
1090
0
    rdp->fips_decrypt = nullptr;
1091
1092
0
    rdp_free_rc4_encrypt_keys(rdp);
1093
0
    rdp_free_rc4_decrypt_keys(rdp);
1094
0
  }
1095
1096
0
  return ret;
1097
0
}
1098
1099
static BOOL rdp_client_send_client_info_and_change_state(rdpRdp* rdp)
1100
0
{
1101
0
  WINPR_ASSERT(rdp);
1102
0
  if (!rdp_client_establish_keys(rdp))
1103
0
    return FALSE;
1104
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE))
1105
0
    return FALSE;
1106
0
  if (!rdp_send_client_info(rdp))
1107
0
    return FALSE;
1108
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT_REQUEST))
1109
0
    return FALSE;
1110
0
  return TRUE;
1111
0
}
1112
1113
BOOL rdp_client_skip_mcs_channel_join(rdpRdp* rdp)
1114
0
{
1115
0
  WINPR_ASSERT(rdp);
1116
1117
0
  rdpMcs* mcs = rdp->mcs;
1118
0
  WINPR_ASSERT(mcs);
1119
1120
0
  mcs->userChannelJoined = TRUE;
1121
0
  mcs->globalChannelJoined = TRUE;
1122
0
  mcs->messageChannelJoined = TRUE;
1123
1124
0
  for (UINT32 i = 0; i < mcs->channelCount; i++)
1125
0
  {
1126
0
    rdpMcsChannel* cur = &mcs->channels[i];
1127
0
    WLog_DBG(TAG, " %s [%" PRIu16 "]", cur->Name, cur->ChannelId);
1128
0
    cur->joined = TRUE;
1129
0
  }
1130
1131
0
  return rdp_client_send_client_info_and_change_state(rdp);
1132
0
}
1133
1134
static BOOL rdp_client_join_channel(rdpRdp* rdp, UINT16 ChannelId)
1135
0
{
1136
0
  WINPR_ASSERT(rdp);
1137
1138
0
  rdpMcs* mcs = rdp->mcs;
1139
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN_REQUEST))
1140
0
    return FALSE;
1141
0
  if (!mcs_send_channel_join_request(mcs, ChannelId))
1142
0
    return FALSE;
1143
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN_RESPONSE))
1144
0
    return FALSE;
1145
0
  return TRUE;
1146
0
}
1147
1148
BOOL rdp_client_connect_mcs_channel_join_confirm(rdpRdp* rdp, wStream* s)
1149
0
{
1150
0
  UINT16 channelId = 0;
1151
0
  BOOL allJoined = TRUE;
1152
1153
0
  WINPR_ASSERT(rdp);
1154
0
  rdpMcs* mcs = rdp->mcs;
1155
1156
0
  if (!mcs_recv_channel_join_confirm(mcs, s, &channelId))
1157
0
    return FALSE;
1158
1159
0
  if (!mcs->userChannelJoined)
1160
0
  {
1161
0
    if (channelId != mcs->userId)
1162
0
    {
1163
0
      WLog_ERR(TAG, "expected user channel id %" PRIu16 ", but received %" PRIu16,
1164
0
               mcs->userId, channelId);
1165
0
      return FALSE;
1166
0
    }
1167
1168
0
    mcs->userChannelJoined = TRUE;
1169
0
    if (!rdp_client_join_channel(rdp, MCS_GLOBAL_CHANNEL_ID))
1170
0
      return FALSE;
1171
0
  }
1172
0
  else if (!mcs->globalChannelJoined)
1173
0
  {
1174
0
    if (channelId != MCS_GLOBAL_CHANNEL_ID)
1175
0
    {
1176
0
      WLog_ERR(TAG, "expected uglobalser channel id %d, but received %" PRIu16,
1177
0
               MCS_GLOBAL_CHANNEL_ID, channelId);
1178
0
      return FALSE;
1179
0
    }
1180
0
    mcs->globalChannelJoined = TRUE;
1181
1182
0
    if (mcs->messageChannelId != 0)
1183
0
    {
1184
0
      if (!rdp_client_join_channel(rdp, mcs->messageChannelId))
1185
0
        return FALSE;
1186
0
      allJoined = FALSE;
1187
0
    }
1188
0
    else
1189
0
    {
1190
0
      if (mcs->channelCount > 0)
1191
0
      {
1192
0
        const rdpMcsChannel* cur = &mcs->channels[0];
1193
0
        if (!rdp_client_join_channel(rdp, cur->ChannelId))
1194
0
          return FALSE;
1195
0
        allJoined = FALSE;
1196
0
      }
1197
0
    }
1198
0
  }
1199
0
  else if ((mcs->messageChannelId != 0) && !mcs->messageChannelJoined)
1200
0
  {
1201
0
    if (channelId != mcs->messageChannelId)
1202
0
    {
1203
0
      WLog_ERR(TAG, "expected messageChannelId=%" PRIu16 ", got %" PRIu16,
1204
0
               mcs->messageChannelId, channelId);
1205
0
      return FALSE;
1206
0
    }
1207
1208
0
    mcs->messageChannelJoined = TRUE;
1209
1210
0
    if (mcs->channelCount > 0)
1211
0
    {
1212
0
      const rdpMcsChannel* cur = &mcs->channels[0];
1213
0
      if (!rdp_client_join_channel(rdp, cur->ChannelId))
1214
0
        return FALSE;
1215
0
      allJoined = FALSE;
1216
0
    }
1217
0
  }
1218
0
  else
1219
0
  {
1220
0
    UINT32 i = 0;
1221
0
    for (; i < mcs->channelCount; i++)
1222
0
    {
1223
0
      rdpMcsChannel* cur = &mcs->channels[i];
1224
0
      if (cur->joined)
1225
0
        continue;
1226
1227
0
      if (cur->ChannelId != channelId)
1228
0
      {
1229
0
        WLog_ERR(TAG, "expected channel id %d, but received %" PRIu16,
1230
0
                 MCS_GLOBAL_CHANNEL_ID, channelId);
1231
0
        return FALSE;
1232
0
      }
1233
0
      cur->joined = TRUE;
1234
0
      break;
1235
0
    }
1236
1237
0
    if (i + 1 < mcs->channelCount)
1238
0
    {
1239
0
      const rdpMcsChannel* cur = &mcs->channels[i + 1];
1240
0
      if (!rdp_client_join_channel(rdp, cur->ChannelId))
1241
0
        return FALSE;
1242
0
      allJoined = FALSE;
1243
0
    }
1244
0
  }
1245
1246
0
  if (mcs->userChannelJoined && mcs->globalChannelJoined && allJoined)
1247
0
  {
1248
0
    if (!rdp_client_send_client_info_and_change_state(rdp))
1249
0
      return FALSE;
1250
0
  }
1251
1252
0
  return TRUE;
1253
0
}
1254
1255
state_run_t rdp_handle_message_channel(rdpRdp* rdp, wStream* s, UINT16 channelId, UINT16 length)
1256
0
{
1257
0
  WINPR_ASSERT(rdp);
1258
0
  WINPR_ASSERT(rdp->mcs);
1259
1260
0
  if (!rdp->mcs->messageChannelJoined)
1261
0
  {
1262
0
    WLog_Print(rdp->log, WLOG_WARN, "MCS message channel not joined!");
1263
0
    return STATE_RUN_FAILED;
1264
0
  }
1265
0
  const UINT16 messageChannelId = rdp->mcs->messageChannelId;
1266
0
  if (messageChannelId == 0)
1267
0
  {
1268
0
    WLog_Print(rdp->log, WLOG_WARN, "MCS message channel id == 0");
1269
0
    return STATE_RUN_FAILED;
1270
0
  }
1271
1272
0
  if ((channelId != messageChannelId) && (channelId != MCS_GLOBAL_CHANNEL_ID))
1273
0
  {
1274
0
    WLog_Print(rdp->log, WLOG_WARN,
1275
0
               "MCS message channel expected id=[%" PRIu16 "|%d], got %" PRIu16,
1276
0
               messageChannelId, MCS_GLOBAL_CHANNEL_ID, channelId);
1277
0
    return STATE_RUN_FAILED;
1278
0
  }
1279
1280
0
  UINT16 securityFlags = 0;
1281
0
  if (!rdp_read_security_header(rdp, s, &securityFlags, &length))
1282
0
    return STATE_RUN_FAILED;
1283
1284
0
  if (securityFlags & SEC_ENCRYPT)
1285
0
  {
1286
0
    if (!rdp_decrypt(rdp, s, &length, securityFlags))
1287
0
      return STATE_RUN_FAILED;
1288
0
  }
1289
1290
0
  const state_run_t rc = rdp_recv_message_channel_pdu(rdp, s, securityFlags);
1291
0
  if (state_run_success(rc))
1292
0
  {
1293
0
    if (!tpkt_ensure_stream_consumed(rdp->log, s, length))
1294
0
      return STATE_RUN_FAILED;
1295
0
  }
1296
0
  return rc;
1297
0
}
1298
1299
BOOL rdp_client_connect_auto_detect(rdpRdp* rdp, wStream* s, DWORD logLevel)
1300
0
{
1301
0
  BOOL res = TRUE;
1302
0
  WINPR_ASSERT(rdp);
1303
0
  WINPR_ASSERT(rdp->mcs);
1304
1305
0
  size_t pos = Stream_GetPosition(s);
1306
0
  UINT16 length = 0;
1307
0
  UINT16 channelId = 0;
1308
1309
0
  if (!rdp_read_header(rdp, s, &length, &channelId))
1310
0
    res = FALSE;
1311
0
  else
1312
0
  {
1313
0
    if (freerdp_shall_disconnect_context(rdp->context))
1314
0
      return TRUE;
1315
1316
0
    const UINT16 messageChannelId = rdp->mcs->messageChannelId;
1317
    /* If the MCS message channel has been joined... */
1318
1319
    /* Process any MCS message channel PDUs. */
1320
0
    if (rdp->mcs->messageChannelJoined && (channelId == messageChannelId))
1321
0
    {
1322
0
      const state_run_t rc = rdp_handle_message_channel(rdp, s, channelId, length);
1323
0
      res = state_run_success(rc);
1324
0
      pos = Stream_GetPosition(s);
1325
0
    }
1326
0
    else
1327
0
    {
1328
0
      wLog* log = WLog_Get(TAG);
1329
0
      WLog_Print(log, logLevel, "expected messageChannelId=%" PRIu16 ", got %" PRIu16,
1330
0
                 messageChannelId, channelId);
1331
0
      res = FALSE;
1332
0
    }
1333
0
  }
1334
1335
0
  if (!Stream_SetPosition(s, pos))
1336
0
    res = FALSE;
1337
0
  return res;
1338
0
}
1339
1340
state_run_t rdp_client_connect_license(rdpRdp* rdp, wStream* s)
1341
0
{
1342
0
  state_run_t status = STATE_RUN_FAILED;
1343
0
  LICENSE_STATE state = LICENSE_STATE_ABORTED;
1344
0
  UINT16 length = 0;
1345
0
  UINT16 channelId = 0;
1346
0
  UINT16 securityFlags = 0;
1347
1348
0
  WINPR_ASSERT(rdp);
1349
0
  if (!rdp_read_header(rdp, s, &length, &channelId))
1350
0
    return STATE_RUN_FAILED;
1351
1352
0
  if (freerdp_shall_disconnect_context(rdp->context))
1353
0
    return STATE_RUN_QUIT_SESSION;
1354
1355
  /* there might be autodetect messages mixed in between licensing messages.
1356
   * that has been observed with 2k12 R2 and 2k19
1357
   */
1358
0
  const UINT16 messageChannelId = rdp->mcs->messageChannelId;
1359
0
  if (rdp->mcs->messageChannelJoined && (channelId == messageChannelId))
1360
0
  {
1361
0
    return rdp_handle_message_channel(rdp, s, channelId, length);
1362
0
  }
1363
1364
0
  if (!rdp_read_security_header(rdp, s, &securityFlags, &length))
1365
0
    return STATE_RUN_FAILED;
1366
1367
0
  if (securityFlags & SEC_ENCRYPT)
1368
0
  {
1369
0
    if (!rdp_decrypt(rdp, s, &length, securityFlags))
1370
0
      return STATE_RUN_FAILED;
1371
0
  }
1372
1373
0
  if (channelId != MCS_GLOBAL_CHANNEL_ID)
1374
0
    WLog_WARN(TAG, "unexpected message for channel %u, expected %d", channelId,
1375
0
              MCS_GLOBAL_CHANNEL_ID);
1376
1377
0
  if ((securityFlags & SEC_LICENSE_PKT) == 0)
1378
0
  {
1379
0
    char buffer[512] = WINPR_C_ARRAY_INIT;
1380
0
    char lbuffer[32] = WINPR_C_ARRAY_INIT;
1381
0
    WLog_ERR(TAG, "securityFlags=%s, missing required flag %s",
1382
0
             rdp_security_flag_string(securityFlags, buffer, sizeof(buffer)),
1383
0
             rdp_security_flag_string(SEC_LICENSE_PKT, lbuffer, sizeof(lbuffer)));
1384
0
    return STATE_RUN_FAILED;
1385
0
  }
1386
1387
0
  status = license_recv(rdp->license, s);
1388
1389
0
  if (state_run_failed(status))
1390
0
    return status;
1391
1392
0
  state = license_get_state(rdp->license);
1393
0
  switch (state)
1394
0
  {
1395
0
    case LICENSE_STATE_ABORTED:
1396
0
      WLog_ERR(TAG, "license connection sequence aborted.");
1397
0
      return STATE_RUN_FAILED;
1398
0
    case LICENSE_STATE_COMPLETED:
1399
0
      if (rdp->settings->MultitransportFlags)
1400
0
      {
1401
0
        if (!rdp_client_transition_to_state(
1402
0
                rdp, CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING_REQUEST))
1403
0
          return STATE_RUN_FAILED;
1404
0
      }
1405
0
      else
1406
0
      {
1407
0
        if (!rdp_client_transition_to_state(
1408
0
                rdp, CONNECTION_STATE_CAPABILITIES_EXCHANGE_DEMAND_ACTIVE))
1409
0
          return STATE_RUN_FAILED;
1410
0
      }
1411
0
      return STATE_RUN_SUCCESS;
1412
0
    default:
1413
0
      return STATE_RUN_SUCCESS;
1414
0
  }
1415
0
}
1416
1417
state_run_t rdp_client_connect_demand_active(rdpRdp* rdp, wStream* s)
1418
0
{
1419
0
  UINT16 length = 0;
1420
0
  UINT16 channelId = 0;
1421
0
  UINT16 pduType = 0;
1422
0
  UINT16 pduSource = 0;
1423
1424
0
  WINPR_ASSERT(rdp);
1425
0
  WINPR_ASSERT(s);
1426
0
  WINPR_ASSERT(rdp->settings);
1427
1428
0
  if (!rdp_recv_get_active_header(rdp, s, &channelId, &length))
1429
0
    return STATE_RUN_FAILED;
1430
1431
0
  if (freerdp_shall_disconnect_context(rdp->context))
1432
0
    return STATE_RUN_QUIT_SESSION;
1433
1434
0
  if (rdp->mcs->messageChannelId && (channelId == rdp->mcs->messageChannelId))
1435
0
  {
1436
0
    rdp->inPackets++;
1437
0
    return rdp_handle_message_channel(rdp, s, channelId, length);
1438
0
  }
1439
1440
0
  if (!rdp_handle_optional_rdp_decryption(rdp, s, &length, nullptr))
1441
0
    return STATE_RUN_FAILED;
1442
1443
0
  UINT16 remainingLength = 0;
1444
0
  if (!rdp_read_share_control_header(rdp, s, nullptr, &remainingLength, &pduType, &pduSource))
1445
0
    return STATE_RUN_FAILED;
1446
1447
0
  switch (pduType)
1448
0
  {
1449
0
    case PDU_TYPE_DEMAND_ACTIVE:
1450
      /* Demand Active consumes this entire payload. Check its Share Control
1451
       * boundary after decryption, when security headers and FIPS padding
1452
       * have been removed. Do not apply this to other, potentially batched
1453
       * Share Control PDUs. */
1454
0
      if (remainingLength != Stream_GetRemainingLength(s))
1455
0
      {
1456
0
        WLog_Print(rdp->log, WLOG_ERROR,
1457
0
                   "Demand Active payload length %" PRIu16
1458
0
                   " differs from remaining data %" PRIuz,
1459
0
                   remainingLength, Stream_GetRemainingLength(s));
1460
0
        return STATE_RUN_FAILED;
1461
0
      }
1462
0
      if (!rdp_recv_demand_active(rdp, s, pduSource, length))
1463
0
        return STATE_RUN_FAILED;
1464
0
      return STATE_RUN_ACTIVE;
1465
0
    default:
1466
0
      return rdp_recv_out_of_sequence_pdu(rdp, s, pduType, length);
1467
0
  }
1468
0
}
1469
1470
WINPR_ATTR_NODISCARD
1471
static state_run_t rdp_client_connect_finalize(rdpRdp* rdp)
1472
0
{
1473
0
  WINPR_ASSERT(rdp);
1474
  /**
1475
   * [MS-RDPBCGR] 1.3.1.1 - 8.
1476
   * The client-to-server PDUs sent during this phase have no dependencies on any of the
1477
   * server-to- client PDUs; they may be sent as a single batch, provided that sequencing is
1478
   * maintained.
1479
   */
1480
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_SYNC))
1481
0
    return STATE_RUN_FAILED;
1482
1483
0
  if (!rdp_send_client_synchronize_pdu(rdp))
1484
0
    return STATE_RUN_FAILED;
1485
1486
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_COOPERATE))
1487
0
    return STATE_RUN_FAILED;
1488
0
  if (!rdp_send_client_control_pdu(rdp, CTRLACTION_COOPERATE))
1489
0
    return STATE_RUN_FAILED;
1490
1491
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_REQUEST_CONTROL))
1492
0
    return STATE_RUN_FAILED;
1493
0
  if (!rdp_send_client_control_pdu(rdp, CTRLACTION_REQUEST_CONTROL))
1494
0
    return STATE_RUN_FAILED;
1495
1496
  /**
1497
   * [MS-RDPBCGR] 2.2.1.17
1498
   * Client persistent key list must be sent if a bitmap is
1499
   * stored in persistent bitmap cache or the server has advertised support for bitmap
1500
   * host cache and a deactivation reactivation sequence is *not* in progress.
1501
   */
1502
1503
0
  if (!rdp_finalize_is_flag_set(rdp, FINALIZE_DEACTIVATE_REACTIVATE) &&
1504
0
      freerdp_settings_get_bool(rdp->settings, FreeRDP_BitmapCachePersistEnabled))
1505
0
  {
1506
0
    if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_PERSISTENT_KEY_LIST))
1507
0
      return STATE_RUN_FAILED;
1508
0
    if (!rdp_send_client_persistent_key_list_pdu(rdp))
1509
0
      return STATE_RUN_FAILED;
1510
0
  }
1511
1512
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_FONT_LIST))
1513
0
    return STATE_RUN_FAILED;
1514
0
  if (!rdp_send_client_font_list_pdu(rdp, FONTLIST_FIRST | FONTLIST_LAST))
1515
0
    return STATE_RUN_FAILED;
1516
1517
0
  if (!rdp_client_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_CLIENT_SYNC))
1518
0
    return STATE_RUN_FAILED;
1519
0
  return STATE_RUN_SUCCESS;
1520
0
}
1521
1522
BOOL rdp_client_transition_to_state(rdpRdp* rdp, CONNECTION_STATE state)
1523
15.8k
{
1524
15.8k
  const char* name = rdp_state_string(state);
1525
1526
15.8k
  WINPR_ASSERT(rdp);
1527
15.8k
  WLog_Print(rdp->log, WLOG_DEBUG, "%s --> %s", rdp_get_state_string(rdp), name);
1528
1529
15.8k
  if (!rdp_set_state(rdp, state))
1530
0
    return FALSE;
1531
1532
15.8k
  switch (state)
1533
15.8k
  {
1534
0
    case CONNECTION_STATE_FINALIZATION_SYNC:
1535
0
    case CONNECTION_STATE_FINALIZATION_COOPERATE:
1536
0
    case CONNECTION_STATE_FINALIZATION_REQUEST_CONTROL:
1537
0
    case CONNECTION_STATE_FINALIZATION_PERSISTENT_KEY_LIST:
1538
0
    case CONNECTION_STATE_FINALIZATION_FONT_LIST:
1539
0
      update_reset_state(rdp->update);
1540
0
      break;
1541
1542
0
    case CONNECTION_STATE_CAPABILITIES_EXCHANGE_CONFIRM_ACTIVE:
1543
0
    {
1544
0
      ActivatedEventArgs activatedEvent = WINPR_C_ARRAY_INIT;
1545
0
      rdpContext* context = rdp->context;
1546
0
      EventArgsInit(&activatedEvent, "libfreerdp");
1547
0
      activatedEvent.firstActivation =
1548
0
          !rdp_finalize_is_flag_set(rdp, FINALIZE_DEACTIVATE_REACTIVATE);
1549
0
      if (PubSub_OnActivated(rdp->pubSub, context, &activatedEvent) < 0)
1550
0
        return FALSE;
1551
0
    }
1552
1553
0
    break;
1554
1555
15.8k
    default:
1556
15.8k
      break;
1557
15.8k
  }
1558
1559
15.8k
  {
1560
15.8k
    ConnectionStateChangeEventArgs stateEvent = WINPR_C_ARRAY_INIT;
1561
15.8k
    rdpContext* context = rdp->context;
1562
15.8k
    EventArgsInit(&stateEvent, "libfreerdp");
1563
15.8k
    stateEvent.state = WINPR_ASSERTING_INT_CAST(int32_t, rdp_get_state(rdp));
1564
15.8k
    stateEvent.active = rdp_is_active_state(rdp);
1565
15.8k
    if (PubSub_OnConnectionStateChange(rdp->pubSub, context, &stateEvent) < 0)
1566
0
      return FALSE;
1567
15.8k
  }
1568
1569
15.8k
  return TRUE;
1570
15.8k
}
1571
1572
BOOL rdp_server_accept_nego(rdpRdp* rdp, wStream* s)
1573
0
{
1574
0
  UINT32 SelectedProtocol = 0;
1575
0
  UINT32 RequestedProtocols = 0;
1576
0
  BOOL status = 0;
1577
0
  rdpSettings* settings = nullptr;
1578
0
  rdpNego* nego = nullptr;
1579
1580
0
  WINPR_ASSERT(rdp);
1581
0
  WINPR_ASSERT(s);
1582
1583
0
  settings = rdp->settings;
1584
0
  WINPR_ASSERT(settings);
1585
1586
0
  nego = rdp->nego;
1587
0
  WINPR_ASSERT(nego);
1588
1589
0
  if (!transport_set_blocking_mode(rdp->transport, TRUE))
1590
0
    return FALSE;
1591
1592
0
  if (!nego_read_request(nego, s))
1593
0
    return FALSE;
1594
1595
0
  RequestedProtocols = nego_get_requested_protocols(nego);
1596
0
  WLog_DBG(TAG, "Client Security: RDSTLS:%d NLA:%d EXT:%d TLS:%d RDP:%d",
1597
0
           (RequestedProtocols & PROTOCOL_RDSTLS) ? 1 : 0,
1598
0
           (RequestedProtocols & PROTOCOL_HYBRID) ? 1 : 0,
1599
0
           (RequestedProtocols & PROTOCOL_HYBRID_EX) ? 1 : 0,
1600
0
           (RequestedProtocols & PROTOCOL_SSL) ? 1 : 0,
1601
0
           (RequestedProtocols == PROTOCOL_RDP) ? 1 : 0);
1602
0
  WLog_DBG(TAG,
1603
0
           "Server Security: RDSTLS:%" PRId32 " NLA:%" PRId32 " EXT:%" PRId32 " TLS:%" PRId32
1604
0
           " RDP:%" PRId32 "",
1605
0
           settings->RdstlsSecurity, settings->NlaSecurity, settings->ExtSecurity,
1606
0
           settings->TlsSecurity, settings->RdpSecurity);
1607
1608
0
  if ((settings->RdstlsSecurity) && (RequestedProtocols & PROTOCOL_RDSTLS))
1609
0
  {
1610
0
    SelectedProtocol = PROTOCOL_RDSTLS;
1611
0
  }
1612
0
  else if ((settings->ExtSecurity) && (RequestedProtocols & PROTOCOL_HYBRID_EX))
1613
0
  {
1614
0
    SelectedProtocol = PROTOCOL_HYBRID_EX;
1615
0
  }
1616
0
  else if ((settings->NlaSecurity) && (RequestedProtocols & PROTOCOL_HYBRID))
1617
0
  {
1618
0
    SelectedProtocol = PROTOCOL_HYBRID;
1619
0
  }
1620
0
  else if ((settings->TlsSecurity) && (RequestedProtocols & PROTOCOL_SSL))
1621
0
  {
1622
0
    SelectedProtocol = PROTOCOL_SSL;
1623
0
  }
1624
0
  else if ((settings->RdpSecurity) && (RequestedProtocols == PROTOCOL_RDP))
1625
0
  {
1626
0
    SelectedProtocol = PROTOCOL_RDP;
1627
0
  }
1628
0
  else
1629
0
  {
1630
    /*
1631
     * when here client and server aren't compatible, we select the right
1632
     * error message to return to the client in the nego failure packet
1633
     */
1634
0
    SelectedProtocol = PROTOCOL_FAILED_NEGO;
1635
1636
0
    if (settings->RdpSecurity)
1637
0
    {
1638
0
      WLog_ERR(TAG, "server supports only Standard RDP Security");
1639
0
      SelectedProtocol |= SSL_NOT_ALLOWED_BY_SERVER;
1640
0
    }
1641
0
    else
1642
0
    {
1643
0
      if ((settings->ExtSecurity || settings->NlaSecurity) && !settings->TlsSecurity)
1644
0
      {
1645
0
        WLog_WARN(TAG, "server supports only NLA Security");
1646
0
        SelectedProtocol |= HYBRID_REQUIRED_BY_SERVER;
1647
0
      }
1648
0
      else
1649
0
      {
1650
0
        WLog_WARN(TAG, "server supports only a SSL based Security (TLS or NLA)");
1651
0
        SelectedProtocol |= SSL_REQUIRED_BY_SERVER;
1652
0
      }
1653
0
    }
1654
1655
0
    WLog_ERR(TAG, "Protocol security negotiation failure");
1656
0
  }
1657
1658
0
  if (!(SelectedProtocol & PROTOCOL_FAILED_NEGO))
1659
0
  {
1660
0
    WLog_DBG(TAG, "Negotiated Security: RDSTLS:%d NLA:%d EXT:%d TLS:%d RDP:%d",
1661
0
             (SelectedProtocol & PROTOCOL_RDSTLS) ? 1 : 0,
1662
0
             (SelectedProtocol & PROTOCOL_HYBRID) ? 1 : 0,
1663
0
             (SelectedProtocol & PROTOCOL_HYBRID_EX) ? 1 : 0,
1664
0
             (SelectedProtocol & PROTOCOL_SSL) ? 1 : 0,
1665
0
             (SelectedProtocol == PROTOCOL_RDP) ? 1 : 0);
1666
0
  }
1667
1668
0
  if (!nego_set_selected_protocol(nego, SelectedProtocol))
1669
0
    return FALSE;
1670
1671
0
  if (!nego_send_negotiation_response(nego))
1672
0
    return FALSE;
1673
1674
0
  if ((SelectedProtocol & PROTOCOL_FAILED_NEGO) != 0)
1675
0
  {
1676
0
    WLog_ERR(TAG, "Protocol security negotiation failed, disconnecting.");
1677
0
    return FALSE;
1678
0
  }
1679
1680
0
  SelectedProtocol = nego_get_selected_protocol(nego);
1681
0
  status = FALSE;
1682
1683
0
  if (freerdp_settings_get_bool(rdp->settings, FreeRDP_VmConnectMode) &&
1684
0
      SelectedProtocol != PROTOCOL_RDP)
1685
    /* When behind a Hyper-V proxy, security != RDP is handled by the host. */
1686
0
    status = TRUE;
1687
0
  else if (SelectedProtocol & PROTOCOL_RDSTLS)
1688
0
    status = transport_accept_rdstls(rdp->transport);
1689
0
  else if (SelectedProtocol & PROTOCOL_HYBRID)
1690
0
    status = transport_accept_nla(rdp->transport, FALSE);
1691
0
  else if (SelectedProtocol & PROTOCOL_HYBRID_EX)
1692
0
    status = transport_accept_nla(rdp->transport, TRUE);
1693
0
  else if (SelectedProtocol & PROTOCOL_SSL)
1694
0
    status = transport_accept_tls(rdp->transport);
1695
0
  else if (SelectedProtocol == PROTOCOL_RDP) /* 0 */
1696
0
    status = transport_accept_rdp(rdp->transport);
1697
1698
0
  if (!status)
1699
0
    return FALSE;
1700
1701
0
  return transport_set_blocking_mode(rdp->transport, FALSE);
1702
0
}
1703
1704
static BOOL rdp_update_encryption_level(rdpSettings* settings)
1705
0
{
1706
0
  WINPR_ASSERT(settings);
1707
1708
0
  UINT32 EncryptionLevel = freerdp_settings_get_uint32(settings, FreeRDP_EncryptionLevel);
1709
0
  UINT32 EncryptionMethods = freerdp_settings_get_uint32(settings, FreeRDP_EncryptionMethods);
1710
1711
  /**
1712
   * Re: settings->EncryptionLevel:
1713
   * This is configured/set by the server implementation and serves the same
1714
   * purpose as the "Encryption Level" setting in the RDP-Tcp configuration
1715
   * dialog of Microsoft's Remote Desktop Session Host Configuration.
1716
   * Re: settings->EncryptionMethods:
1717
   * at this point this setting contains the client's supported encryption
1718
   * methods we've received in gcc_read_client_security_data()
1719
   */
1720
1721
0
  if (!settings->UseRdpSecurityLayer)
1722
0
  {
1723
    /* TLS/NLA is used: disable rdp style encryption */
1724
0
    EncryptionLevel = ENCRYPTION_LEVEL_NONE;
1725
0
  }
1726
0
  else
1727
0
  {
1728
    /* verify server encryption level value */
1729
0
    switch (EncryptionLevel)
1730
0
    {
1731
0
      case ENCRYPTION_LEVEL_NONE:
1732
0
        WLog_INFO(TAG, "Active rdp encryption level: NONE");
1733
0
        break;
1734
1735
0
      case ENCRYPTION_LEVEL_FIPS:
1736
0
        WLog_INFO(TAG, "Active rdp encryption level: FIPS Compliant");
1737
0
        break;
1738
1739
0
      case ENCRYPTION_LEVEL_HIGH:
1740
0
        WLog_INFO(TAG, "Active rdp encryption level: HIGH");
1741
0
        break;
1742
1743
0
      case ENCRYPTION_LEVEL_LOW:
1744
0
        WLog_INFO(TAG, "Active rdp encryption level: LOW");
1745
0
        break;
1746
1747
0
      case ENCRYPTION_LEVEL_CLIENT_COMPATIBLE:
1748
0
        WLog_INFO(TAG, "Active rdp encryption level: CLIENT-COMPATIBLE");
1749
0
        break;
1750
1751
0
      default:
1752
0
        WLog_ERR(TAG, "Invalid server encryption level 0x%08" PRIX32 "", EncryptionLevel);
1753
0
        WLog_ERR(TAG, "Switching to encryption level CLIENT-COMPATIBLE");
1754
0
        EncryptionLevel = ENCRYPTION_LEVEL_CLIENT_COMPATIBLE;
1755
0
    }
1756
0
  }
1757
1758
  /* choose rdp encryption method based on server level and client methods */
1759
0
  switch (EncryptionLevel)
1760
0
  {
1761
0
    case ENCRYPTION_LEVEL_NONE:
1762
      /* The only valid method is NONE in this case */
1763
0
      EncryptionMethods = ENCRYPTION_METHOD_NONE;
1764
0
      break;
1765
1766
0
    case ENCRYPTION_LEVEL_FIPS:
1767
1768
      /* The only valid method is FIPS in this case */
1769
0
      if (!(EncryptionMethods & ENCRYPTION_METHOD_FIPS))
1770
0
      {
1771
0
        WLog_WARN(TAG, "client does not support FIPS as required by server configuration");
1772
0
      }
1773
1774
0
      EncryptionMethods = ENCRYPTION_METHOD_FIPS;
1775
0
      break;
1776
1777
0
    case ENCRYPTION_LEVEL_HIGH:
1778
1779
      /* Maximum key strength supported by the server must be used (128 bit)*/
1780
0
      if (!(EncryptionMethods & ENCRYPTION_METHOD_128BIT))
1781
0
      {
1782
0
        WLog_WARN(TAG, "client does not support 128 bit encryption method as required by "
1783
0
                       "server configuration");
1784
0
      }
1785
1786
0
      EncryptionMethods = ENCRYPTION_METHOD_128BIT;
1787
0
      break;
1788
1789
0
    case ENCRYPTION_LEVEL_LOW:
1790
0
    case ENCRYPTION_LEVEL_CLIENT_COMPATIBLE:
1791
1792
      /* Maximum key strength supported by the client must be used */
1793
0
      if (EncryptionMethods & ENCRYPTION_METHOD_128BIT)
1794
0
        EncryptionMethods = ENCRYPTION_METHOD_128BIT;
1795
0
      else if (EncryptionMethods & ENCRYPTION_METHOD_56BIT)
1796
0
        EncryptionMethods = ENCRYPTION_METHOD_56BIT;
1797
0
      else if (EncryptionMethods & ENCRYPTION_METHOD_40BIT)
1798
0
        EncryptionMethods = ENCRYPTION_METHOD_40BIT;
1799
0
      else if (EncryptionMethods & ENCRYPTION_METHOD_FIPS)
1800
0
        EncryptionMethods = ENCRYPTION_METHOD_FIPS;
1801
0
      else
1802
0
      {
1803
0
        WLog_WARN(TAG, "client has not announced any supported encryption methods");
1804
0
        EncryptionMethods = ENCRYPTION_METHOD_128BIT;
1805
0
      }
1806
1807
0
      break;
1808
1809
0
    default:
1810
0
      WLog_ERR(TAG, "internal error: unknown encryption level");
1811
0
      return FALSE;
1812
0
  }
1813
1814
  /* log selected encryption method */
1815
0
  if (settings->UseRdpSecurityLayer)
1816
0
  {
1817
0
    switch (EncryptionMethods)
1818
0
    {
1819
0
      case ENCRYPTION_METHOD_NONE:
1820
0
        WLog_INFO(TAG, "Selected rdp encryption method: NONE");
1821
0
        break;
1822
1823
0
      case ENCRYPTION_METHOD_40BIT:
1824
0
        WLog_INFO(TAG, "Selected rdp encryption method: 40BIT");
1825
0
        break;
1826
1827
0
      case ENCRYPTION_METHOD_56BIT:
1828
0
        WLog_INFO(TAG, "Selected rdp encryption method: 56BIT");
1829
0
        break;
1830
1831
0
      case ENCRYPTION_METHOD_128BIT:
1832
0
        WLog_INFO(TAG, "Selected rdp encryption method: 128BIT");
1833
0
        break;
1834
1835
0
      case ENCRYPTION_METHOD_FIPS:
1836
0
        WLog_INFO(TAG, "Selected rdp encryption method: FIPS");
1837
0
        break;
1838
1839
0
      default:
1840
0
        WLog_ERR(TAG, "internal error: unknown encryption method");
1841
0
        return FALSE;
1842
0
    }
1843
0
  }
1844
1845
0
  if (!freerdp_settings_set_uint32(settings, FreeRDP_EncryptionLevel, EncryptionLevel))
1846
0
    return FALSE;
1847
0
  if (!freerdp_settings_set_uint32(settings, FreeRDP_EncryptionMethods, EncryptionMethods))
1848
0
    return FALSE;
1849
0
  return TRUE;
1850
0
}
1851
1852
BOOL rdp_server_accept_mcs_connect_initial(rdpRdp* rdp, wStream* s)
1853
0
{
1854
0
  WINPR_ASSERT(rdp);
1855
0
  WINPR_ASSERT(s);
1856
1857
0
  rdpMcs* mcs = rdp->mcs;
1858
0
  WINPR_ASSERT(mcs);
1859
1860
0
  WINPR_ASSERT(rdp_is_reached_state(rdp, CONNECTION_STATE_MCS_CREATE_REQUEST));
1861
0
  if (!mcs_recv_connect_initial(mcs, s))
1862
0
    return FALSE;
1863
0
  WINPR_ASSERT(rdp->settings);
1864
1865
0
  if (!mcs_server_apply_to_settings(mcs, rdp->settings))
1866
0
    return FALSE;
1867
1868
0
  WLog_DBG(TAG, "Accepted client: %s", rdp->settings->ClientHostname);
1869
0
  WLog_DBG(TAG, "Accepted channels:");
1870
1871
0
  WINPR_ASSERT(mcs->channels || (mcs->channelCount == 0));
1872
0
  for (UINT32 i = 0; i < mcs->channelCount; i++)
1873
0
  {
1874
0
    ADDIN_ARGV* arg = nullptr;
1875
0
    rdpMcsChannel* cur = &mcs->channels[i];
1876
0
    const char* params[1] = { cur->Name };
1877
0
    WLog_DBG(TAG, " %s [%" PRIu16 "]", cur->Name, cur->ChannelId);
1878
0
    arg = freerdp_addin_argv_new(ARRAYSIZE(params), params);
1879
0
    if (!arg)
1880
0
      return FALSE;
1881
1882
0
    if (!freerdp_static_channel_collection_add(rdp->settings, arg))
1883
0
    {
1884
0
      freerdp_addin_argv_free(arg);
1885
0
      return FALSE;
1886
0
    }
1887
0
  }
1888
1889
0
  if (!rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_CREATE_RESPONSE))
1890
0
    return FALSE;
1891
0
  if (!rdp_update_encryption_level(rdp->settings))
1892
0
    return FALSE;
1893
0
  if (!mcs_send_connect_response(mcs))
1894
0
    return FALSE;
1895
0
  if (!rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_ERECT_DOMAIN))
1896
0
    return FALSE;
1897
1898
0
  return TRUE;
1899
0
}
1900
1901
BOOL rdp_server_accept_mcs_erect_domain_request(rdpRdp* rdp, wStream* s)
1902
0
{
1903
0
  WINPR_ASSERT(rdp);
1904
0
  WINPR_ASSERT(s);
1905
0
  WINPR_ASSERT(rdp_is_reached_state(rdp, CONNECTION_STATE_MCS_ERECT_DOMAIN));
1906
1907
0
  if (!mcs_recv_erect_domain_request(rdp->mcs, s))
1908
0
    return FALSE;
1909
1910
0
  return rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_ATTACH_USER);
1911
0
}
1912
1913
static BOOL rdp_server_skip_mcs_channel_join(rdpRdp* rdp)
1914
0
{
1915
0
  WINPR_ASSERT(rdp);
1916
1917
0
  rdpMcs* mcs = rdp->mcs;
1918
0
  WINPR_ASSERT(mcs);
1919
1920
0
  mcs->userChannelJoined = TRUE;
1921
0
  mcs->globalChannelJoined = TRUE;
1922
0
  mcs->messageChannelJoined = TRUE;
1923
1924
0
  for (UINT32 i = 0; i < mcs->channelCount; i++)
1925
0
  {
1926
0
    rdpMcsChannel* cur = &mcs->channels[i];
1927
0
    WLog_DBG(TAG, " %s [%" PRIu16 "]", cur->Name, cur->ChannelId);
1928
0
    cur->joined = TRUE;
1929
0
  }
1930
0
  return rdp_server_transition_to_state(rdp, CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT);
1931
0
}
1932
1933
BOOL rdp_server_accept_mcs_attach_user_request(rdpRdp* rdp, wStream* s)
1934
0
{
1935
0
  if (!mcs_recv_attach_user_request(rdp->mcs, s))
1936
0
    return FALSE;
1937
1938
0
  if (!rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_ATTACH_USER_CONFIRM))
1939
0
    return FALSE;
1940
1941
0
  if (!mcs_send_attach_user_confirm(rdp->mcs))
1942
0
    return FALSE;
1943
1944
0
  if (freerdp_settings_get_bool(rdp->settings, FreeRDP_SupportSkipChannelJoin))
1945
0
    return rdp_server_skip_mcs_channel_join(rdp);
1946
0
  return rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN_REQUEST);
1947
0
}
1948
1949
BOOL rdp_server_accept_mcs_channel_join_request(rdpRdp* rdp, wStream* s)
1950
0
{
1951
0
  UINT16 channelId = 0;
1952
0
  BOOL allJoined = TRUE;
1953
0
  rdpMcs* mcs = nullptr;
1954
1955
0
  WINPR_ASSERT(rdp);
1956
0
  WINPR_ASSERT(rdp->context);
1957
1958
0
  mcs = rdp->mcs;
1959
0
  WINPR_ASSERT(mcs);
1960
1961
0
  WINPR_ASSERT(rdp_is_reached_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN_REQUEST));
1962
1963
0
  if (!mcs_recv_channel_join_request(mcs, rdp->settings, s, &channelId))
1964
0
    return FALSE;
1965
1966
0
  if (!rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_CHANNEL_JOIN_RESPONSE))
1967
0
    return FALSE;
1968
1969
0
  if (!mcs_send_channel_join_confirm(mcs, channelId))
1970
0
    return FALSE;
1971
1972
0
  if (channelId == mcs->userId)
1973
0
    mcs->userChannelJoined = TRUE;
1974
0
  if (channelId == MCS_GLOBAL_CHANNEL_ID)
1975
0
    mcs->globalChannelJoined = TRUE;
1976
0
  if (channelId == mcs->messageChannelId)
1977
0
    mcs->messageChannelJoined = TRUE;
1978
1979
0
  for (UINT32 i = 0; i < mcs->channelCount; i++)
1980
0
  {
1981
0
    rdpMcsChannel* cur = &mcs->channels[i];
1982
0
    WLog_DBG(TAG, " %s [%" PRIu16 "]", cur->Name, cur->ChannelId);
1983
0
    if (cur->ChannelId == channelId)
1984
0
      cur->joined = TRUE;
1985
1986
0
    if (!cur->joined)
1987
0
      allJoined = FALSE;
1988
0
  }
1989
1990
0
  CONNECTION_STATE rc = CONNECTION_STATE_INITIAL;
1991
0
  if ((mcs->userChannelJoined) && (mcs->globalChannelJoined) &&
1992
0
      (mcs->messageChannelId == 0 || mcs->messageChannelJoined) && allJoined)
1993
0
    rc = CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT;
1994
0
  else
1995
0
    rc = CONNECTION_STATE_MCS_CHANNEL_JOIN_REQUEST;
1996
1997
0
  return rdp_server_transition_to_state(rdp, rc);
1998
0
}
1999
2000
static BOOL rdp_server_send_sync(rdpRdp* rdp)
2001
0
{
2002
0
  WINPR_ASSERT(rdp);
2003
2004
0
  if (!rdp_server_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_CLIENT_SYNC))
2005
0
    return FALSE;
2006
0
  if (!rdp_send_server_synchronize_pdu(rdp))
2007
0
    return FALSE;
2008
0
  if (!rdp_server_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_CLIENT_COOPERATE))
2009
0
    return FALSE;
2010
0
  if (!rdp_send_server_control_cooperate_pdu(rdp))
2011
0
    return FALSE;
2012
0
  if (!rdp_finalize_reset_flags(rdp, FALSE))
2013
0
    return FALSE;
2014
0
  return rdp_server_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION_SYNC);
2015
0
}
2016
2017
BOOL rdp_server_accept_confirm_active(rdpRdp* rdp, wStream* s, UINT16 pduLength)
2018
0
{
2019
0
  WINPR_ASSERT(rdp);
2020
0
  WINPR_ASSERT(rdp->context);
2021
0
  WINPR_ASSERT(rdp->settings);
2022
0
  WINPR_ASSERT(s);
2023
2024
0
  freerdp_peer* peer = rdp->context->peer;
2025
0
  WINPR_ASSERT(peer);
2026
2027
0
  if (rdp_get_state(rdp) != CONNECTION_STATE_CAPABILITIES_EXCHANGE_CONFIRM_ACTIVE)
2028
0
  {
2029
0
    if (freerdp_settings_get_bool(rdp->settings, FreeRDP_TransportDumpReplay))
2030
0
      rdp_finalize_set_flag(rdp, FINALIZE_DEACTIVATE_REACTIVATE);
2031
0
    else
2032
0
    {
2033
0
      WLog_WARN(TAG, "Invalid state, got %s, expected %s", rdp_get_state_string(rdp),
2034
0
                rdp_state_string(CONNECTION_STATE_CAPABILITIES_EXCHANGE_CONFIRM_ACTIVE));
2035
0
      return FALSE;
2036
0
    }
2037
0
  }
2038
2039
0
  if (!rdp_recv_confirm_active(rdp, s, pduLength))
2040
0
    return FALSE;
2041
2042
0
  if (peer->ClientCapabilities && !peer->ClientCapabilities(peer))
2043
0
  {
2044
0
    WLog_WARN(TAG, "peer->ClientCapabilities failed");
2045
0
    return FALSE;
2046
0
  }
2047
2048
0
  if (rdp->settings->SaltedChecksum)
2049
0
    rdp->do_secure_checksum = TRUE;
2050
2051
0
  return rdp_server_send_sync(rdp);
2052
0
}
2053
2054
BOOL rdp_server_reactivate(rdpRdp* rdp)
2055
0
{
2056
0
  freerdp_peer* client = nullptr;
2057
2058
0
  if (rdp->context && rdp->context->peer)
2059
0
    client = rdp->context->peer;
2060
2061
0
  if (client)
2062
0
    client->activated = FALSE;
2063
2064
0
  if (!rdp_send_deactivate_all(rdp))
2065
0
    return FALSE;
2066
2067
0
  rdp_finalize_set_flag(rdp, FINALIZE_DEACTIVATE_REACTIVATE);
2068
0
  if (!rdp_server_transition_to_state(rdp, CONNECTION_STATE_CAPABILITIES_EXCHANGE_DEMAND_ACTIVE))
2069
0
    return FALSE;
2070
2071
0
  state_run_t rc = rdp_peer_handle_state_demand_active(client);
2072
0
  return state_run_success(rc);
2073
0
}
2074
2075
static BOOL rdp_is_active_peer_state(CONNECTION_STATE state)
2076
121k
{
2077
  /* [MS-RDPBCGR] 1.3.1.1 Connection Sequence states:
2078
   * 'upon receipt of the Font List PDU the server can start sending graphics
2079
   *  output to the client'
2080
   */
2081
121k
  switch (state)
2082
121k
  {
2083
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_SYNC:
2084
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_COOPERATE:
2085
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_GRANTED_CONTROL:
2086
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_FONT_MAP:
2087
0
    case CONNECTION_STATE_ACTIVE:
2088
0
      return TRUE;
2089
121k
    default:
2090
121k
      return FALSE;
2091
121k
  }
2092
121k
}
2093
2094
static BOOL rdp_is_active_client_state(CONNECTION_STATE state)
2095
406k
{
2096
  /* [MS-RDPBCGR] 1.3.1.1 Connection Sequence states:
2097
   * 'Once the client has sent the Confirm Active PDU, it can start sending
2098
   *  mouse and keyboard input to the server'
2099
   */
2100
406k
  switch (state)
2101
406k
  {
2102
0
    case CONNECTION_STATE_FINALIZATION_SYNC:
2103
0
    case CONNECTION_STATE_FINALIZATION_COOPERATE:
2104
0
    case CONNECTION_STATE_FINALIZATION_REQUEST_CONTROL:
2105
0
    case CONNECTION_STATE_FINALIZATION_PERSISTENT_KEY_LIST:
2106
0
    case CONNECTION_STATE_FINALIZATION_FONT_LIST:
2107
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_SYNC:
2108
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_COOPERATE:
2109
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_GRANTED_CONTROL:
2110
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_FONT_MAP:
2111
0
    case CONNECTION_STATE_ACTIVE:
2112
0
      return TRUE;
2113
406k
    default:
2114
406k
      return FALSE;
2115
406k
  }
2116
406k
}
2117
2118
BOOL rdp_has_reached_state_impl(const rdpRdp* rdp, CONNECTION_STATE state, const char* file,
2119
                                size_t line, const char* fkt)
2120
66.8k
{
2121
66.8k
  WINPR_ASSERT(rdp);
2122
66.8k
  const CONNECTION_STATE cur = rdp_get_state(rdp);
2123
66.8k
  if (cur < state)
2124
21.8k
  {
2125
21.8k
    if (WLog_IsLevelActive(rdp->log, WLOG_WARN))
2126
21.8k
      WLog_PrintTextMessage(rdp->log, WLOG_WARN, line, file, fkt,
2127
21.8k
                            "State %s (or higher) requested, but %s found. Aborting.",
2128
21.8k
                            rdp_state_string(state), rdp_state_string(cur));
2129
21.8k
    return FALSE;
2130
21.8k
  }
2131
44.9k
  return TRUE;
2132
66.8k
}
2133
2134
BOOL rdp_is_reached_state_impl(const rdpRdp* rdp, CONNECTION_STATE state, const char* file,
2135
                               size_t line, const char* fkt)
2136
15.8k
{
2137
15.8k
  WINPR_ASSERT(rdp);
2138
15.8k
  const CONNECTION_STATE cur = rdp_get_state(rdp);
2139
15.8k
  if (cur != state)
2140
0
  {
2141
0
    if (WLog_IsLevelActive(rdp->log, WLOG_WARN))
2142
0
      WLog_PrintTextMessage(rdp->log, WLOG_WARN, line, file, fkt,
2143
0
                            "State %s requested, but %s found. Aborting.",
2144
0
                            rdp_state_string(state), rdp_state_string(cur));
2145
0
    return FALSE;
2146
0
  }
2147
15.8k
  return TRUE;
2148
15.8k
}
2149
2150
BOOL rdp_is_active_state(const rdpRdp* rdp)
2151
528k
{
2152
528k
  WINPR_ASSERT(rdp);
2153
528k
  WINPR_ASSERT(rdp->context);
2154
2155
528k
  const CONNECTION_STATE state = rdp_get_state(rdp);
2156
528k
  if (freerdp_settings_get_bool(rdp->context->settings, FreeRDP_ServerMode))
2157
121k
    return rdp_is_active_peer_state(state);
2158
406k
  else
2159
406k
    return rdp_is_active_client_state(state);
2160
528k
}
2161
2162
BOOL rdp_server_transition_to_state(rdpRdp* rdp, CONNECTION_STATE state)
2163
0
{
2164
0
  BOOL status = FALSE;
2165
0
  freerdp_peer* client = nullptr;
2166
0
  const CONNECTION_STATE cstate = rdp_get_state(rdp);
2167
2168
0
  if (cstate >= CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT)
2169
0
  {
2170
0
    WINPR_ASSERT(rdp->context);
2171
0
    client = rdp->context->peer;
2172
0
  }
2173
2174
0
  if (!rdp_is_active_peer_state(cstate))
2175
0
  {
2176
0
    if (client)
2177
0
      client->activated = FALSE;
2178
0
  }
2179
2180
0
  WLog_Print(rdp->log, WLOG_DEBUG, "%s --> %s", rdp_get_state_string(rdp),
2181
0
             rdp_state_string(state));
2182
0
  if (!rdp_set_state(rdp, state))
2183
0
    goto fail;
2184
2185
0
  status = TRUE;
2186
0
fail:
2187
0
  return status;
2188
0
}
2189
2190
const char* rdp_client_connection_state_string(UINT state)
2191
0
{
2192
0
  switch (state)
2193
0
  {
2194
0
    case CLIENT_STATE_INITIAL:
2195
0
      return "CLIENT_STATE_INITIAL";
2196
0
    case CLIENT_STATE_PRECONNECT_PASSED:
2197
0
      return "CLIENT_STATE_PRECONNECT_PASSED";
2198
0
    case CLIENT_STATE_POSTCONNECT_PASSED:
2199
0
      return "CLIENT_STATE_POSTCONNECT_PASSED";
2200
0
    default:
2201
0
      return "UNKNOWN";
2202
0
  }
2203
0
}
2204
2205
const char* rdp_state_string(CONNECTION_STATE state)
2206
99.4k
{
2207
99.4k
  switch (state)
2208
99.4k
  {
2209
56.4k
    case CONNECTION_STATE_INITIAL:
2210
56.4k
      return "CONNECTION_STATE_INITIAL";
2211
0
    case CONNECTION_STATE_NEGO:
2212
0
      return "CONNECTION_STATE_NEGO";
2213
0
    case CONNECTION_STATE_NLA:
2214
0
      return "CONNECTION_STATE_NLA";
2215
0
    case CONNECTION_STATE_AAD:
2216
0
      return "CONNECTION_STATE_AAD";
2217
0
    case CONNECTION_STATE_MCS_CREATE_REQUEST:
2218
0
      return "CONNECTION_STATE_MCS_CREATE_REQUEST";
2219
0
    case CONNECTION_STATE_MCS_CREATE_RESPONSE:
2220
0
      return "CONNECTION_STATE_MCS_CREATE_RESPONSE";
2221
0
    case CONNECTION_STATE_MCS_ERECT_DOMAIN:
2222
0
      return "CONNECTION_STATE_MCS_ERECT_DOMAIN";
2223
0
    case CONNECTION_STATE_MCS_ATTACH_USER:
2224
0
      return "CONNECTION_STATE_MCS_ATTACH_USER";
2225
0
    case CONNECTION_STATE_MCS_ATTACH_USER_CONFIRM:
2226
0
      return "CONNECTION_STATE_MCS_ATTACH_USER_CONFIRM";
2227
0
    case CONNECTION_STATE_MCS_CHANNEL_JOIN_REQUEST:
2228
0
      return "CONNECTION_STATE_MCS_CHANNEL_JOIN_REQUEST";
2229
0
    case CONNECTION_STATE_MCS_CHANNEL_JOIN_RESPONSE:
2230
0
      return "CONNECTION_STATE_MCS_CHANNEL_JOIN_RESPONSE";
2231
0
    case CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT:
2232
0
      return "CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT";
2233
2.64k
    case CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE:
2234
2.64k
      return "CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE";
2235
0
    case CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT_REQUEST:
2236
0
      return "CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT_REQUEST";
2237
0
    case CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT_RESPONSE:
2238
0
      return "CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT_RESPONSE";
2239
0
    case CONNECTION_STATE_LICENSING:
2240
0
      return "CONNECTION_STATE_LICENSING";
2241
0
    case CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING_REQUEST:
2242
0
      return "CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING_REQUEST";
2243
2.64k
    case CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING_RESPONSE:
2244
2.64k
      return "CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING_RESPONSE";
2245
15.8k
    case CONNECTION_STATE_CAPABILITIES_EXCHANGE_DEMAND_ACTIVE:
2246
15.8k
      return "CONNECTION_STATE_CAPABILITIES_EXCHANGE_DEMAND_ACTIVE";
2247
1
    case CONNECTION_STATE_CAPABILITIES_EXCHANGE_MONITOR_LAYOUT:
2248
1
      return "CONNECTION_STATE_CAPABILITIES_EXCHANGE_MONITOR_LAYOUT";
2249
0
    case CONNECTION_STATE_CAPABILITIES_EXCHANGE_CONFIRM_ACTIVE:
2250
0
      return "CONNECTION_STATE_CAPABILITIES_EXCHANGE_CONFIRM_ACTIVE";
2251
0
    case CONNECTION_STATE_FINALIZATION_SYNC:
2252
0
      return "CONNECTION_STATE_FINALIZATION_SYNC";
2253
0
    case CONNECTION_STATE_FINALIZATION_COOPERATE:
2254
0
      return "CONNECTION_STATE_FINALIZATION_COOPERATE";
2255
0
    case CONNECTION_STATE_FINALIZATION_REQUEST_CONTROL:
2256
0
      return "CONNECTION_STATE_FINALIZATION_REQUEST_CONTROL";
2257
0
    case CONNECTION_STATE_FINALIZATION_PERSISTENT_KEY_LIST:
2258
0
      return "CONNECTION_STATE_FINALIZATION_PERSISTENT_KEY_LIST";
2259
0
    case CONNECTION_STATE_FINALIZATION_FONT_LIST:
2260
0
      return "CONNECTION_STATE_FINALIZATION_FONT_LIST";
2261
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_SYNC:
2262
0
      return "CONNECTION_STATE_FINALIZATION_CLIENT_SYNC";
2263
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_COOPERATE:
2264
0
      return "CONNECTION_STATE_FINALIZATION_CLIENT_COOPERATE";
2265
0
    case CONNECTION_STATE_FINALIZATION_CLIENT_GRANTED_CONTROL:
2266
0
      return "CONNECTION_STATE_FINALIZATION_CLIENT_GRANTED_CONTROL";
2267
1
    case CONNECTION_STATE_FINALIZATION_CLIENT_FONT_MAP:
2268
1
      return "CONNECTION_STATE_FINALIZATION_CLIENT_FONT_MAP";
2269
21.8k
    case CONNECTION_STATE_ACTIVE:
2270
21.8k
      return "CONNECTION_STATE_ACTIVE";
2271
0
    default:
2272
0
      return "UNKNOWN";
2273
99.4k
  }
2274
99.4k
}
2275
2276
CONNECTION_STATE rdp_get_state(const rdpRdp* rdp)
2277
700k
{
2278
700k
  WINPR_ASSERT(rdp);
2279
700k
  return rdp->state;
2280
700k
}
2281
2282
BOOL rdp_set_state(rdpRdp* rdp, CONNECTION_STATE state)
2283
15.8k
{
2284
15.8k
  WINPR_ASSERT(rdp);
2285
2286
15.8k
  rdpContext* context = rdp->context;
2287
15.8k
  WINPR_ASSERT(context);
2288
2289
15.8k
  if (context->pubSub)
2290
8.65k
  {
2291
8.65k
    StateChangedEventArgs e = WINPR_C_ARRAY_INIT;
2292
8.65k
    EventArgsInit(&e, "freerdp");
2293
8.65k
    e.oldState = rdp->state;
2294
8.65k
    e.newState = state;
2295
2296
8.65k
    const int rc = PubSub_OnStateChanged(context->pubSub, context, &e);
2297
8.65k
    if (rc < 0)
2298
0
      WLog_WARN(TAG, "PubSub_OnStateChanged() failed");
2299
8.65k
  }
2300
15.8k
  rdp->state = state;
2301
15.8k
  return TRUE;
2302
15.8k
}
2303
2304
const char* rdp_get_state_string(const rdpRdp* rdp)
2305
37.2k
{
2306
37.2k
  CONNECTION_STATE state = rdp_get_state(rdp);
2307
37.2k
  return rdp_state_string(state);
2308
37.2k
}
2309
2310
BOOL rdp_channels_from_mcs(rdpSettings* settings, const rdpRdp* rdp)
2311
0
{
2312
0
  const rdpMcs* mcs = nullptr;
2313
2314
0
  WINPR_ASSERT(rdp);
2315
2316
0
  mcs = rdp->mcs;
2317
0
  WINPR_ASSERT(mcs);
2318
2319
0
  if (!freerdp_settings_set_pointer_len(settings, FreeRDP_ChannelDefArray, nullptr,
2320
0
                                        CHANNEL_MAX_COUNT))
2321
0
    return FALSE;
2322
2323
0
  for (UINT32 x = 0; x < mcs->channelCount; x++)
2324
0
  {
2325
0
    const rdpMcsChannel* mchannel = &mcs->channels[x];
2326
0
    CHANNEL_DEF cur = WINPR_C_ARRAY_INIT;
2327
2328
0
    memcpy(cur.name, mchannel->Name, sizeof(cur.name));
2329
0
    cur.options = mchannel->options;
2330
0
    if (!freerdp_settings_set_pointer_array(settings, FreeRDP_ChannelDefArray, x, &cur))
2331
0
      return FALSE;
2332
0
  }
2333
2334
0
  return freerdp_settings_set_uint32(settings, FreeRDP_ChannelCount, mcs->channelCount);
2335
0
}
2336
2337
/* Here we are in client state CONFIRM_ACTIVE.
2338
 *
2339
 * This means:
2340
 * 1. send the CONFIRM_ACTIVE PDU to the server
2341
 * 2. register callbacks, the server can now start sending stuff
2342
 */
2343
state_run_t rdp_client_connect_confirm_active(rdpRdp* rdp, WINPR_ATTR_UNUSED wStream* s)
2344
0
{
2345
0
  WINPR_ASSERT(rdp);
2346
0
  WINPR_ASSERT(rdp->settings);
2347
0
  WINPR_ASSERT(s);
2348
2349
0
  const UINT32 width = rdp->settings->DesktopWidth;
2350
0
  const UINT32 height = rdp->settings->DesktopHeight;
2351
2352
0
  if (!rdp_send_confirm_active(rdp))
2353
0
    return STATE_RUN_FAILED;
2354
2355
0
  if (!input_register_client_callbacks(rdp->input))
2356
0
  {
2357
0
    WLog_ERR(TAG, "error registering client callbacks");
2358
0
    return STATE_RUN_FAILED;
2359
0
  }
2360
2361
  /**
2362
   * The server may request a different desktop size during Deactivation-Reactivation sequence.
2363
   * In this case, the UI should be informed and do actual window resizing at this point.
2364
   */
2365
0
  const BOOL deactivate_reactivate =
2366
0
      rdp->was_deactivated && ((rdp->deactivated_width != rdp->settings->DesktopWidth) ||
2367
0
                               (rdp->deactivated_height != rdp->settings->DesktopHeight));
2368
0
  const BOOL resolution_change =
2369
0
      ((width != rdp->settings->DesktopWidth) || (height != rdp->settings->DesktopHeight));
2370
0
  if (deactivate_reactivate || resolution_change)
2371
0
  {
2372
0
    BOOL status = TRUE;
2373
0
    WLog_DBG(TAG, "new size %" PRIu32 "x%" PRIu32, rdp->settings->DesktopWidth,
2374
0
             rdp->settings->DesktopHeight);
2375
2376
0
    rdp_update_internal* up = update_cast(rdp->update);
2377
0
    up->stats.base[RDP_STATS_RESIZE]++;
2378
2379
    /* Keep the lock order of BeginPaint/EndPaint: update lock first, client locks second */
2380
0
    rdp_update_lock(rdp->update);
2381
0
    IFCALLRET(rdp->update->DesktopResize, status, rdp->update->context);
2382
0
    rdp_update_unlock(rdp->update);
2383
2384
0
    if (!status)
2385
0
    {
2386
0
      WLog_ERR(TAG, "client desktop resize callback failed");
2387
0
      return STATE_RUN_FAILED;
2388
0
    }
2389
2390
    /* The codecs for bitmap updates and surface bits were sized for the
2391
     * old desktop when connecting. The GFX codecs are reset by the GFX
2392
     * channel on ResetGraphics instead. */
2393
0
    rdpCodecs* codecs = rdp->context->codecs;
2394
0
    if (codecs)
2395
0
    {
2396
0
      const UINT32 flags = FREERDP_CODEC_INTERLEAVED | FREERDP_CODEC_PLANAR |
2397
0
                           FREERDP_CODEC_NSCODEC | FREERDP_CODEC_REMOTEFX;
2398
0
      if (!freerdp_client_codecs_reset(codecs, flags, rdp->settings->DesktopWidth,
2399
0
                                       rdp->settings->DesktopHeight))
2400
0
      {
2401
0
        WLog_ERR(TAG, "failed to reset codecs to the new desktop size");
2402
0
        return STATE_RUN_FAILED;
2403
0
      }
2404
0
    }
2405
0
  }
2406
2407
0
  WINPR_ASSERT(rdp->context);
2408
0
  if (freerdp_shall_disconnect_context(rdp->context))
2409
0
    return STATE_RUN_SUCCESS;
2410
2411
0
  if (!cache_resize(rdp->context))
2412
0
    return STATE_RUN_FAILED;
2413
2414
0
  state_run_t status = rdp_client_connect_finalize(rdp);
2415
0
  if (state_run_success(status) &&
2416
0
      freerdp_settings_get_bool(rdp->settings, FreeRDP_SupportMonitorLayoutPdu))
2417
0
  {
2418
0
    if (!rdp_client_transition_to_state(rdp,
2419
0
                                        CONNECTION_STATE_CAPABILITIES_EXCHANGE_MONITOR_LAYOUT))
2420
0
      status = STATE_RUN_FAILED;
2421
0
  }
2422
0
  if (!rdp_finalize_reset_flags(rdp, FALSE))
2423
0
    status = STATE_RUN_FAILED;
2424
0
  return status;
2425
0
}
2426
2427
BOOL rdp_handle_optional_rdp_decryption(rdpRdp* rdp, wStream* s, UINT16* length,
2428
                                        UINT16* pSecurityFlags)
2429
0
{
2430
0
  BOOL rc = FALSE;
2431
0
  WINPR_ASSERT(rdp);
2432
0
  WINPR_ASSERT(rdp->settings);
2433
2434
0
  UINT16 securityFlags = 0;
2435
0
  if (rdp->settings->UseRdpSecurityLayer)
2436
0
  {
2437
0
    if (!rdp_read_security_header(rdp, s, &securityFlags, length))
2438
0
      goto fail;
2439
2440
0
    if (securityFlags & SEC_ENCRYPT)
2441
0
    {
2442
0
      if (!rdp_decrypt(rdp, s, length, securityFlags))
2443
0
        goto fail;
2444
0
    }
2445
0
  }
2446
2447
0
  rc = TRUE;
2448
2449
0
fail:
2450
0
  if (pSecurityFlags)
2451
0
    *pSecurityFlags = securityFlags;
2452
0
  return rc;
2453
0
}