FreeRDP
rpc_client.c
1 
20 #include <freerdp/config.h>
21 
22 #include <freerdp/log.h>
23 
24 #include <winpr/crt.h>
25 #include <winpr/wtypes.h>
26 #include <winpr/assert.h>
27 #include <winpr/print.h>
28 #include <winpr/synch.h>
29 #include <winpr/thread.h>
30 #include <winpr/stream.h>
31 
32 #include "http.h"
33 #include "ncacn_http.h"
34 
35 #include "rpc_bind.h"
36 #include "rpc_fault.h"
37 #include "rpc_client.h"
38 #include "rts_signature.h"
39 
40 #include "../utils.h"
41 #include "../rdp.h"
42 #include "../proxy.h"
43 
44 #define TAG FREERDP_TAG("core.gateway.rpc")
45 
46 static const char* rpc_client_state_str(RPC_CLIENT_STATE state)
47 {
48  // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores)
49  const char* str = "RPC_CLIENT_STATE_UNKNOWN";
50 
51  switch (state)
52  {
53  case RPC_CLIENT_STATE_INITIAL:
54  str = "RPC_CLIENT_STATE_INITIAL";
55  break;
56 
57  case RPC_CLIENT_STATE_ESTABLISHED:
58  str = "RPC_CLIENT_STATE_ESTABLISHED";
59  break;
60 
61  case RPC_CLIENT_STATE_WAIT_SECURE_BIND_ACK:
62  str = "RPC_CLIENT_STATE_WAIT_SECURE_BIND_ACK";
63  break;
64 
65  case RPC_CLIENT_STATE_WAIT_UNSECURE_BIND_ACK:
66  str = "RPC_CLIENT_STATE_WAIT_UNSECURE_BIND_ACK";
67  break;
68 
69  case RPC_CLIENT_STATE_WAIT_SECURE_ALTER_CONTEXT_RESPONSE:
70  str = "RPC_CLIENT_STATE_WAIT_SECURE_ALTER_CONTEXT_RESPONSE";
71  break;
72 
73  case RPC_CLIENT_STATE_CONTEXT_NEGOTIATED:
74  str = "RPC_CLIENT_STATE_CONTEXT_NEGOTIATED";
75  break;
76 
77  case RPC_CLIENT_STATE_WAIT_RESPONSE:
78  str = "RPC_CLIENT_STATE_WAIT_RESPONSE";
79  break;
80 
81  case RPC_CLIENT_STATE_FINAL:
82  str = "RPC_CLIENT_STATE_FINAL";
83  break;
84  default:
85  break;
86  }
87  return str;
88 }
89 
90 static void rpc_pdu_reset(RPC_PDU* pdu)
91 {
92  pdu->Type = 0;
93  pdu->Flags = 0;
94  pdu->CallId = 0;
95  Stream_SetPosition(pdu->s, 0);
96  Stream_SetLength(pdu->s, 0);
97 }
98 
99 static RPC_PDU* rpc_pdu_new(void)
100 {
101  RPC_PDU* pdu = NULL;
102  pdu = (RPC_PDU*)malloc(sizeof(RPC_PDU));
103 
104  if (!pdu)
105  return NULL;
106 
107  pdu->s = Stream_New(NULL, 4096);
108 
109  if (!pdu->s)
110  {
111  free(pdu);
112  return NULL;
113  }
114 
115  rpc_pdu_reset(pdu);
116  return pdu;
117 }
118 
119 static void rpc_pdu_free(RPC_PDU* pdu)
120 {
121  if (!pdu)
122  return;
123 
124  Stream_Free(pdu->s, TRUE);
125  free(pdu);
126 }
127 
128 static int rpc_client_receive_pipe_write(RpcClient* client, const BYTE* buffer, size_t length)
129 {
130  int status = 0;
131 
132  if (!client || !buffer)
133  return -1;
134 
135  EnterCriticalSection(&(client->PipeLock));
136 
137  if (ringbuffer_write(&(client->ReceivePipe), buffer, length))
138  status += (int)length;
139 
140  if (ringbuffer_used(&(client->ReceivePipe)) > 0)
141  (void)SetEvent(client->PipeEvent);
142 
143  LeaveCriticalSection(&(client->PipeLock));
144  return status;
145 }
146 
147 int rpc_client_receive_pipe_read(RpcClient* client, BYTE* buffer, size_t length)
148 {
149  size_t status = 0;
150  int nchunks = 0;
151  DataChunk chunks[2];
152 
153  if (!client || !buffer)
154  return -1;
155 
156  EnterCriticalSection(&(client->PipeLock));
157  nchunks = ringbuffer_peek(&(client->ReceivePipe), chunks, length);
158 
159  for (int index = 0; index < nchunks; index++)
160  {
161  CopyMemory(&buffer[status], chunks[index].data, chunks[index].size);
162  status += chunks[index].size;
163  }
164 
165  if (status > 0)
166  ringbuffer_commit_read_bytes(&(client->ReceivePipe), status);
167 
168  if (ringbuffer_used(&(client->ReceivePipe)) < 1)
169  (void)ResetEvent(client->PipeEvent);
170 
171  LeaveCriticalSection(&(client->PipeLock));
172 
173  if (status > INT_MAX)
174  return -1;
175  return (int)status;
176 }
177 
178 static int rpc_client_transition_to_state(rdpRpc* rpc, RPC_CLIENT_STATE state)
179 {
180  int status = 1;
181 
182  rpc->State = state;
183  WLog_DBG(TAG, "%s", rpc_client_state_str(state));
184  return status;
185 }
186 
187 static int rpc_client_recv_pdu_int(rdpRpc* rpc, RPC_PDU* pdu)
188 {
189  int status = -1;
190  RtsPduSignature found = { 0 };
191 
192  WINPR_ASSERT(rpc);
193  WINPR_ASSERT(pdu);
194 
195  rdpTsg* tsg = transport_get_tsg(rpc->transport);
196 
197  WLog_VRB(TAG, "client state %s, vc state %s", rpc_client_state_str(rpc->State),
198  rpc_vc_state_str(rpc->VirtualConnection->State));
199 
200  const BOOL rc = rts_match_pdu_signature_ex(&RTS_PDU_PING_SIGNATURE, pdu->s, NULL, &found, TRUE);
201  rts_print_pdu_signature(rpc->log, WLOG_TRACE, &found);
202  if (rc)
203  return rts_recv_ping_pdu(rpc, pdu->s);
204 
205  if (rpc->VirtualConnection->State < VIRTUAL_CONNECTION_STATE_OPENED)
206  {
207  switch (rpc->VirtualConnection->State)
208  {
209  case VIRTUAL_CONNECTION_STATE_INITIAL:
210  break;
211 
212  case VIRTUAL_CONNECTION_STATE_OUT_CHANNEL_WAIT:
213  break;
214 
215  case VIRTUAL_CONNECTION_STATE_WAIT_A3W:
216  if (memcmp(&found, &RTS_PDU_CONN_A3_SIGNATURE, sizeof(found)) != 0)
217  {
218  wLog* log = WLog_Get(TAG);
219  WLog_Print(log, WLOG_ERROR, "unexpected RTS PDU: Expected CONN/A3");
220  rts_print_pdu_signature(log, WLOG_ERROR, &found);
221  return -1;
222  }
223 
224  if (!rts_recv_CONN_A3_pdu(rpc, pdu->s))
225  {
226  WLog_ERR(TAG, "rts_recv_CONN_A3_pdu failure");
227  return -1;
228  }
229 
230  rpc_virtual_connection_transition_to_state(rpc, rpc->VirtualConnection,
231  VIRTUAL_CONNECTION_STATE_WAIT_C2);
232  status = 1;
233  break;
234 
235  case VIRTUAL_CONNECTION_STATE_WAIT_C2:
236  if (memcmp(&found, &RTS_PDU_CONN_C2_SIGNATURE, sizeof(found)) != 0)
237  {
238  wLog* log = WLog_Get(TAG);
239  WLog_Print(log, WLOG_ERROR, "unexpected RTS PDU: Expected CONN/C2");
240  rts_print_pdu_signature(log, WLOG_ERROR, &found);
241  return -1;
242  }
243 
244  if (!rts_recv_CONN_C2_pdu(rpc, pdu->s))
245  {
246  WLog_ERR(TAG, "rts_recv_CONN_C2_pdu failure");
247  return -1;
248  }
249 
250  rpc_virtual_connection_transition_to_state(rpc, rpc->VirtualConnection,
251  VIRTUAL_CONNECTION_STATE_OPENED);
252  rpc_client_transition_to_state(rpc, RPC_CLIENT_STATE_ESTABLISHED);
253 
254  if (rpc_send_bind_pdu(rpc, TRUE) < 0)
255  {
256  WLog_ERR(TAG, "rpc_send_bind_pdu failure");
257  return -1;
258  }
259 
260  rpc_client_transition_to_state(rpc, RPC_CLIENT_STATE_WAIT_SECURE_BIND_ACK);
261  status = 1;
262  break;
263 
264  case VIRTUAL_CONNECTION_STATE_OPENED:
265  break;
266 
267  case VIRTUAL_CONNECTION_STATE_FINAL:
268  break;
269  default:
270  break;
271  }
272  }
273  else if (rpc->State < RPC_CLIENT_STATE_CONTEXT_NEGOTIATED)
274  {
275  if (rpc->State == RPC_CLIENT_STATE_WAIT_SECURE_BIND_ACK)
276  {
277  if (pdu->Type == PTYPE_BIND_ACK || pdu->Type == PTYPE_ALTER_CONTEXT_RESP)
278  {
279  if (!rpc_recv_bind_ack_pdu(rpc, pdu->s))
280  {
281  WLog_ERR(TAG, "rpc_recv_bind_ack_pdu failure");
282  return -1;
283  }
284  }
285  else
286  {
287  WLog_ERR(TAG,
288  "RPC_CLIENT_STATE_WAIT_SECURE_BIND_ACK unexpected pdu type: 0x%08" PRIX32
289  "",
290  pdu->Type);
291  return -1;
292  }
293 
294  switch (rpc_bind_state(rpc))
295  {
296  case RPC_BIND_STATE_INCOMPLETE:
297  if (rpc_send_bind_pdu(rpc, FALSE) < 0)
298  {
299  WLog_ERR(TAG, "rpc_send_bind_pdu failure");
300  return -1;
301  }
302  break;
303  case RPC_BIND_STATE_LAST_LEG:
304  if (rpc_send_rpc_auth_3_pdu(rpc) < 0)
305  {
306  WLog_ERR(TAG, "rpc_secure_bind: error sending rpc_auth_3 pdu!");
307  return -1;
308  }
309  /* fallthrough */
310  WINPR_FALLTHROUGH
311  case RPC_BIND_STATE_COMPLETE:
312  rpc_client_transition_to_state(rpc, RPC_CLIENT_STATE_CONTEXT_NEGOTIATED);
313 
314  if (!tsg_proxy_begin(tsg))
315  {
316  WLog_ERR(TAG, "tsg_proxy_begin failure");
317  return -1;
318  }
319  break;
320  default:
321  break;
322  }
323 
324  status = 1;
325  }
326  else
327  {
328  WLog_ERR(TAG, "invalid rpc->State: %d", rpc->State);
329  }
330  }
331  else if (rpc->State >= RPC_CLIENT_STATE_CONTEXT_NEGOTIATED)
332  {
333  if (!tsg_recv_pdu(tsg, pdu))
334  status = -1;
335  else
336  status = 1;
337  }
338 
339  return status;
340 }
341 
342 static int rpc_client_recv_pdu(rdpRpc* rpc, RPC_PDU* pdu)
343 {
344  WINPR_ASSERT(rpc);
345  WINPR_ASSERT(pdu);
346 
347  Stream_SealLength(pdu->s);
348  Stream_SetPosition(pdu->s, 0);
349 
350  const size_t before = Stream_GetRemainingLength(pdu->s);
351  WLog_VRB(TAG, "RPC PDU parsing %" PRIuz " bytes", before);
352  const int rc = rpc_client_recv_pdu_int(rpc, pdu);
353  if (rc < 0)
354  return rc;
355  const size_t after = Stream_GetRemainingLength(pdu->s);
356  if (after > 0)
357  {
358  /* Just log so we do not fail if we have some unprocessed padding bytes */
359  WLog_WARN(TAG, "Incompletely parsed RPC PDU (%" PRIuz " bytes remain)", after);
360  }
361 
362  return rc;
363 }
364 
365 static int rpc_client_recv_fragment(rdpRpc* rpc, wStream* fragment)
366 {
367  int rc = -1;
368  RPC_PDU* pdu = NULL;
369  size_t StubOffset = 0;
370  size_t StubLength = 0;
371  RpcClientCall* call = NULL;
372  rpcconn_hdr_t header = { 0 };
373 
374  WINPR_ASSERT(rpc);
375  WINPR_ASSERT(rpc->client);
376  WINPR_ASSERT(fragment);
377 
378  pdu = rpc->client->pdu;
379  WINPR_ASSERT(pdu);
380 
381  Stream_SealLength(fragment);
382  Stream_SetPosition(fragment, 0);
383 
384  if (!rts_read_pdu_header(fragment, &header))
385  goto fail;
386 
387  if (header.common.ptype == PTYPE_RESPONSE)
388  {
389  rpc->VirtualConnection->DefaultOutChannel->BytesReceived += header.common.frag_length;
390  rpc->VirtualConnection->DefaultOutChannel->ReceiverAvailableWindow -=
391  header.common.frag_length;
392 
393  if (rpc->VirtualConnection->DefaultOutChannel->ReceiverAvailableWindow <
394  (rpc->ReceiveWindow / 2))
395  {
396  if (!rts_send_flow_control_ack_pdu(rpc))
397  goto fail;
398  }
399 
400  if (!rpc_get_stub_data_info(rpc, &header, &StubOffset, &StubLength))
401  {
402  WLog_ERR(TAG, "expected stub");
403  goto fail;
404  }
405 
406  if (StubLength == 4)
407  {
408  if ((header.common.call_id == rpc->PipeCallId) &&
409  (header.common.pfc_flags & PFC_LAST_FRAG))
410  {
411  /* End of TsProxySetupReceivePipe */
412  TerminateEventArgs e;
413  rdpContext* context = transport_get_context(rpc->transport);
414  rdpTsg* tsg = transport_get_tsg(rpc->transport);
415 
416  WINPR_ASSERT(context);
417 
418  if (Stream_Length(fragment) < StubOffset + 4)
419  goto fail;
420  Stream_SetPosition(fragment, StubOffset);
421  Stream_Read_UINT32(fragment, rpc->result);
422 
423  utils_abort_connect(context->rdp);
424  tsg_set_state(tsg, TSG_STATE_TUNNEL_CLOSE_PENDING);
425  EventArgsInit(&e, "freerdp");
426  e.code = 0;
427  PubSub_OnTerminate(context->rdp->pubSub, context, &e);
428  rc = 0;
429  goto success;
430  }
431 
432  if (header.common.call_id != rpc->PipeCallId)
433  {
434  /* Ignoring non-TsProxySetupReceivePipe Response */
435  rc = 0;
436  goto success;
437  }
438  }
439 
440  if (rpc->StubFragCount == 0)
441  rpc->StubCallId = header.common.call_id;
442 
443  if (rpc->StubCallId != header.common.call_id)
444  {
445  WLog_ERR(TAG,
446  "invalid call_id: actual: %" PRIu32 ", expected: %" PRIu32
447  ", frag_count: %" PRIu32 "",
448  rpc->StubCallId, header.common.call_id, rpc->StubFragCount);
449  }
450 
451  call = rpc_client_call_find_by_id(rpc->client, rpc->StubCallId);
452 
453  if (!call)
454  goto fail;
455 
456  if (call->OpNum != TsProxySetupReceivePipeOpnum)
457  {
458  const rpcconn_response_hdr_t* response =
459  (const rpcconn_response_hdr_t*)&header.response;
460  if (!Stream_EnsureCapacity(pdu->s, response->alloc_hint))
461  goto fail;
462 
463  if (Stream_Length(fragment) < StubOffset + StubLength)
464  goto fail;
465 
466  Stream_SetPosition(fragment, StubOffset);
467  Stream_Write(pdu->s, Stream_ConstPointer(fragment), StubLength);
468  rpc->StubFragCount++;
469 
470  if (response->alloc_hint == StubLength)
471  {
472  pdu->Flags = RPC_PDU_FLAG_STUB;
473  pdu->Type = PTYPE_RESPONSE;
474  pdu->CallId = rpc->StubCallId;
475 
476  if (rpc_client_recv_pdu(rpc, pdu) < 0)
477  goto fail;
478  rpc_pdu_reset(pdu);
479  rpc->StubFragCount = 0;
480  rpc->StubCallId = 0;
481  }
482  }
483  else
484  {
485  const rpcconn_response_hdr_t* response = &header.response;
486  if (Stream_Length(fragment) < StubOffset + StubLength)
487  goto fail;
488  Stream_SetPosition(fragment, StubOffset);
489  rpc_client_receive_pipe_write(rpc->client, Stream_ConstPointer(fragment), StubLength);
490  rpc->StubFragCount++;
491 
492  if (response->alloc_hint == StubLength)
493  {
494  rpc->StubFragCount = 0;
495  rpc->StubCallId = 0;
496  }
497  }
498 
499  goto success;
500  }
501  else if (header.common.ptype == PTYPE_RTS)
502  {
503  if (rpc->State < RPC_CLIENT_STATE_CONTEXT_NEGOTIATED)
504  {
505  pdu->Flags = 0;
506  pdu->Type = header.common.ptype;
507  pdu->CallId = header.common.call_id;
508 
509  const size_t len = Stream_Length(fragment);
510  if (!Stream_EnsureCapacity(pdu->s, len))
511  goto fail;
512 
513  Stream_Write(pdu->s, Stream_Buffer(fragment), len);
514 
515  if (rpc_client_recv_pdu(rpc, pdu) < 0)
516  goto fail;
517 
518  rpc_pdu_reset(pdu);
519  }
520  else
521  {
522  if (!rts_recv_out_of_sequence_pdu(rpc, fragment, &header))
523  goto fail;
524  }
525 
526  goto success;
527  }
528  else if (header.common.ptype == PTYPE_BIND_ACK ||
529  header.common.ptype == PTYPE_ALTER_CONTEXT_RESP)
530  {
531  pdu->Flags = 0;
532  pdu->Type = header.common.ptype;
533  pdu->CallId = header.common.call_id;
534 
535  const size_t len = Stream_Length(fragment);
536  if (!Stream_EnsureCapacity(pdu->s, len))
537  goto fail;
538 
539  Stream_Write(pdu->s, Stream_Buffer(fragment), len);
540 
541  if (rpc_client_recv_pdu(rpc, pdu) < 0)
542  goto fail;
543 
544  rpc_pdu_reset(pdu);
545  goto success;
546  }
547  else if (header.common.ptype == PTYPE_FAULT)
548  {
549  const rpcconn_fault_hdr_t* fault = (const rpcconn_fault_hdr_t*)&header.fault;
550  rpc_recv_fault_pdu(fault->status);
551  goto fail;
552  }
553  else
554  {
555  WLog_ERR(TAG, "unexpected RPC PDU type 0x%02" PRIX8 "", header.common.ptype);
556  goto fail;
557  }
558 
559 success:
560  rc = (rc < 0) ? 1 : 0; /* In case of default error return change to 1, otherwise we already set
561  the return code */
562 fail:
563  rts_free_pdu_header(&header, FALSE);
564  return rc;
565 }
566 
567 static SSIZE_T rpc_client_default_out_channel_recv(rdpRpc* rpc)
568 {
569  SSIZE_T status = -1;
570  UINT32 statusCode = 0;
571  HttpResponse* response = NULL;
572  RpcInChannel* inChannel = NULL;
573  RpcOutChannel* outChannel = NULL;
574  HANDLE outChannelEvent = NULL;
575  RpcVirtualConnection* connection = rpc->VirtualConnection;
576  inChannel = connection->DefaultInChannel;
577  outChannel = connection->DefaultOutChannel;
578  BIO_get_event(outChannel->common.tls->bio, &outChannelEvent);
579 
580  if (outChannel->State < CLIENT_OUT_CHANNEL_STATE_OPENED)
581  {
582  if (WaitForSingleObject(outChannelEvent, 0) != WAIT_OBJECT_0)
583  return 1;
584 
585  response = http_response_recv(outChannel->common.tls, TRUE);
586 
587  if (!response)
588  return -1;
589 
590  if (outChannel->State == CLIENT_OUT_CHANNEL_STATE_SECURITY)
591  {
592  /* Receive OUT Channel Response */
593  if (!rpc_ncacn_http_recv_out_channel_response(&outChannel->common, response))
594  {
595  http_response_free(response);
596  WLog_ERR(TAG, "rpc_ncacn_http_recv_out_channel_response failure");
597  return -1;
598  }
599 
600  /* Send OUT Channel Request */
601 
602  if (!rpc_ncacn_http_send_out_channel_request(&outChannel->common, FALSE))
603  {
604  http_response_free(response);
605  WLog_ERR(TAG, "rpc_ncacn_http_send_out_channel_request failure");
606  return -1;
607  }
608 
609  if (rpc_ncacn_http_is_final_request(&outChannel->common))
610  {
611  rpc_ncacn_http_auth_uninit(&outChannel->common);
612  rpc_out_channel_transition_to_state(outChannel,
613  CLIENT_OUT_CHANNEL_STATE_NEGOTIATED);
614 
615  /* Send CONN/A1 PDU over OUT channel */
616 
617  if (!rts_send_CONN_A1_pdu(rpc))
618  {
619  http_response_free(response);
620  WLog_ERR(TAG, "rpc_send_CONN_A1_pdu error!");
621  return -1;
622  }
623 
624  rpc_out_channel_transition_to_state(outChannel, CLIENT_OUT_CHANNEL_STATE_OPENED);
625 
626  if (inChannel->State == CLIENT_IN_CHANNEL_STATE_OPENED)
627  {
628  rpc_virtual_connection_transition_to_state(
629  rpc, connection, VIRTUAL_CONNECTION_STATE_OUT_CHANNEL_WAIT);
630  }
631  }
632 
633  status = 1;
634  }
635 
636  http_response_free(response);
637  }
638  else if (connection->State == VIRTUAL_CONNECTION_STATE_OUT_CHANNEL_WAIT)
639  {
640  /* Receive OUT channel response */
641  if (WaitForSingleObject(outChannelEvent, 0) != WAIT_OBJECT_0)
642  return 1;
643 
644  response = http_response_recv(outChannel->common.tls, FALSE);
645 
646  if (!response)
647  return -1;
648 
649  statusCode = http_response_get_status_code(response);
650 
651  if (statusCode != HTTP_STATUS_OK)
652  {
653  http_response_log_error_status(WLog_Get(TAG), WLOG_ERROR, response);
654 
655  if (statusCode == HTTP_STATUS_DENIED)
656  {
657  rdpContext* context = transport_get_context(rpc->transport);
658  freerdp_set_last_error_if_not(context, FREERDP_ERROR_CONNECT_ACCESS_DENIED);
659  }
660 
661  http_response_free(response);
662  return -1;
663  }
664 
665  http_response_free(response);
666  rpc_virtual_connection_transition_to_state(rpc, rpc->VirtualConnection,
667  VIRTUAL_CONNECTION_STATE_WAIT_A3W);
668  status = 1;
669  }
670  else
671  {
672  wStream* fragment = rpc->client->ReceiveFragment;
673 
674  while (1)
675  {
676  size_t pos = 0;
677  rpcconn_common_hdr_t header = { 0 };
678 
679  while (Stream_GetPosition(fragment) < RPC_COMMON_FIELDS_LENGTH)
680  {
681  status = rpc_channel_read(&outChannel->common, fragment,
682  RPC_COMMON_FIELDS_LENGTH - Stream_GetPosition(fragment));
683 
684  if (status < 0)
685  return -1;
686 
687  if (Stream_GetPosition(fragment) < RPC_COMMON_FIELDS_LENGTH)
688  return 0;
689  }
690 
691  pos = Stream_GetPosition(fragment);
692  Stream_SetPosition(fragment, 0);
693 
694  /* Ignore errors, the PDU might not be complete. */
695  rts_read_common_pdu_header(fragment, &header, TRUE);
696  Stream_SetPosition(fragment, pos);
697 
698  if (header.frag_length > rpc->max_recv_frag)
699  {
700  WLog_ERR(TAG,
701  "rpc_client_recv: invalid fragment size: %" PRIu16 " (max: %" PRIu16 ")",
702  header.frag_length, rpc->max_recv_frag);
703  winpr_HexDump(TAG, WLOG_ERROR, Stream_Buffer(fragment),
704  Stream_GetPosition(fragment));
705  return -1;
706  }
707 
708  while (Stream_GetPosition(fragment) < header.frag_length)
709  {
710  status = rpc_channel_read(&outChannel->common, fragment,
711  header.frag_length - Stream_GetPosition(fragment));
712 
713  if (status < 0)
714  {
715  WLog_ERR(TAG, "error reading fragment body");
716  return -1;
717  }
718 
719  if (Stream_GetPosition(fragment) < header.frag_length)
720  return 0;
721  }
722 
723  {
724  /* complete fragment received */
725  status = rpc_client_recv_fragment(rpc, fragment);
726 
727  if (status < 0)
728  return status;
729 
730  /* channel recycling may update channel pointers */
731  if (outChannel->State == CLIENT_OUT_CHANNEL_STATE_RECYCLED &&
732  connection->NonDefaultOutChannel)
733  {
734  rpc_channel_free(&connection->DefaultOutChannel->common);
735  connection->DefaultOutChannel = connection->NonDefaultOutChannel;
736  connection->NonDefaultOutChannel = NULL;
737  rpc_out_channel_transition_to_state(connection->DefaultOutChannel,
738  CLIENT_OUT_CHANNEL_STATE_OPENED);
739  rpc_virtual_connection_transition_to_state(
740  rpc, connection, VIRTUAL_CONNECTION_STATE_OUT_CHANNEL_WAIT);
741  return 0;
742  }
743 
744  Stream_SetPosition(fragment, 0);
745  }
746  }
747  }
748 
749  return status;
750 }
751 
752 static SSIZE_T rpc_client_nondefault_out_channel_recv(rdpRpc* rpc)
753 {
754  SSIZE_T status = -1;
755  HttpResponse* response = NULL;
756  RpcOutChannel* nextOutChannel = NULL;
757  HANDLE nextOutChannelEvent = NULL;
758  nextOutChannel = rpc->VirtualConnection->NonDefaultOutChannel;
759  BIO_get_event(nextOutChannel->common.tls->bio, &nextOutChannelEvent);
760 
761  if (WaitForSingleObject(nextOutChannelEvent, 0) != WAIT_OBJECT_0)
762  return 1;
763 
764  response = http_response_recv(nextOutChannel->common.tls, TRUE);
765 
766  if (response)
767  {
768  switch (nextOutChannel->State)
769  {
770  case CLIENT_OUT_CHANNEL_STATE_SECURITY:
771  if (rpc_ncacn_http_recv_out_channel_response(&nextOutChannel->common, response))
772  {
773  if (rpc_ncacn_http_send_out_channel_request(&nextOutChannel->common, TRUE))
774  {
775  if (rpc_ncacn_http_is_final_request(&nextOutChannel->common))
776  {
777  rpc_ncacn_http_auth_uninit(&nextOutChannel->common);
778 
779  if (rts_send_OUT_R1_A3_pdu(rpc))
780  {
781  status = 1;
782  rpc_out_channel_transition_to_state(
783  nextOutChannel, CLIENT_OUT_CHANNEL_STATE_OPENED_A6W);
784  }
785  else
786  {
787  WLog_ERR(TAG, "rts_send_OUT_R1/A3_pdu failure");
788  }
789  }
790  else
791  {
792  status = 1;
793  }
794  }
795  else
796  {
797  WLog_ERR(TAG, "rpc_ncacn_http_send_out_channel_request failure");
798  }
799  }
800  else
801  {
802  WLog_ERR(TAG, "rpc_ncacn_http_recv_out_channel_response failure");
803  }
804 
805  break;
806 
807  case CLIENT_OUT_CHANNEL_STATE_INITIAL:
808  case CLIENT_OUT_CHANNEL_STATE_CONNECTED:
809  case CLIENT_OUT_CHANNEL_STATE_NEGOTIATED:
810  default:
811  WLog_ERR(TAG,
812  "rpc_client_nondefault_out_channel_recv: Unexpected message %08" PRIx32,
813  nextOutChannel->State);
814  status = -1;
815  }
816 
817  http_response_free(response);
818  }
819 
820  return status;
821 }
822 
823 int rpc_client_out_channel_recv(rdpRpc* rpc)
824 {
825  SSIZE_T status = 0;
826  RpcVirtualConnection* connection = rpc->VirtualConnection;
827 
828  if (connection->DefaultOutChannel)
829  {
830  status = rpc_client_default_out_channel_recv(rpc);
831 
832  if (status < 0)
833  return -1;
834  }
835 
836  if (connection->NonDefaultOutChannel)
837  {
838  status = rpc_client_nondefault_out_channel_recv(rpc);
839 
840  if (status < 0)
841  return -1;
842  }
843 
844  return 1;
845 }
846 
847 int rpc_client_in_channel_recv(rdpRpc* rpc)
848 {
849  int status = 1;
850  HttpResponse* response = NULL;
851  RpcInChannel* inChannel = NULL;
852  RpcOutChannel* outChannel = NULL;
853  HANDLE InChannelEvent = NULL;
854  RpcVirtualConnection* connection = rpc->VirtualConnection;
855  inChannel = connection->DefaultInChannel;
856  outChannel = connection->DefaultOutChannel;
857  BIO_get_event(inChannel->common.tls->bio, &InChannelEvent);
858 
859  if (WaitForSingleObject(InChannelEvent, 0) != WAIT_OBJECT_0)
860  return 1;
861 
862  if (inChannel->State < CLIENT_IN_CHANNEL_STATE_OPENED)
863  {
864  response = http_response_recv(inChannel->common.tls, TRUE);
865 
866  if (!response)
867  return -1;
868 
869  if (inChannel->State == CLIENT_IN_CHANNEL_STATE_SECURITY)
870  {
871  if (!rpc_ncacn_http_recv_in_channel_response(&inChannel->common, response))
872  {
873  WLog_ERR(TAG, "rpc_ncacn_http_recv_in_channel_response failure");
874  http_response_free(response);
875  return -1;
876  }
877 
878  /* Send IN Channel Request */
879 
880  if (!rpc_ncacn_http_send_in_channel_request(&inChannel->common))
881  {
882  WLog_ERR(TAG, "rpc_ncacn_http_send_in_channel_request failure");
883  http_response_free(response);
884  return -1;
885  }
886 
887  if (rpc_ncacn_http_is_final_request(&inChannel->common))
888  {
889  rpc_ncacn_http_auth_uninit(&inChannel->common);
890  rpc_in_channel_transition_to_state(inChannel, CLIENT_IN_CHANNEL_STATE_NEGOTIATED);
891 
892  /* Send CONN/B1 PDU over IN channel */
893 
894  if (!rts_send_CONN_B1_pdu(rpc))
895  {
896  WLog_ERR(TAG, "rpc_send_CONN_B1_pdu error!");
897  http_response_free(response);
898  return -1;
899  }
900 
901  rpc_in_channel_transition_to_state(inChannel, CLIENT_IN_CHANNEL_STATE_OPENED);
902 
903  if (outChannel->State == CLIENT_OUT_CHANNEL_STATE_OPENED)
904  {
905  rpc_virtual_connection_transition_to_state(
906  rpc, connection, VIRTUAL_CONNECTION_STATE_OUT_CHANNEL_WAIT);
907  }
908  }
909 
910  status = 1;
911  }
912 
913  http_response_free(response);
914  }
915  else
916  {
917  response = http_response_recv(inChannel->common.tls, TRUE);
918 
919  if (!response)
920  return -1;
921 
922  /* We can receive an unauthorized HTTP response on the IN channel */
923  http_response_free(response);
924  }
925 
926  return status;
927 }
928 
934 RpcClientCall* rpc_client_call_find_by_id(RpcClient* client, UINT32 CallId)
935 {
936  RpcClientCall* clientCall = NULL;
937 
938  if (!client)
939  return NULL;
940 
941  ArrayList_Lock(client->ClientCallList);
942  const size_t count = ArrayList_Count(client->ClientCallList);
943 
944  for (size_t index = 0; index < count; index++)
945  {
946  clientCall = (RpcClientCall*)ArrayList_GetItem(client->ClientCallList, index);
947 
948  if (clientCall->CallId == CallId)
949  break;
950  }
951 
952  ArrayList_Unlock(client->ClientCallList);
953  return clientCall;
954 }
955 
956 RpcClientCall* rpc_client_call_new(UINT32 CallId, UINT32 OpNum)
957 {
958  RpcClientCall* clientCall = NULL;
959  clientCall = (RpcClientCall*)calloc(1, sizeof(RpcClientCall));
960 
961  if (!clientCall)
962  return NULL;
963 
964  clientCall->CallId = CallId;
965  clientCall->OpNum = OpNum;
966  clientCall->State = RPC_CLIENT_CALL_STATE_SEND_PDUS;
967  return clientCall;
968 }
969 
970 void rpc_client_call_free(RpcClientCall* clientCall)
971 {
972  free(clientCall);
973 }
974 
975 static void rpc_array_client_call_free(void* call)
976 {
977  rpc_client_call_free((RpcClientCall*)call);
978 }
979 
980 int rpc_in_channel_send_pdu(RpcInChannel* inChannel, const BYTE* buffer, size_t length)
981 {
982  SSIZE_T status = 0;
983  RpcClientCall* clientCall = NULL;
984  wStream s;
985  rpcconn_common_hdr_t header = { 0 };
986 
987  status = rpc_channel_write(&inChannel->common, buffer, length);
988 
989  if (status <= 0)
990  return -1;
991 
992  Stream_StaticConstInit(&s, buffer, length);
993  if (!rts_read_common_pdu_header(&s, &header, FALSE))
994  return -1;
995 
996  clientCall = rpc_client_call_find_by_id(inChannel->common.client, header.call_id);
997  if (!clientCall)
998  return -1;
999 
1000  clientCall->State = RPC_CLIENT_CALL_STATE_DISPATCHED;
1001 
1002  /*
1003  * This protocol specifies that only RPC PDUs are subject to the flow control abstract
1004  * data model. RTS PDUs and the HTTP request and response headers are not subject to flow
1005  * control. Implementations of this protocol MUST NOT include them when computing any of the
1006  * variables specified by this abstract data model.
1007  */
1008 
1009  if (header.ptype == PTYPE_REQUEST)
1010  {
1011  inChannel->BytesSent += status;
1012  inChannel->SenderAvailableWindow -= status;
1013  }
1014 
1015  if (status > INT32_MAX)
1016  return -1;
1017  return (int)status;
1018 }
1019 
1020 BOOL rpc_client_write_call(rdpRpc* rpc, wStream* s, UINT16 opnum)
1021 {
1022  size_t offset = 0;
1023  BYTE* buffer = NULL;
1024  size_t stub_data_pad = 0;
1025  SecBuffer plaintext;
1026  SecBuffer ciphertext = { 0 };
1027  RpcClientCall* clientCall = NULL;
1028  rdpCredsspAuth* auth = NULL;
1029  rpcconn_request_hdr_t request_pdu = { 0 };
1030  RpcVirtualConnection* connection = NULL;
1031  RpcInChannel* inChannel = NULL;
1032  BOOL rc = FALSE;
1033 
1034  if (!s)
1035  return FALSE;
1036 
1037  if (!rpc)
1038  goto fail;
1039 
1040  auth = rpc->auth;
1041  connection = rpc->VirtualConnection;
1042 
1043  if (!auth)
1044  {
1045  WLog_ERR(TAG, "invalid auth context");
1046  goto fail;
1047  }
1048 
1049  if (!connection)
1050  goto fail;
1051 
1052  inChannel = connection->DefaultInChannel;
1053 
1054  if (!inChannel)
1055  goto fail;
1056 
1057  Stream_SealLength(s);
1058  const size_t length = Stream_Length(s);
1059  if (length > UINT32_MAX)
1060  goto fail;
1061 
1062  const size_t asize = credssp_auth_trailer_size(auth);
1063 
1064  request_pdu.header = rpc_pdu_header_init(rpc);
1065  request_pdu.header.ptype = PTYPE_REQUEST;
1066  request_pdu.header.pfc_flags = PFC_FIRST_FRAG | PFC_LAST_FRAG;
1067  request_pdu.header.auth_length = (UINT16)asize;
1068  request_pdu.header.call_id = rpc->CallId++;
1069  request_pdu.alloc_hint = (UINT32)length;
1070  request_pdu.p_cont_id = 0x0000;
1071  request_pdu.opnum = opnum;
1072  clientCall = rpc_client_call_new(request_pdu.header.call_id, request_pdu.opnum);
1073 
1074  if (!clientCall)
1075  goto fail;
1076 
1077  if (!ArrayList_Append(rpc->client->ClientCallList, clientCall))
1078  {
1079  rpc_client_call_free(clientCall);
1080  goto fail;
1081  }
1082 
1083  // NOLINTNEXTLINE(clang-analyzer-unix.Malloc): ArrayList_Append takes ownership of clientCall
1084  if (request_pdu.opnum == TsProxySetupReceivePipeOpnum)
1085  rpc->PipeCallId = request_pdu.header.call_id;
1086 
1087  request_pdu.stub_data = Stream_Buffer(s);
1088  offset = 24;
1089  stub_data_pad = rpc_offset_align(&offset, 8);
1090  offset += length;
1091  request_pdu.auth_verifier.auth_pad_length = rpc_offset_align(&offset, 4);
1092  request_pdu.auth_verifier.auth_type =
1093  rpc_auth_pkg_to_security_provider(credssp_auth_pkg_name(rpc->auth));
1094  request_pdu.auth_verifier.auth_level = RPC_C_AUTHN_LEVEL_PKT_INTEGRITY;
1095  request_pdu.auth_verifier.auth_reserved = 0x00;
1096  request_pdu.auth_verifier.auth_context_id = 0x00000000;
1097  offset += (8 + request_pdu.header.auth_length);
1098 
1099  if (offset > UINT32_MAX)
1100  goto fail;
1101  request_pdu.header.frag_length = (UINT32)offset;
1102  buffer = (BYTE*)calloc(1, request_pdu.header.frag_length);
1103 
1104  if (!buffer)
1105  goto fail;
1106 
1107  CopyMemory(buffer, &request_pdu, 24);
1108  offset = 24;
1109  rpc_offset_pad(&offset, stub_data_pad);
1110  CopyMemory(&buffer[offset], request_pdu.stub_data, length);
1111  offset += length;
1112  rpc_offset_pad(&offset, request_pdu.auth_verifier.auth_pad_length);
1113  CopyMemory(&buffer[offset], &request_pdu.auth_verifier.auth_type, 8);
1114  offset += 8;
1115 
1116  if (offset > UINT32_MAX)
1117  goto fail;
1118 
1119  plaintext.pvBuffer = buffer;
1120  plaintext.cbBuffer = (UINT32)offset;
1121  plaintext.BufferType = SECBUFFER_READONLY;
1122 
1123  size_t size = 0;
1124  if (!credssp_auth_encrypt(auth, &plaintext, &ciphertext, &size, rpc->SendSeqNum++))
1125  goto fail;
1126 
1127  CopyMemory(&buffer[offset], ciphertext.pvBuffer, size);
1128  offset += size;
1129 
1130  sspi_SecBufferFree(&ciphertext);
1131 
1132  if (rpc_in_channel_send_pdu(inChannel, buffer, request_pdu.header.frag_length) < 0)
1133  goto fail;
1134 
1135  rc = TRUE;
1136 fail:
1137  free(buffer);
1138  Stream_Free(s, TRUE);
1139  return rc;
1140 }
1141 
1142 static BOOL rpc_client_resolve_gateway(rdpSettings* settings, char** host, UINT16* port,
1143  BOOL* isProxy)
1144 {
1145  struct addrinfo* result = NULL;
1146 
1147  if (!settings || !host || !port || !isProxy)
1148  return FALSE;
1149  else
1150  {
1151  const char* peerHostname = freerdp_settings_get_string(settings, FreeRDP_GatewayHostname);
1152  const char* proxyUsername = freerdp_settings_get_string(settings, FreeRDP_GatewayUsername);
1153  const char* proxyPassword = freerdp_settings_get_string(settings, FreeRDP_GatewayPassword);
1154  *port = (UINT16)freerdp_settings_get_uint32(settings, FreeRDP_GatewayPort);
1155  *isProxy = proxy_prepare(settings, &peerHostname, port, &proxyUsername, &proxyPassword);
1156  result = freerdp_tcp_resolve_host(peerHostname, *port, 0);
1157 
1158  if (!result)
1159  return FALSE;
1160 
1161  *host =
1162  freerdp_tcp_address_to_string((const struct sockaddr_storage*)result->ai_addr, NULL);
1163  freeaddrinfo(result);
1164  return TRUE;
1165  }
1166 }
1167 
1168 RpcClient* rpc_client_new(rdpContext* context, UINT32 max_recv_frag)
1169 {
1170  wObject* obj = NULL;
1171  RpcClient* client = (RpcClient*)calloc(1, sizeof(RpcClient));
1172 
1173  if (!client)
1174  return NULL;
1175 
1176  if (!rpc_client_resolve_gateway(context->settings, &client->host, &client->port,
1177  &client->isProxy))
1178  goto fail;
1179 
1180  client->context = context;
1181 
1182  if (!client->context)
1183  goto fail;
1184 
1185  client->pdu = rpc_pdu_new();
1186 
1187  if (!client->pdu)
1188  goto fail;
1189 
1190  client->ReceiveFragment = Stream_New(NULL, max_recv_frag);
1191 
1192  if (!client->ReceiveFragment)
1193  goto fail;
1194 
1195  client->PipeEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1196 
1197  if (!client->PipeEvent)
1198  goto fail;
1199 
1200  if (!ringbuffer_init(&(client->ReceivePipe), 4096))
1201  goto fail;
1202 
1203  if (!InitializeCriticalSectionAndSpinCount(&(client->PipeLock), 4000))
1204  goto fail;
1205 
1206  client->ClientCallList = ArrayList_New(TRUE);
1207 
1208  if (!client->ClientCallList)
1209  goto fail;
1210 
1211  obj = ArrayList_Object(client->ClientCallList);
1212  obj->fnObjectFree = rpc_array_client_call_free;
1213  return client;
1214 fail:
1215  WINPR_PRAGMA_DIAG_PUSH
1216  WINPR_PRAGMA_DIAG_IGNORED_MISMATCHED_DEALLOC
1217  rpc_client_free(client);
1218  WINPR_PRAGMA_DIAG_POP
1219  return NULL;
1220 }
1221 
1222 void rpc_client_free(RpcClient* client)
1223 {
1224  if (!client)
1225  return;
1226 
1227  free(client->host);
1228 
1229  if (client->ReceiveFragment)
1230  Stream_Free(client->ReceiveFragment, TRUE);
1231 
1232  if (client->PipeEvent)
1233  (void)CloseHandle(client->PipeEvent);
1234 
1235  ringbuffer_destroy(&(client->ReceivePipe));
1236  DeleteCriticalSection(&(client->PipeLock));
1237 
1238  if (client->pdu)
1239  rpc_pdu_free(client->pdu);
1240 
1241  if (client->ClientCallList)
1242  ArrayList_Free(client->ClientCallList);
1243 
1244  free(client);
1245 }
FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.
a piece of data in the ring buffer, exactly like a glibc iovec
Definition: ringbuffer.h:44
This struct contains function pointer to initialize/free objects.
Definition: collections.h:57