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  *
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *     http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  */
21 
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25 
26 #include "info.h"
27 #include "input.h"
28 #include "rdp.h"
29 
30 #include "connection.h"
31 #include "transport.h"
32 
33 #include <winpr/crt.h>
34 #include <winpr/crypto.h>
35 #include <winpr/ssl.h>
36 
37 #include <freerdp/log.h>
38 #include <freerdp/error.h>
39 #include <freerdp/listener.h>
40 #include <freerdp/cache/pointer.h>
41 
42 #define TAG FREERDP_TAG("core.connection")
43 
44 /**
45  *                                      Connection Sequence
46  *     client                                                                    server
47  *        |                                                                         |
48  *        |-----------------------X.224 Connection Request PDU--------------------->|
49  *        |<----------------------X.224 Connection Confirm PDU----------------------|
50  *        |-------MCS Connect-Initial PDU with GCC Conference Create Request------->|
51  *        |<-----MCS Connect-Response PDU with GCC Conference Create Response-------|
52  *        |------------------------MCS Erect Domain Request PDU-------------------->|
53  *        |------------------------MCS Attach User Request PDU--------------------->|
54  *        |<-----------------------MCS Attach User Confirm PDU----------------------|
55  *        |------------------------MCS Channel Join Request PDU-------------------->|
56  *        |<-----------------------MCS Channel Join Confirm PDU---------------------|
57  *        |----------------------------Security Exchange PDU----------------------->|
58  *        |-------------------------------Client Info PDU-------------------------->|
59  *        |<---------------------License Error PDU - Valid Client-------------------|
60  *        |<-----------------------------Demand Active PDU--------------------------|
61  *        |------------------------------Confirm Active PDU------------------------>|
62  *        |-------------------------------Synchronize PDU-------------------------->|
63  *        |---------------------------Control PDU - Cooperate---------------------->|
64  *        |------------------------Control PDU - Request Control------------------->|
65  *        |--------------------------Persistent Key List PDU(s)-------------------->|
66  *        |--------------------------------Font List PDU--------------------------->|
67  *        |<------------------------------Synchronize PDU---------------------------|
68  *        |<--------------------------Control PDU - Cooperate-----------------------|
69  *        |<-----------------------Control PDU - Granted Control--------------------|
70  *        |<-------------------------------Font Map PDU-----------------------------|
71  *
72  */
73 
74 /**
75  *
76  * Connection Sequence
77  *
78  * 1.	Connection Initiation: The client initiates the connection by sending the server a
79  * 	Class 0 X.224 Connection Request PDU (section 2.2.1.1). The server responds with a
80  * 	Class 0 X.224 Connection Confirm PDU (section 2.2.1.2). From this point, all subsequent
81  * 	data sent between client and server is wrapped in an X.224 Data Protocol Data Unit (PDU).
82  *
83  * 2.	Basic Settings Exchange: Basic settings are exchanged between the client and server by
84  * 	using the MCS Connect Initial PDU (section 2.2.1.3) and MCS Connect Response PDU
85  *(section 2.2.1.4). The Connect Initial PDU contains a Generic Conference Control (GCC) Conference
86  *Create Request, while the Connect Response PDU contains a GCC Conference Create Response. These
87  *two GCC packets contain concatenated blocks of settings data (such as core data, security data,
88  *and network data) which are read by client and server.
89  *
90  * 3.	Channel Connection: The client sends an MCS Erect Domain Request PDU (section 2.2.1.5),
91  * 	followed by an MCS Attach User Request PDU (section 2.2.1.6) to attach the primary user identity
92  * 	to the MCS domain. The server responds with an MCS Attach User Confirm PDU (section 2.2.1.7)
93  * 	containing the User Channel ID. The client then proceeds to join the user channel, the
94  * 	input/output (I/O) channel, and all of the static virtual channels (the I/O and static virtual
95  * 	channel IDs are obtained from the data embedded in the GCC packets) by using multiple MCS
96  *Channel Join Request PDUs (section 2.2.1.8). The server confirms each channel with an MCS Channel
97  *Join Confirm PDU (section 2.2.1.9). (The client only sends a Channel Join Request after it has
98  *received the Channel Join Confirm for the previously sent request.)
99  *
100  * 	From this point, all subsequent data sent from the client to the server is wrapped in an MCS
101  *Send Data Request PDU, while data sent from the server to the client is wrapped in an MCS Send
102  *Data Indication PDU. This is in addition to the data being wrapped by an X.224 Data PDU.
103  *
104  * 4.	RDP Security Commencement: If Standard RDP Security mechanisms (section 5.3) are being
105  *employed and encryption is in force (this is determined by examining the data embedded in the GCC
106  *Conference Create Response packet) then the client sends a Security Exchange PDU
107  *(section 2.2.1.10) containing an encrypted 32-byte random number to the server. This random number
108  *is encrypted with the public key of the server as described in section 5.3.4.1 (the server's
109  *public key, as well as a 32-byte server-generated random number, are both obtained from the data
110  *embedded in the GCC Conference Create Response packet). The client and server then utilize the two
111  *32-byte random numbers to generate session keys which are used to encrypt and validate the
112  *integrity of subsequent RDP traffic.
113  *
114  * 	From this point, all subsequent RDP traffic can be encrypted and a security header is included
115  *with the data if encryption is in force. (The Client Info PDU (section 2.2.1.11) and licensing
116  *PDUs ([MS-RDPELE] section 2.2.2) are an exception in that they always have a security header). The
117  *Security Header follows the X.224 and MCS Headers and indicates whether the attached data is
118  *encrypted. Even if encryption is in force, server-to-client traffic may not always be encrypted,
119  *while client-to-server traffic must always be encrypted (encryption of licensing PDUs is optional,
120  *however).
121  *
122  * 5.	Secure Settings Exchange: Secure client data (such as the username, password, and
123  *auto-reconnect cookie) is sent to the server by using the Client Info PDU (section 2.2.1.11).
124  *
125  * 6.	Optional Connect-Time Auto-Detection: During the optional connect-time auto-detect phase the
126  *goal is to determine characteristics of the network, such as the round-trip latency time and the
127  *bandwidth of the link between the server and client. This is accomplished by exchanging a
128  *collection of PDUs (specified in section 2.2.1.4) over a predetermined period of time with enough
129  *data to ensure that the results are statistically relevant.
130  *
131  * 7.	Licensing: The goal of the licensing exchange is to transfer a license from the server to
132  *the client. The client stores this license and on subsequent connections sends the license to the
133  *server for validation. However, in some situations the client may not be issued a license to
134  *store. In effect, the packets exchanged during this phase of the protocol depend on the licensing
135  *mechanisms employed by the server. Within the context of this document, it is assumed that the
136  *client will not be issued a license to store. For details regarding more advanced licensing
137  *scenarios that take place during the Licensing Phase, see [MS-RDPELE] section 1.3.
138  *
139  * 8.	Optional Multitransport Bootstrapping: After the connection has been secured and the
140  *Licensing Phase has run to completion, the server can choose to initiate multitransport
141  *connections ([MS-RDPEMT] section 1.3). The Initiate Multitransport Request PDU (section 2.2.15.1)
142  *is sent by the server to the client and results in the out-of-band creation of a multitransport
143  *connection using messages from the RDP-UDP, TLS, DTLS, and multitransport protocols ([MS-RDPEMT]
144  *section 1.3.1).
145  *
146  * 9.	Capabilities Exchange: The server sends the set of capabilities it supports to the client in
147  *a Demand Active PDU (section 2.2.1.13.1). The client responds with its capabilities by sending a
148  *Confirm Active PDU (section 2.2.1.13.2).
149  *
150  * 10.	Connection Finalization: The client and server exchange PDUs to finalize the connection
151  *details. The client-to-server PDUs sent during this phase have no dependencies on any of the
152  *server-to-client PDUs; they may be sent as a single batch, provided that sequencing is maintained.
153  *
154  * 	- The Client Synchronize PDU (section 2.2.1.14) is sent after transmitting the Confirm Active
155  *PDU.
156  * 	- The Client Control (Cooperate) PDU (section 2.2.1.15) is sent after transmitting the Client
157  *Synchronize PDU.
158  * 	- The Client Control (Request Control) PDU (section 2.2.1.16) is sent after transmitting the
159  *Client Control (Cooperate) PDU.
160  * 	- The optional Persistent Key List PDUs (section 2.2.1.17) are sent after transmitting the
161  *Client Control (Request Control) PDU.
162  * 	- The Font List PDU (section 2.2.1.18) is sent after transmitting the Persistent Key List PDUs
163  *or, if the Persistent Key List PDUs were not sent, it is sent after transmitting the Client
164  *Control (Request Control) PDU (section 2.2.1.16).
165  *
166  *	The server-to-client PDUs sent during the Connection Finalization Phase have dependencies on the
167  *client-to-server PDUs.
168  *
169  *	- The optional Monitor Layout PDU (section 2.2.12.1) has no dependency on any client-to-server
170  *PDUs and is sent after the Demand Active PDU.
171  *	- The Server Synchronize PDU (section 2.2.1.19) is sent in response to the Confirm Active PDU.
172  *	- The Server Control (Cooperate) PDU (section 2.2.1.20) is sent after transmitting the Server
173  *Synchronize PDU.
174  *	- The Server Control (Granted Control) PDU (section 2.2.1.21) is sent in response to the Client
175  *Control (Request Control) PDU.
176  *	- The Font Map PDU (section 2.2.1.22) is sent in response to the Font List PDU.
177  *
178  *	Once the client has sent the Confirm Active PDU, it can start sending mouse and keyboard input
179  *to the server, and upon receipt of the Font List PDU the server can start sending graphics output
180  *to the client.
181  *
182  *	Besides input and graphics data, other data that can be exchanged between client and server
183  *after the connection has been finalized includes connection management information and virtual
184  *channel messages (exchanged between client-side plug-ins and server-side applications).
185  */
186 
187 static int rdp_client_connect_finalize(rdpRdp* rdp);
188 static BOOL rdp_send_server_control_granted_pdu(rdpRdp* rdp);
189 
rdp_client_reset_codecs(rdpContext * context)190 static BOOL rdp_client_reset_codecs(rdpContext* context)
191 {
192 	rdpSettings* settings;
193 
194 	if (!context || !context->settings)
195 		return FALSE;
196 
197 	settings = context->settings;
198 	context->codecs = codecs_new(context);
199 
200 	if (!context->codecs)
201 		return FALSE;
202 
203 	if (!freerdp_client_codecs_prepare(context->codecs, FREERDP_CODEC_ALL, settings->DesktopWidth,
204 	                                   settings->DesktopHeight))
205 		return FALSE;
206 
207 /* Runtime H264 detection. (only available if dynamic backend loading is defined)
208  * If no backend is available disable it before the channel is loaded.
209  */
210 #if defined(WITH_GFX_H264) && defined(WITH_OPENH264_LOADING)
211 	if (!context->codecs->h264)
212 	{
213 		settings->GfxH264 = FALSE;
214 		settings->GfxAVC444 = FALSE;
215 		settings->GfxAVC444v2 = FALSE;
216 	}
217 #endif
218 	return TRUE;
219 }
220 
221 /**
222  * Establish RDP Connection based on the settings given in the 'rdp' parameter.
223  * @msdn{cc240452}
224  * @param rdp RDP module
225  * @return true if the connection succeeded. FALSE otherwise.
226  */
227 
rdp_client_connect(rdpRdp * rdp)228 BOOL rdp_client_connect(rdpRdp* rdp)
229 {
230 	UINT32 SelectedProtocol;
231 	BOOL status;
232 	rdpSettings* settings = rdp->settings;
233 	/* make sure SSL is initialize for earlier enough for crypto, by taking advantage of winpr SSL
234 	 * FIPS flag for openssl initialization */
235 	DWORD flags = WINPR_SSL_INIT_DEFAULT;
236 	UINT32 timeout;
237 
238 	if (!rdp_client_reset_codecs(rdp->context))
239 		return FALSE;
240 
241 	if (settings->FIPSMode)
242 		flags |= WINPR_SSL_INIT_ENABLE_FIPS;
243 
244 	winpr_InitializeSSL(flags);
245 
246 	/* FIPS Mode forces the following and overrides the following(by happening later */
247 	/* in the command line processing): */
248 	/* 1. Disables NLA Security since NLA in freerdp uses NTLM(no Kerberos support yet) which uses
249 	 * algorithms */
250 	/*      not allowed in FIPS for sensitive data. So, we disallow NLA when FIPS is required. */
251 	/* 2. Forces the only supported RDP encryption method to be FIPS. */
252 	if (settings->FIPSMode || winpr_FIPSMode())
253 	{
254 		settings->NlaSecurity = FALSE;
255 		settings->EncryptionMethods = ENCRYPTION_METHOD_FIPS;
256 	}
257 
258 	nego_init(rdp->nego);
259 	nego_set_target(rdp->nego, settings->ServerHostname, settings->ServerPort);
260 
261 	if (settings->GatewayEnabled)
262 	{
263 		char* user = NULL;
264 		char* domain = NULL;
265 		char* cookie = NULL;
266 		int user_length = 0;
267 		int domain_length = 0;
268 		int cookie_length = 0;
269 
270 		if (settings->Username)
271 		{
272 			user = settings->Username;
273 			user_length = strlen(settings->Username);
274 		}
275 
276 		if (settings->Domain)
277 			domain = settings->Domain;
278 		else
279 			domain = settings->ComputerName;
280 
281 		domain_length = strlen(domain);
282 		cookie_length = domain_length + 1 + user_length;
283 		cookie = (char*)malloc(cookie_length + 1);
284 
285 		if (!cookie)
286 			return FALSE;
287 
288 		CopyMemory(cookie, domain, domain_length);
289 		CharUpperBuffA(cookie, domain_length);
290 		cookie[domain_length] = '\\';
291 
292 		if (settings->Username)
293 			CopyMemory(&cookie[domain_length + 1], user, user_length);
294 
295 		cookie[cookie_length] = '\0';
296 		status = nego_set_cookie(rdp->nego, cookie);
297 		free(cookie);
298 	}
299 	else
300 	{
301 		status = nego_set_cookie(rdp->nego, settings->Username);
302 	}
303 
304 	if (!status)
305 		return FALSE;
306 
307 	nego_set_send_preconnection_pdu(rdp->nego, settings->SendPreconnectionPdu);
308 	nego_set_preconnection_id(rdp->nego, settings->PreconnectionId);
309 	nego_set_preconnection_blob(rdp->nego, settings->PreconnectionBlob);
310 	nego_set_negotiation_enabled(rdp->nego, settings->NegotiateSecurityLayer);
311 	nego_set_restricted_admin_mode_required(rdp->nego, settings->RestrictedAdminModeRequired);
312 	nego_set_gateway_enabled(rdp->nego, settings->GatewayEnabled);
313 	nego_set_gateway_bypass_local(rdp->nego, settings->GatewayBypassLocal);
314 	nego_enable_rdp(rdp->nego, settings->RdpSecurity);
315 	nego_enable_tls(rdp->nego, settings->TlsSecurity);
316 	nego_enable_nla(rdp->nego, settings->NlaSecurity);
317 	nego_enable_ext(rdp->nego, settings->ExtSecurity);
318 
319 	if (settings->MstscCookieMode)
320 		settings->CookieMaxLength = MSTSC_COOKIE_MAX_LENGTH;
321 
322 	nego_set_cookie_max_length(rdp->nego, settings->CookieMaxLength);
323 
324 	if (settings->LoadBalanceInfo && (settings->LoadBalanceInfoLength > 0))
325 	{
326 		if (!nego_set_routing_token(rdp->nego, settings->LoadBalanceInfo,
327 		                            settings->LoadBalanceInfoLength))
328 			return FALSE;
329 	}
330 
331 	rdp_client_transition_to_state(rdp, CONNECTION_STATE_NEGO);
332 
333 	if (!nego_connect(rdp->nego))
334 	{
335 		if (!freerdp_get_last_error(rdp->context))
336 		{
337 			freerdp_set_last_error_log(rdp->context, FREERDP_ERROR_SECURITY_NEGO_CONNECT_FAILED);
338 			WLog_ERR(TAG, "Error: protocol security negotiation or connection failure");
339 		}
340 
341 		return FALSE;
342 	}
343 
344 	SelectedProtocol = nego_get_selected_protocol(rdp->nego);
345 
346 	if ((SelectedProtocol & PROTOCOL_SSL) || (SelectedProtocol == PROTOCOL_RDP))
347 	{
348 		if ((settings->Username != NULL) &&
349 		    ((settings->Password != NULL) ||
350 		     (settings->RedirectionPassword != NULL && settings->RedirectionPasswordLength > 0)))
351 			settings->AutoLogonEnabled = TRUE;
352 	}
353 
354 	/* everything beyond this point is event-driven and non blocking */
355 	rdp->transport->ReceiveCallback = rdp_recv_callback;
356 	rdp->transport->ReceiveExtra = rdp;
357 	transport_set_blocking_mode(rdp->transport, FALSE);
358 
359 	if (rdp->state != CONNECTION_STATE_NLA)
360 	{
361 		if (!mcs_client_begin(rdp->mcs))
362 			return FALSE;
363 	}
364 
365 	for (timeout = 0; timeout < settings->TcpAckTimeout; timeout += 100)
366 	{
367 		if (rdp_check_fds(rdp) < 0)
368 		{
369 			freerdp_set_last_error_if_not(rdp->context, FREERDP_ERROR_CONNECT_TRANSPORT_FAILED);
370 			return FALSE;
371 		}
372 
373 		if (rdp->state == CONNECTION_STATE_ACTIVE)
374 			return TRUE;
375 
376 		Sleep(100);
377 	}
378 
379 	WLog_ERR(TAG, "Timeout waiting for activation");
380 	return FALSE;
381 }
382 
rdp_client_disconnect(rdpRdp * rdp)383 BOOL rdp_client_disconnect(rdpRdp* rdp)
384 {
385 	rdpContext* context;
386 
387 	if (!rdp || !rdp->settings || !rdp->context)
388 		return FALSE;
389 
390 	context = rdp->context;
391 
392 	if (!nego_disconnect(rdp->nego))
393 		return FALSE;
394 
395 	rdp_reset(rdp);
396 	rdp_client_transition_to_state(rdp, CONNECTION_STATE_INITIAL);
397 
398 	if (freerdp_channels_disconnect(context->channels, context->instance) != CHANNEL_RC_OK)
399 		return FALSE;
400 
401 	codecs_free(context->codecs);
402 	context->codecs = NULL;
403 	return TRUE;
404 }
405 
rdp_client_disconnect_and_clear(rdpRdp * rdp)406 BOOL rdp_client_disconnect_and_clear(rdpRdp* rdp)
407 {
408 	rdpContext* context;
409 
410 	if (!rdp_client_disconnect(rdp))
411 		return FALSE;
412 
413 	context = rdp->context;
414 	context->LastError = FREERDP_ERROR_SUCCESS;
415 	clearChannelError(context);
416 	ResetEvent(context->abortEvent);
417 	return TRUE;
418 }
419 
rdp_client_reconnect_channels(rdpRdp * rdp,BOOL redirect)420 static BOOL rdp_client_reconnect_channels(rdpRdp* rdp, BOOL redirect)
421 {
422 	BOOL status = FALSE;
423 	rdpContext* context;
424 
425 	if (!rdp || !rdp->context || !rdp->context->channels)
426 		return FALSE;
427 
428 	context = rdp->context;
429 
430 	if (context->instance->ConnectionCallbackState == CLIENT_STATE_INITIAL)
431 		return FALSE;
432 
433 	if (context->instance->ConnectionCallbackState == CLIENT_STATE_PRECONNECT_PASSED)
434 	{
435 		if (redirect)
436 			return TRUE;
437 
438 		pointer_cache_register_callbacks(context->update);
439 
440 		if (!IFCALLRESULT(FALSE, context->instance->PostConnect, context->instance))
441 			return FALSE;
442 
443 		context->instance->ConnectionCallbackState = CLIENT_STATE_POSTCONNECT_PASSED;
444 	}
445 
446 	if (context->instance->ConnectionCallbackState == CLIENT_STATE_POSTCONNECT_PASSED)
447 		status =
448 		    (freerdp_channels_post_connect(context->channels, context->instance) == CHANNEL_RC_OK);
449 
450 	return status;
451 }
452 
rdp_client_redirect_resolvable(const char * host)453 static BOOL rdp_client_redirect_resolvable(const char* host)
454 {
455 	struct addrinfo* result = freerdp_tcp_resolve_host(host, -1, 0);
456 
457 	if (!result)
458 		return FALSE;
459 
460 	freeaddrinfo(result);
461 	return TRUE;
462 }
463 
rdp_client_redirect_try_fqdn(rdpSettings * settings)464 static BOOL rdp_client_redirect_try_fqdn(rdpSettings* settings)
465 {
466 	if (settings->RedirectionFlags & LB_TARGET_FQDN)
467 	{
468 		if (settings->GatewayEnabled ||
469 		    rdp_client_redirect_resolvable(settings->RedirectionTargetFQDN))
470 		{
471 			free(settings->ServerHostname);
472 			settings->ServerHostname = _strdup(settings->RedirectionTargetFQDN);
473 
474 			if (!settings->ServerHostname)
475 				return FALSE;
476 
477 			return TRUE;
478 		}
479 	}
480 
481 	return FALSE;
482 }
483 
rdp_client_redirect_try_ip(rdpSettings * settings)484 static BOOL rdp_client_redirect_try_ip(rdpSettings* settings)
485 {
486 	if (settings->RedirectionFlags & LB_TARGET_NET_ADDRESS)
487 	{
488 		free(settings->ServerHostname);
489 		settings->ServerHostname = _strdup(settings->TargetNetAddress);
490 
491 		if (!settings->ServerHostname)
492 			return FALSE;
493 
494 		return TRUE;
495 	}
496 
497 	return FALSE;
498 }
499 
rdp_client_redirect_try_netbios(rdpSettings * settings)500 static BOOL rdp_client_redirect_try_netbios(rdpSettings* settings)
501 {
502 	if (settings->RedirectionFlags & LB_TARGET_NETBIOS_NAME)
503 	{
504 		if (settings->GatewayEnabled ||
505 		    rdp_client_redirect_resolvable(settings->RedirectionTargetNetBiosName))
506 		{
507 			free(settings->ServerHostname);
508 			settings->ServerHostname = _strdup(settings->RedirectionTargetNetBiosName);
509 
510 			if (!settings->ServerHostname)
511 				return FALSE;
512 
513 			return TRUE;
514 		}
515 	}
516 
517 	return FALSE;
518 }
519 
rdp_client_redirect(rdpRdp * rdp)520 BOOL rdp_client_redirect(rdpRdp* rdp)
521 {
522 	BOOL status;
523 	rdpSettings* settings;
524 
525 	if (!rdp || !rdp->settings)
526 		return FALSE;
527 
528 	settings = rdp->settings;
529 
530 	if (!rdp_client_disconnect_and_clear(rdp))
531 		return FALSE;
532 
533 	if (rdp_redirection_apply_settings(rdp) != 0)
534 		return FALSE;
535 
536 	if (settings->RedirectionFlags & LB_LOAD_BALANCE_INFO)
537 	{
538 		if (settings->LoadBalanceInfo && (settings->LoadBalanceInfoLength > 0))
539 		{
540 			if (!nego_set_routing_token(rdp->nego, settings->LoadBalanceInfo,
541 			                            settings->LoadBalanceInfoLength))
542 				return FALSE;
543 		}
544 	}
545 	else
546 	{
547 		BOOL haveRedirectAddress = FALSE;
548 		UINT32 redirectionMask = settings->RedirectionPreferType;
549 
550 		do
551 		{
552 			const BOOL tryFQDN = (redirectionMask & 0x01) == 0;
553 			const BOOL tryNetAddress = (redirectionMask & 0x02) == 0;
554 			const BOOL tryNetbios = (redirectionMask & 0x04) == 0;
555 
556 			if (tryFQDN && !haveRedirectAddress)
557 				haveRedirectAddress = rdp_client_redirect_try_fqdn(settings);
558 
559 			if (tryNetAddress && !haveRedirectAddress)
560 				haveRedirectAddress = rdp_client_redirect_try_ip(settings);
561 
562 			if (tryNetbios && !haveRedirectAddress)
563 				haveRedirectAddress = rdp_client_redirect_try_netbios(settings);
564 
565 			redirectionMask >>= 3;
566 		} while (!haveRedirectAddress && (redirectionMask != 0));
567 	}
568 
569 	if (settings->RedirectionFlags & LB_USERNAME)
570 	{
571 		free(settings->Username);
572 		settings->Username = _strdup(settings->RedirectionUsername);
573 
574 		if (!settings->Username)
575 			return FALSE;
576 	}
577 
578 	if (settings->RedirectionFlags & LB_DOMAIN)
579 	{
580 		free(settings->Domain);
581 		settings->Domain = _strdup(settings->RedirectionDomain);
582 
583 		if (!settings->Domain)
584 			return FALSE;
585 	}
586 
587 	status = rdp_client_connect(rdp);
588 
589 	if (status)
590 		status = rdp_client_reconnect_channels(rdp, TRUE);
591 
592 	return status;
593 }
594 
rdp_client_reconnect(rdpRdp * rdp)595 BOOL rdp_client_reconnect(rdpRdp* rdp)
596 {
597 	BOOL status;
598 
599 	if (!rdp || !rdp->context || !rdp->context->channels)
600 		return FALSE;
601 
602 	if (!rdp_client_disconnect_and_clear(rdp))
603 		return FALSE;
604 
605 	status = rdp_client_connect(rdp);
606 
607 	if (status)
608 		status = rdp_client_reconnect_channels(rdp, FALSE);
609 
610 	return status;
611 }
612 
613 static const BYTE fips_ivec[8] = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
614 
rdp_client_establish_keys(rdpRdp * rdp)615 static BOOL rdp_client_establish_keys(rdpRdp* rdp)
616 {
617 	BYTE* mod;
618 	BYTE* exp;
619 	wStream* s;
620 	UINT32 length;
621 	UINT32 key_len;
622 	int status = 0;
623 	BOOL ret = FALSE;
624 	rdpSettings* settings;
625 	BYTE* crypt_client_random = NULL;
626 	settings = rdp->settings;
627 
628 	if (!settings->UseRdpSecurityLayer)
629 	{
630 		/* no RDP encryption */
631 		return TRUE;
632 	}
633 
634 	/* encrypt client random */
635 	free(settings->ClientRandom);
636 	settings->ClientRandomLength = CLIENT_RANDOM_LENGTH;
637 	settings->ClientRandom = malloc(settings->ClientRandomLength);
638 
639 	if (!settings->ClientRandom)
640 		return FALSE;
641 
642 	winpr_RAND(settings->ClientRandom, settings->ClientRandomLength);
643 	key_len = settings->RdpServerCertificate->cert_info.ModulusLength;
644 	mod = settings->RdpServerCertificate->cert_info.Modulus;
645 	exp = settings->RdpServerCertificate->cert_info.exponent;
646 	/*
647 	 * client random must be (bitlen / 8) + 8 - see [MS-RDPBCGR] 5.3.4.1
648 	 * for details
649 	 */
650 	crypt_client_random = calloc(key_len + 8, 1);
651 
652 	if (!crypt_client_random)
653 		return FALSE;
654 
655 	crypto_rsa_public_encrypt(settings->ClientRandom, settings->ClientRandomLength, key_len, mod,
656 	                          exp, crypt_client_random);
657 	/* send crypt client random to server */
658 	length = RDP_PACKET_HEADER_MAX_LENGTH + RDP_SECURITY_HEADER_LENGTH + 4 + key_len + 8;
659 	s = Stream_New(NULL, length);
660 
661 	if (!s)
662 	{
663 		WLog_ERR(TAG, "Stream_New failed!");
664 		goto end;
665 	}
666 
667 	rdp_write_header(rdp, s, length, MCS_GLOBAL_CHANNEL_ID);
668 	rdp_write_security_header(s, SEC_EXCHANGE_PKT | SEC_LICENSE_ENCRYPT_SC);
669 	length = key_len + 8;
670 	Stream_Write_UINT32(s, length);
671 	Stream_Write(s, crypt_client_random, length);
672 	Stream_SealLength(s);
673 	status = transport_write(rdp->mcs->transport, s);
674 	Stream_Free(s, TRUE);
675 
676 	if (status < 0)
677 		goto end;
678 
679 	rdp->do_crypt_license = TRUE;
680 
681 	/* now calculate encrypt / decrypt and update keys */
682 	if (!security_establish_keys(settings->ClientRandom, rdp))
683 		goto end;
684 
685 	rdp->do_crypt = TRUE;
686 
687 	if (settings->SaltedChecksum)
688 		rdp->do_secure_checksum = TRUE;
689 
690 	if (settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
691 	{
692 		rdp->fips_encrypt = winpr_Cipher_New(WINPR_CIPHER_DES_EDE3_CBC, WINPR_ENCRYPT,
693 		                                     rdp->fips_encrypt_key, fips_ivec);
694 
695 		if (!rdp->fips_encrypt)
696 		{
697 			WLog_ERR(TAG, "unable to allocate des3 encrypt key");
698 			goto end;
699 		}
700 
701 		rdp->fips_decrypt = winpr_Cipher_New(WINPR_CIPHER_DES_EDE3_CBC, WINPR_DECRYPT,
702 		                                     rdp->fips_decrypt_key, fips_ivec);
703 
704 		if (!rdp->fips_decrypt)
705 		{
706 			WLog_ERR(TAG, "unable to allocate des3 decrypt key");
707 			goto end;
708 		}
709 
710 		ret = TRUE;
711 		goto end;
712 	}
713 
714 	rdp->rc4_decrypt_key = winpr_RC4_New(rdp->decrypt_key, rdp->rc4_key_len);
715 	rdp->rc4_encrypt_key = winpr_RC4_New(rdp->encrypt_key, rdp->rc4_key_len);
716 
717 	if (!rdp->rc4_decrypt_key || !rdp->rc4_encrypt_key)
718 		goto end;
719 
720 	ret = TRUE;
721 end:
722 	free(crypt_client_random);
723 
724 	if (!ret)
725 	{
726 		winpr_Cipher_Free(rdp->fips_decrypt);
727 		winpr_Cipher_Free(rdp->fips_encrypt);
728 		winpr_RC4_Free(rdp->rc4_decrypt_key);
729 		winpr_RC4_Free(rdp->rc4_encrypt_key);
730 		rdp->fips_decrypt = NULL;
731 		rdp->fips_encrypt = NULL;
732 		rdp->rc4_decrypt_key = NULL;
733 		rdp->rc4_encrypt_key = NULL;
734 	}
735 
736 	return ret;
737 }
738 
rdp_server_establish_keys(rdpRdp * rdp,wStream * s)739 BOOL rdp_server_establish_keys(rdpRdp* rdp, wStream* s)
740 {
741 	BYTE* client_random = NULL;
742 	BYTE* crypt_client_random = NULL;
743 	UINT32 rand_len, key_len;
744 	UINT16 channel_id, length, sec_flags;
745 	BYTE* mod;
746 	BYTE* priv_exp;
747 	BOOL ret = FALSE;
748 
749 	if (!rdp->settings->UseRdpSecurityLayer)
750 	{
751 		/* No RDP Security. */
752 		return TRUE;
753 	}
754 
755 	if (!rdp_read_header(rdp, s, &length, &channel_id))
756 	{
757 		WLog_ERR(TAG, "invalid RDP header");
758 		return FALSE;
759 	}
760 
761 	if (!rdp_read_security_header(s, &sec_flags, NULL))
762 	{
763 		WLog_ERR(TAG, "invalid security header");
764 		return FALSE;
765 	}
766 
767 	if ((sec_flags & SEC_EXCHANGE_PKT) == 0)
768 	{
769 		WLog_ERR(TAG, "missing SEC_EXCHANGE_PKT in security header");
770 		return FALSE;
771 	}
772 
773 	rdp->do_crypt_license = (sec_flags & SEC_LICENSE_ENCRYPT_SC) != 0 ? TRUE : FALSE;
774 
775 	if (Stream_GetRemainingLength(s) < 4)
776 		return FALSE;
777 
778 	Stream_Read_UINT32(s, rand_len);
779 
780 	/* rand_len already includes 8 bytes of padding */
781 	if (Stream_GetRemainingLength(s) < rand_len)
782 		return FALSE;
783 
784 	key_len = rdp->settings->RdpServerRsaKey->ModulusLength;
785 	client_random = malloc(key_len);
786 
787 	if (!client_random)
788 		return FALSE;
789 
790 	if (rand_len != key_len + 8)
791 	{
792 		WLog_ERR(TAG, "invalid encrypted client random length");
793 		free(client_random);
794 		goto end;
795 	}
796 
797 	crypt_client_random = calloc(1, rand_len);
798 
799 	if (!crypt_client_random)
800 	{
801 		free(client_random);
802 		goto end;
803 	}
804 
805 	Stream_Read(s, crypt_client_random, rand_len);
806 	mod = rdp->settings->RdpServerRsaKey->Modulus;
807 	priv_exp = rdp->settings->RdpServerRsaKey->PrivateExponent;
808 
809 	if (crypto_rsa_private_decrypt(crypt_client_random, rand_len - 8, key_len, mod, priv_exp,
810 	                               client_random) <= 0)
811 	{
812 		free(client_random);
813 		goto end;
814 	}
815 
816 	rdp->settings->ClientRandom = client_random;
817 	rdp->settings->ClientRandomLength = 32;
818 
819 	/* now calculate encrypt / decrypt and update keys */
820 	if (!security_establish_keys(client_random, rdp))
821 		goto end;
822 
823 	rdp->do_crypt = TRUE;
824 
825 	if (rdp->settings->EncryptionMethods == ENCRYPTION_METHOD_FIPS)
826 	{
827 		rdp->fips_encrypt = winpr_Cipher_New(WINPR_CIPHER_DES_EDE3_CBC, WINPR_ENCRYPT,
828 		                                     rdp->fips_encrypt_key, fips_ivec);
829 
830 		if (!rdp->fips_encrypt)
831 		{
832 			WLog_ERR(TAG, "unable to allocate des3 encrypt key");
833 			goto end;
834 		}
835 
836 		rdp->fips_decrypt = winpr_Cipher_New(WINPR_CIPHER_DES_EDE3_CBC, WINPR_DECRYPT,
837 		                                     rdp->fips_decrypt_key, fips_ivec);
838 
839 		if (!rdp->fips_decrypt)
840 		{
841 			WLog_ERR(TAG, "unable to allocate des3 decrypt key");
842 			goto end;
843 		}
844 
845 		ret = TRUE;
846 		goto end;
847 	}
848 
849 	rdp->rc4_decrypt_key = winpr_RC4_New(rdp->decrypt_key, rdp->rc4_key_len);
850 	rdp->rc4_encrypt_key = winpr_RC4_New(rdp->encrypt_key, rdp->rc4_key_len);
851 
852 	if (!rdp->rc4_decrypt_key || !rdp->rc4_encrypt_key)
853 		goto end;
854 
855 	ret = tpkt_ensure_stream_consumed(s, length);
856 end:
857 	free(crypt_client_random);
858 
859 	if (!ret)
860 	{
861 		winpr_Cipher_Free(rdp->fips_encrypt);
862 		winpr_Cipher_Free(rdp->fips_decrypt);
863 		winpr_RC4_Free(rdp->rc4_encrypt_key);
864 		winpr_RC4_Free(rdp->rc4_decrypt_key);
865 		rdp->fips_encrypt = NULL;
866 		rdp->fips_decrypt = NULL;
867 		rdp->rc4_encrypt_key = NULL;
868 		rdp->rc4_decrypt_key = NULL;
869 	}
870 
871 	return ret;
872 }
873 
rdp_client_connect_mcs_channel_join_confirm(rdpRdp * rdp,wStream * s)874 BOOL rdp_client_connect_mcs_channel_join_confirm(rdpRdp* rdp, wStream* s)
875 {
876 	UINT32 i;
877 	UINT16 channelId;
878 	BOOL allJoined = TRUE;
879 	rdpMcs* mcs = rdp->mcs;
880 
881 	if (!mcs_recv_channel_join_confirm(mcs, s, &channelId))
882 		return FALSE;
883 
884 	if (!mcs->userChannelJoined)
885 	{
886 		if (channelId != mcs->userId)
887 			return FALSE;
888 
889 		mcs->userChannelJoined = TRUE;
890 
891 		if (!mcs_send_channel_join_request(mcs, MCS_GLOBAL_CHANNEL_ID))
892 			return FALSE;
893 	}
894 	else if (!mcs->globalChannelJoined)
895 	{
896 		if (channelId != MCS_GLOBAL_CHANNEL_ID)
897 			return FALSE;
898 
899 		mcs->globalChannelJoined = TRUE;
900 
901 		if (mcs->messageChannelId != 0)
902 		{
903 			if (!mcs_send_channel_join_request(mcs, mcs->messageChannelId))
904 				return FALSE;
905 
906 			allJoined = FALSE;
907 		}
908 		else
909 		{
910 			if (mcs->channelCount > 0)
911 			{
912 				if (!mcs_send_channel_join_request(mcs, mcs->channels[0].ChannelId))
913 					return FALSE;
914 
915 				allJoined = FALSE;
916 			}
917 		}
918 	}
919 	else if ((mcs->messageChannelId != 0) && !mcs->messageChannelJoined)
920 	{
921 		if (channelId != mcs->messageChannelId)
922 			return FALSE;
923 
924 		mcs->messageChannelJoined = TRUE;
925 
926 		if (mcs->channelCount > 0)
927 		{
928 			if (!mcs_send_channel_join_request(mcs, mcs->channels[0].ChannelId))
929 				return FALSE;
930 
931 			allJoined = FALSE;
932 		}
933 	}
934 	else
935 	{
936 		for (i = 0; i < mcs->channelCount; i++)
937 		{
938 			if (mcs->channels[i].joined)
939 				continue;
940 
941 			if (mcs->channels[i].ChannelId != channelId)
942 				return FALSE;
943 
944 			mcs->channels[i].joined = TRUE;
945 			break;
946 		}
947 
948 		if (i + 1 < mcs->channelCount)
949 		{
950 			if (!mcs_send_channel_join_request(mcs, mcs->channels[i + 1].ChannelId))
951 				return FALSE;
952 
953 			allJoined = FALSE;
954 		}
955 	}
956 
957 	if (mcs->userChannelJoined && mcs->globalChannelJoined && allJoined)
958 	{
959 		if (!rdp_client_establish_keys(rdp))
960 			return FALSE;
961 
962 		if (!rdp_send_client_info(rdp))
963 			return FALSE;
964 
965 		rdp_client_transition_to_state(rdp, CONNECTION_STATE_LICENSING);
966 	}
967 
968 	return TRUE;
969 }
970 
rdp_client_connect_auto_detect(rdpRdp * rdp,wStream * s)971 BOOL rdp_client_connect_auto_detect(rdpRdp* rdp, wStream* s)
972 {
973 	BYTE* mark;
974 	UINT16 length;
975 	UINT16 channelId;
976 
977 	/* If the MCS message channel has been joined... */
978 	if (rdp->mcs->messageChannelId != 0)
979 	{
980 		/* Process any MCS message channel PDUs. */
981 		Stream_GetPointer(s, mark);
982 
983 		if (rdp_read_header(rdp, s, &length, &channelId))
984 		{
985 			if (channelId == rdp->mcs->messageChannelId)
986 			{
987 				UINT16 securityFlags = 0;
988 
989 				if (!rdp_read_security_header(s, &securityFlags, &length))
990 					return FALSE;
991 
992 				if (securityFlags & SEC_ENCRYPT)
993 				{
994 					if (!rdp_decrypt(rdp, s, &length, securityFlags))
995 					{
996 						WLog_ERR(TAG, "rdp_decrypt failed");
997 						return FALSE;
998 					}
999 				}
1000 
1001 				if (rdp_recv_message_channel_pdu(rdp, s, securityFlags) == 0)
1002 					return tpkt_ensure_stream_consumed(s, length);
1003 			}
1004 		}
1005 
1006 		Stream_SetPointer(s, mark);
1007 	}
1008 
1009 	return FALSE;
1010 }
1011 
rdp_client_connect_license(rdpRdp * rdp,wStream * s)1012 int rdp_client_connect_license(rdpRdp* rdp, wStream* s)
1013 {
1014 	int status;
1015 	status = license_recv(rdp->license, s);
1016 
1017 	if (status < 0)
1018 		return status;
1019 
1020 	if (rdp->license->state == LICENSE_STATE_ABORTED)
1021 	{
1022 		WLog_ERR(TAG, "license connection sequence aborted.");
1023 		return -1;
1024 	}
1025 
1026 	if (rdp->license->state == LICENSE_STATE_COMPLETED)
1027 	{
1028 		rdp_client_transition_to_state(rdp, CONNECTION_STATE_CAPABILITIES_EXCHANGE);
1029 	}
1030 
1031 	return 0;
1032 }
1033 
rdp_client_connect_demand_active(rdpRdp * rdp,wStream * s)1034 int rdp_client_connect_demand_active(rdpRdp* rdp, wStream* s)
1035 {
1036 	BYTE* mark;
1037 	UINT16 width;
1038 	UINT16 height;
1039 	UINT16 length;
1040 	width = rdp->settings->DesktopWidth;
1041 	height = rdp->settings->DesktopHeight;
1042 	Stream_GetPointer(s, mark);
1043 
1044 	if (!rdp_recv_demand_active(rdp, s))
1045 	{
1046 		int rc;
1047 		UINT16 channelId;
1048 		Stream_SetPointer(s, mark);
1049 		if (!rdp_recv_get_active_header(rdp, s, &channelId, &length))
1050 			return -1;
1051 		/* Was Stream_Seek(s, RDP_PACKET_HEADER_MAX_LENGTH);
1052 		 * but the headers aren't always that length,
1053 		 * so that could result in a bad offset.
1054 		 */
1055 		rc = rdp_recv_out_of_sequence_pdu(rdp, s);
1056 		if (rc < 0)
1057 			return rc;
1058 		if (!tpkt_ensure_stream_consumed(s, length))
1059 			return -1;
1060 		return rc;
1061 	}
1062 
1063 	if (freerdp_shall_disconnect(rdp->instance))
1064 		return 0;
1065 
1066 	if (!rdp_send_confirm_active(rdp))
1067 		return -1;
1068 
1069 	if (!input_register_client_callbacks(rdp->input))
1070 	{
1071 		WLog_ERR(TAG, "error registering client callbacks");
1072 		return -1;
1073 	}
1074 
1075 	/**
1076 	 * The server may request a different desktop size during Deactivation-Reactivation sequence.
1077 	 * In this case, the UI should be informed and do actual window resizing at this point.
1078 	 */
1079 	if (width != rdp->settings->DesktopWidth || height != rdp->settings->DesktopHeight)
1080 	{
1081 		BOOL status = TRUE;
1082 		IFCALLRET(rdp->update->DesktopResize, status, rdp->update->context);
1083 
1084 		if (!status)
1085 		{
1086 			WLog_ERR(TAG, "client desktop resize callback failed");
1087 			return -1;
1088 		}
1089 	}
1090 
1091 	rdp_client_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION);
1092 	return rdp_client_connect_finalize(rdp);
1093 }
1094 
rdp_client_connect_finalize(rdpRdp * rdp)1095 int rdp_client_connect_finalize(rdpRdp* rdp)
1096 {
1097 	/**
1098 	 * [MS-RDPBCGR] 1.3.1.1 - 8.
1099 	 * The client-to-server PDUs sent during this phase have no dependencies on any of the
1100 	 * server-to- client PDUs; they may be sent as a single batch, provided that sequencing is
1101 	 * maintained.
1102 	 */
1103 	if (!rdp_send_client_synchronize_pdu(rdp))
1104 		return -1;
1105 
1106 	if (!rdp_send_client_control_pdu(rdp, CTRLACTION_COOPERATE))
1107 		return -1;
1108 
1109 	if (!rdp_send_client_control_pdu(rdp, CTRLACTION_REQUEST_CONTROL))
1110 		return -1;
1111 
1112 	/**
1113 	 * [MS-RDPBCGR] 2.2.1.17
1114 	 * Client persistent key list must be sent if a bitmap is
1115 	 * stored in persistent bitmap cache or the server has advertised support for bitmap
1116 	 * host cache and a deactivation reactivation sequence is *not* in progress.
1117 	 */
1118 
1119 	if (!rdp->deactivation_reactivation && rdp->settings->BitmapCachePersistEnabled)
1120 	{
1121 		if (!rdp_send_client_persistent_key_list_pdu(rdp))
1122 			return -1;
1123 	}
1124 
1125 	if (!rdp_send_client_font_list_pdu(rdp, FONTLIST_FIRST | FONTLIST_LAST))
1126 		return -1;
1127 
1128 	return 0;
1129 }
1130 
rdp_client_transition_to_state(rdpRdp * rdp,int state)1131 int rdp_client_transition_to_state(rdpRdp* rdp, int state)
1132 {
1133 	int status = 0;
1134 
1135 	switch (state)
1136 	{
1137 		case CONNECTION_STATE_INITIAL:
1138 			rdp->state = CONNECTION_STATE_INITIAL;
1139 			break;
1140 
1141 		case CONNECTION_STATE_NEGO:
1142 			rdp->state = CONNECTION_STATE_NEGO;
1143 			break;
1144 
1145 		case CONNECTION_STATE_NLA:
1146 			rdp->state = CONNECTION_STATE_NLA;
1147 			break;
1148 
1149 		case CONNECTION_STATE_MCS_CONNECT:
1150 			rdp->state = CONNECTION_STATE_MCS_CONNECT;
1151 			break;
1152 
1153 		case CONNECTION_STATE_MCS_ERECT_DOMAIN:
1154 			rdp->state = CONNECTION_STATE_MCS_ERECT_DOMAIN;
1155 			break;
1156 
1157 		case CONNECTION_STATE_MCS_ATTACH_USER:
1158 			rdp->state = CONNECTION_STATE_MCS_ATTACH_USER;
1159 			break;
1160 
1161 		case CONNECTION_STATE_MCS_CHANNEL_JOIN:
1162 			rdp->state = CONNECTION_STATE_MCS_CHANNEL_JOIN;
1163 			break;
1164 
1165 		case CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT:
1166 			rdp->state = CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT;
1167 			break;
1168 
1169 		case CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE:
1170 			rdp->state = CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE;
1171 			break;
1172 
1173 		case CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT:
1174 			rdp->state = CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT;
1175 			break;
1176 
1177 		case CONNECTION_STATE_LICENSING:
1178 			rdp->state = CONNECTION_STATE_LICENSING;
1179 			break;
1180 
1181 		case CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING:
1182 			rdp->state = CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING;
1183 			break;
1184 
1185 		case CONNECTION_STATE_CAPABILITIES_EXCHANGE:
1186 			rdp->state = CONNECTION_STATE_CAPABILITIES_EXCHANGE;
1187 			break;
1188 
1189 		case CONNECTION_STATE_FINALIZATION:
1190 			rdp->state = CONNECTION_STATE_FINALIZATION;
1191 			update_reset_state(rdp->update);
1192 			rdp->finalize_sc_pdus = 0;
1193 			break;
1194 
1195 		case CONNECTION_STATE_ACTIVE:
1196 			rdp->state = CONNECTION_STATE_ACTIVE;
1197 			{
1198 				ActivatedEventArgs activatedEvent;
1199 				rdpContext* context = rdp->context;
1200 				EventArgsInit(&activatedEvent, "libfreerdp");
1201 				activatedEvent.firstActivation = !rdp->deactivation_reactivation;
1202 				PubSub_OnActivated(context->pubSub, context, &activatedEvent);
1203 			}
1204 
1205 			break;
1206 
1207 		default:
1208 			status = -1;
1209 			break;
1210 	}
1211 
1212 	{
1213 		ConnectionStateChangeEventArgs stateEvent;
1214 		rdpContext* context = rdp->context;
1215 		EventArgsInit(&stateEvent, "libfreerdp");
1216 		stateEvent.state = rdp->state;
1217 		stateEvent.active = rdp->state == CONNECTION_STATE_ACTIVE;
1218 		PubSub_OnConnectionStateChange(context->pubSub, context, &stateEvent);
1219 	}
1220 
1221 	return status;
1222 }
1223 
rdp_server_accept_nego(rdpRdp * rdp,wStream * s)1224 BOOL rdp_server_accept_nego(rdpRdp* rdp, wStream* s)
1225 {
1226 	UINT32 SelectedProtocol = 0;
1227 	UINT32 RequestedProtocols;
1228 	BOOL status;
1229 	rdpSettings* settings = rdp->settings;
1230 	rdpNego* nego = rdp->nego;
1231 	transport_set_blocking_mode(rdp->transport, TRUE);
1232 
1233 	if (!nego_read_request(nego, s))
1234 		return FALSE;
1235 
1236 	RequestedProtocols = nego_get_requested_protocols(nego);
1237 	WLog_INFO(TAG, "Client Security: NLA:%d TLS:%d RDP:%d",
1238 	          (RequestedProtocols & PROTOCOL_HYBRID) ? 1 : 0,
1239 	          (RequestedProtocols & PROTOCOL_SSL) ? 1 : 0,
1240 	          (RequestedProtocols == PROTOCOL_RDP) ? 1 : 0);
1241 	WLog_INFO(TAG, "Server Security: NLA:%" PRId32 " TLS:%" PRId32 " RDP:%" PRId32 "",
1242 	          settings->NlaSecurity, settings->TlsSecurity, settings->RdpSecurity);
1243 
1244 	if ((settings->NlaSecurity) && (RequestedProtocols & PROTOCOL_HYBRID))
1245 	{
1246 		SelectedProtocol = PROTOCOL_HYBRID;
1247 	}
1248 	else if ((settings->TlsSecurity) && (RequestedProtocols & PROTOCOL_SSL))
1249 	{
1250 		SelectedProtocol = PROTOCOL_SSL;
1251 	}
1252 	else if ((settings->RdpSecurity) && (RequestedProtocols == PROTOCOL_RDP))
1253 	{
1254 		SelectedProtocol = PROTOCOL_RDP;
1255 	}
1256 	else
1257 	{
1258 		/*
1259 		 * when here client and server aren't compatible, we select the right
1260 		 * error message to return to the client in the nego failure packet
1261 		 */
1262 		SelectedProtocol = PROTOCOL_FAILED_NEGO;
1263 
1264 		if (settings->RdpSecurity)
1265 		{
1266 			WLog_ERR(TAG, "server supports only Standard RDP Security");
1267 			SelectedProtocol |= SSL_NOT_ALLOWED_BY_SERVER;
1268 		}
1269 		else
1270 		{
1271 			if (settings->NlaSecurity && !settings->TlsSecurity)
1272 			{
1273 				WLog_WARN(TAG, "server supports only NLA Security");
1274 				SelectedProtocol |= HYBRID_REQUIRED_BY_SERVER;
1275 			}
1276 			else
1277 			{
1278 				WLog_WARN(TAG, "server supports only a SSL based Security (TLS or NLA)");
1279 				SelectedProtocol |= SSL_REQUIRED_BY_SERVER;
1280 			}
1281 		}
1282 
1283 		WLog_ERR(TAG, "Protocol security negotiation failure");
1284 	}
1285 
1286 	if (!(SelectedProtocol & PROTOCOL_FAILED_NEGO))
1287 	{
1288 		WLog_INFO(TAG, "Negotiated Security: NLA:%d TLS:%d RDP:%d",
1289 		          (SelectedProtocol & PROTOCOL_HYBRID) ? 1 : 0,
1290 		          (SelectedProtocol & PROTOCOL_SSL) ? 1 : 0,
1291 		          (SelectedProtocol == PROTOCOL_RDP) ? 1 : 0);
1292 	}
1293 
1294 	if (!nego_set_selected_protocol(nego, SelectedProtocol))
1295 		return FALSE;
1296 
1297 	if (!nego_send_negotiation_response(nego))
1298 		return FALSE;
1299 
1300 	SelectedProtocol = nego_get_selected_protocol(nego);
1301 	status = FALSE;
1302 
1303 	if (SelectedProtocol & PROTOCOL_HYBRID)
1304 		status = transport_accept_nla(rdp->transport);
1305 	else if (SelectedProtocol & PROTOCOL_SSL)
1306 		status = transport_accept_tls(rdp->transport);
1307 	else if (SelectedProtocol == PROTOCOL_RDP) /* 0 */
1308 		status = transport_accept_rdp(rdp->transport);
1309 
1310 	if (!status)
1311 		return FALSE;
1312 
1313 	transport_set_blocking_mode(rdp->transport, FALSE);
1314 	rdp_server_transition_to_state(rdp, CONNECTION_STATE_NEGO);
1315 	return TRUE;
1316 }
1317 
rdp_server_accept_mcs_connect_initial(rdpRdp * rdp,wStream * s)1318 BOOL rdp_server_accept_mcs_connect_initial(rdpRdp* rdp, wStream* s)
1319 {
1320 	UINT32 i;
1321 	rdpMcs* mcs = rdp->mcs;
1322 
1323 	if (!mcs_recv_connect_initial(mcs, s))
1324 		return FALSE;
1325 
1326 	WLog_INFO(TAG, "Accepted client: %s", rdp->settings->ClientHostname);
1327 	WLog_INFO(TAG, "Accepted channels:");
1328 
1329 	for (i = 0; i < mcs->channelCount; i++)
1330 	{
1331 		WLog_INFO(TAG, " %s", mcs->channels[i].Name);
1332 	}
1333 
1334 	if (!mcs_send_connect_response(mcs))
1335 		return FALSE;
1336 
1337 	rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_CONNECT);
1338 	return TRUE;
1339 }
1340 
rdp_server_accept_mcs_erect_domain_request(rdpRdp * rdp,wStream * s)1341 BOOL rdp_server_accept_mcs_erect_domain_request(rdpRdp* rdp, wStream* s)
1342 {
1343 	if (!mcs_recv_erect_domain_request(rdp->mcs, s))
1344 		return FALSE;
1345 
1346 	rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_ERECT_DOMAIN);
1347 	return TRUE;
1348 }
1349 
rdp_server_accept_mcs_attach_user_request(rdpRdp * rdp,wStream * s)1350 BOOL rdp_server_accept_mcs_attach_user_request(rdpRdp* rdp, wStream* s)
1351 {
1352 	if (!mcs_recv_attach_user_request(rdp->mcs, s))
1353 		return FALSE;
1354 
1355 	if (!mcs_send_attach_user_confirm(rdp->mcs))
1356 		return FALSE;
1357 
1358 	rdp_server_transition_to_state(rdp, CONNECTION_STATE_MCS_ATTACH_USER);
1359 	return TRUE;
1360 }
1361 
rdp_server_accept_mcs_channel_join_request(rdpRdp * rdp,wStream * s)1362 BOOL rdp_server_accept_mcs_channel_join_request(rdpRdp* rdp, wStream* s)
1363 {
1364 	UINT32 i;
1365 	UINT16 channelId;
1366 	BOOL allJoined = TRUE;
1367 	rdpMcs* mcs = rdp->mcs;
1368 
1369 	if (!mcs_recv_channel_join_request(mcs, s, &channelId))
1370 		return FALSE;
1371 
1372 	if (!mcs_send_channel_join_confirm(mcs, channelId))
1373 		return FALSE;
1374 
1375 	if (channelId == mcs->userId)
1376 		mcs->userChannelJoined = TRUE;
1377 	else if (channelId == MCS_GLOBAL_CHANNEL_ID)
1378 		mcs->globalChannelJoined = TRUE;
1379 	else if (channelId == mcs->messageChannelId)
1380 		mcs->messageChannelJoined = TRUE;
1381 
1382 	for (i = 0; i < mcs->channelCount; i++)
1383 	{
1384 		if (mcs->channels[i].ChannelId == channelId)
1385 			mcs->channels[i].joined = TRUE;
1386 
1387 		if (!mcs->channels[i].joined)
1388 			allJoined = FALSE;
1389 	}
1390 
1391 	if ((mcs->userChannelJoined) && (mcs->globalChannelJoined) &&
1392 	    (mcs->messageChannelId == 0 || mcs->messageChannelJoined) && allJoined)
1393 	{
1394 		rdp_server_transition_to_state(rdp, CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT);
1395 	}
1396 
1397 	return TRUE;
1398 }
1399 
rdp_server_accept_confirm_active(rdpRdp * rdp,wStream * s,UINT16 pduLength)1400 BOOL rdp_server_accept_confirm_active(rdpRdp* rdp, wStream* s, UINT16 pduLength)
1401 {
1402 	freerdp_peer* peer = rdp->context->peer;
1403 
1404 	if (rdp->state != CONNECTION_STATE_CAPABILITIES_EXCHANGE)
1405 		return FALSE;
1406 
1407 	if (!rdp_recv_confirm_active(rdp, s, pduLength))
1408 		return FALSE;
1409 
1410 	if (peer->ClientCapabilities && !peer->ClientCapabilities(peer))
1411 		return FALSE;
1412 
1413 	if (rdp->settings->SaltedChecksum)
1414 		rdp->do_secure_checksum = TRUE;
1415 
1416 	rdp_server_transition_to_state(rdp, CONNECTION_STATE_FINALIZATION);
1417 
1418 	if (!rdp_send_server_synchronize_pdu(rdp))
1419 		return FALSE;
1420 
1421 	if (!rdp_send_server_control_cooperate_pdu(rdp))
1422 		return FALSE;
1423 
1424 	return TRUE;
1425 }
1426 
rdp_server_reactivate(rdpRdp * rdp)1427 BOOL rdp_server_reactivate(rdpRdp* rdp)
1428 {
1429 	freerdp_peer* client = NULL;
1430 
1431 	if (rdp->context && rdp->context->peer)
1432 		client = rdp->context->peer;
1433 
1434 	if (client)
1435 		client->activated = FALSE;
1436 
1437 	if (!rdp_send_deactivate_all(rdp))
1438 		return FALSE;
1439 
1440 	rdp_server_transition_to_state(rdp, CONNECTION_STATE_CAPABILITIES_EXCHANGE);
1441 
1442 	if (!rdp_send_demand_active(rdp))
1443 		return FALSE;
1444 
1445 	rdp->AwaitCapabilities = TRUE;
1446 	return TRUE;
1447 }
1448 
rdp_server_transition_to_state(rdpRdp * rdp,int state)1449 int rdp_server_transition_to_state(rdpRdp* rdp, int state)
1450 {
1451 	int status = 0;
1452 	freerdp_peer* client = NULL;
1453 
1454 	if (rdp->state >= CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT)
1455 		client = rdp->context->peer;
1456 
1457 	if (rdp->state < CONNECTION_STATE_ACTIVE)
1458 	{
1459 		if (client)
1460 			client->activated = FALSE;
1461 	}
1462 
1463 	switch (state)
1464 	{
1465 		case CONNECTION_STATE_INITIAL:
1466 			rdp->state = CONNECTION_STATE_INITIAL;
1467 			break;
1468 
1469 		case CONNECTION_STATE_NEGO:
1470 			rdp->state = CONNECTION_STATE_NEGO;
1471 			break;
1472 
1473 		case CONNECTION_STATE_MCS_CONNECT:
1474 			rdp->state = CONNECTION_STATE_MCS_CONNECT;
1475 			break;
1476 
1477 		case CONNECTION_STATE_MCS_ERECT_DOMAIN:
1478 			rdp->state = CONNECTION_STATE_MCS_ERECT_DOMAIN;
1479 			break;
1480 
1481 		case CONNECTION_STATE_MCS_ATTACH_USER:
1482 			rdp->state = CONNECTION_STATE_MCS_ATTACH_USER;
1483 			break;
1484 
1485 		case CONNECTION_STATE_MCS_CHANNEL_JOIN:
1486 			rdp->state = CONNECTION_STATE_MCS_CHANNEL_JOIN;
1487 			break;
1488 
1489 		case CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT:
1490 			rdp->state = CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT;
1491 			break;
1492 
1493 		case CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE:
1494 			rdp->state = CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE;
1495 			break;
1496 
1497 		case CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT:
1498 			rdp->state = CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT;
1499 			break;
1500 
1501 		case CONNECTION_STATE_LICENSING:
1502 			rdp->state = CONNECTION_STATE_LICENSING;
1503 			break;
1504 
1505 		case CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING:
1506 			rdp->state = CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING;
1507 			break;
1508 
1509 		case CONNECTION_STATE_CAPABILITIES_EXCHANGE:
1510 			rdp->state = CONNECTION_STATE_CAPABILITIES_EXCHANGE;
1511 			rdp->AwaitCapabilities = FALSE;
1512 			break;
1513 
1514 		case CONNECTION_STATE_FINALIZATION:
1515 			rdp->state = CONNECTION_STATE_FINALIZATION;
1516 			rdp->finalize_sc_pdus = 0;
1517 			break;
1518 
1519 		case CONNECTION_STATE_ACTIVE:
1520 			rdp->state = CONNECTION_STATE_ACTIVE;
1521 			update_reset_state(rdp->update);
1522 
1523 			if (client)
1524 			{
1525 				if (!client->connected)
1526 				{
1527 					/**
1528 					 * PostConnect should only be called once and should not
1529 					 * be called after a reactivation sequence.
1530 					 */
1531 					IFCALLRET(client->PostConnect, client->connected, client);
1532 
1533 					if (!client->connected)
1534 						return -1;
1535 				}
1536 
1537 				if (rdp->state >= CONNECTION_STATE_ACTIVE)
1538 				{
1539 					IFCALLRET(client->Activate, client->activated, client);
1540 
1541 					if (!client->activated)
1542 						return -1;
1543 				}
1544 			}
1545 
1546 			break;
1547 
1548 		default:
1549 			status = -1;
1550 			break;
1551 	}
1552 
1553 	return status;
1554 }
1555 
rdp_client_connection_state_string(int state)1556 const char* rdp_client_connection_state_string(int state)
1557 {
1558 	switch (state)
1559 	{
1560 		case CLIENT_STATE_INITIAL:
1561 			return "CLIENT_STATE_INITIAL";
1562 		case CLIENT_STATE_PRECONNECT_PASSED:
1563 			return "CLIENT_STATE_PRECONNECT_PASSED";
1564 		case CLIENT_STATE_POSTCONNECT_PASSED:
1565 			return "CLIENT_STATE_POSTCONNECT_PASSED";
1566 		default:
1567 			return "UNKNOWN";
1568 	}
1569 }
1570 
rdp_server_connection_state_string(int state)1571 const char* rdp_server_connection_state_string(int state)
1572 {
1573 	switch (state)
1574 	{
1575 		case CONNECTION_STATE_INITIAL:
1576 			return "CONNECTION_STATE_INITIAL";
1577 		case CONNECTION_STATE_NEGO:
1578 			return "CONNECTION_STATE_NEGO";
1579 		case CONNECTION_STATE_NLA:
1580 			return "CONNECTION_STATE_NLA";
1581 		case CONNECTION_STATE_MCS_CONNECT:
1582 			return "CONNECTION_STATE_MCS_CONNECT";
1583 		case CONNECTION_STATE_MCS_ERECT_DOMAIN:
1584 			return "CONNECTION_STATE_MCS_ERECT_DOMAIN";
1585 		case CONNECTION_STATE_MCS_ATTACH_USER:
1586 			return "CONNECTION_STATE_MCS_ATTACH_USER";
1587 		case CONNECTION_STATE_MCS_CHANNEL_JOIN:
1588 			return "CONNECTION_STATE_MCS_CHANNEL_JOIN";
1589 		case CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT:
1590 			return "CONNECTION_STATE_RDP_SECURITY_COMMENCEMENT";
1591 		case CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE:
1592 			return "CONNECTION_STATE_SECURE_SETTINGS_EXCHANGE";
1593 		case CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT:
1594 			return "CONNECTION_STATE_CONNECT_TIME_AUTO_DETECT";
1595 		case CONNECTION_STATE_LICENSING:
1596 			return "CONNECTION_STATE_LICENSING";
1597 		case CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING:
1598 			return "CONNECTION_STATE_MULTITRANSPORT_BOOTSTRAPPING";
1599 		case CONNECTION_STATE_CAPABILITIES_EXCHANGE:
1600 			return "CONNECTION_STATE_CAPABILITIES_EXCHANGE";
1601 		case CONNECTION_STATE_FINALIZATION:
1602 			return "CONNECTION_STATE_FINALIZATION";
1603 		case CONNECTION_STATE_ACTIVE:
1604 			return "CONNECTION_STATE_ACTIVE";
1605 		default:
1606 			return "UNKNOWN";
1607 	}
1608 }
1609 
rdp_client_get_state(rdpRdp * rdp)1610 int rdp_client_get_state(rdpRdp* rdp)
1611 {
1612 	if (!rdp)
1613 		return -1;
1614 	return rdp->state;
1615 }
1616