Coverage Report

Created: 2025-07-01 06:46

/src/FreeRDP/libfreerdp/core/childsession.c
Line
Count
Source (jump to first uncovered line)
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Named pipe transport
4
 *
5
 * Copyright 2023-2024 David Fort <contact@hardening-consulting.com>
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
20
#include "tcp.h"
21
22
#include <winpr/library.h>
23
#include <winpr/assert.h>
24
#include <winpr/print.h>
25
#include <winpr/sysinfo.h>
26
27
#include <freerdp/utils/ringbuffer.h>
28
29
#include "childsession.h"
30
31
#define TAG FREERDP_TAG("childsession")
32
33
typedef struct
34
{
35
  OVERLAPPED readOverlapped;
36
  HANDLE hFile;
37
  BOOL opInProgress;
38
  BOOL lastOpClosed;
39
  RingBuffer readBuffer;
40
  BOOL blocking;
41
  BYTE tmpReadBuffer[4096];
42
43
  HANDLE readEvent;
44
} WINPR_BIO_NAMED;
45
46
static int transport_bio_named_uninit(BIO* bio);
47
48
static int transport_bio_named_write(BIO* bio, const char* buf, int size)
49
0
{
50
0
  WINPR_ASSERT(bio);
51
0
  WINPR_ASSERT(buf);
52
53
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
54
55
0
  if (!buf)
56
0
    return 0;
57
58
0
  BIO_clear_flags(bio, BIO_FLAGS_WRITE);
59
0
  DWORD written = 0;
60
61
0
  UINT64 start = GetTickCount64();
62
0
  BOOL ret = WriteFile(ptr->hFile, buf, WINPR_ASSERTING_INT_CAST(uint32_t, size), &written, NULL);
63
  // winpr_HexDump(TAG, WLOG_DEBUG, buf, size);
64
65
0
  if (!ret)
66
0
  {
67
0
    WLog_VRB(TAG, "error or deferred");
68
0
    return 0;
69
0
  }
70
71
0
  WLog_VRB(TAG, "(%d)=%d written=%d duration=%d", size, ret, written, GetTickCount64() - start);
72
73
0
  if (written == 0)
74
0
  {
75
0
    WLog_VRB(TAG, "closed on write");
76
0
    return 0;
77
0
  }
78
79
0
  WINPR_ASSERT(written <= INT32_MAX);
80
0
  return (int)written;
81
0
}
82
83
static BOOL treatReadResult(WINPR_BIO_NAMED* ptr, DWORD readBytes)
84
0
{
85
0
  WLog_VRB(TAG, "treatReadResult(readBytes=%" PRIu32 ")", readBytes);
86
0
  ptr->opInProgress = FALSE;
87
0
  if (readBytes == 0)
88
0
  {
89
0
    WLog_VRB(TAG, "readBytes == 0");
90
0
    return TRUE;
91
0
  }
92
93
0
  if (!ringbuffer_write(&ptr->readBuffer, ptr->tmpReadBuffer, readBytes))
94
0
  {
95
0
    WLog_VRB(TAG, "ringbuffer_write()");
96
0
    return FALSE;
97
0
  }
98
99
0
  return SetEvent(ptr->readEvent);
100
0
}
101
102
static BOOL doReadOp(WINPR_BIO_NAMED* ptr)
103
0
{
104
0
  DWORD readBytes = 0;
105
106
0
  if (!ResetEvent(ptr->readEvent))
107
0
    return FALSE;
108
109
0
  ptr->opInProgress = TRUE;
110
0
  if (!ReadFile(ptr->hFile, ptr->tmpReadBuffer, sizeof(ptr->tmpReadBuffer), &readBytes,
111
0
                &ptr->readOverlapped))
112
0
  {
113
0
    DWORD error = GetLastError();
114
0
    switch (error)
115
0
    {
116
0
      case ERROR_NO_DATA:
117
0
        WLog_VRB(TAG, "No Data, unexpected");
118
0
        return TRUE;
119
0
      case ERROR_IO_PENDING:
120
0
        WLog_VRB(TAG, "ERROR_IO_PENDING");
121
0
        return TRUE;
122
0
      case ERROR_BROKEN_PIPE:
123
0
        WLog_VRB(TAG, "broken pipe");
124
0
        ptr->lastOpClosed = TRUE;
125
0
        return TRUE;
126
0
      default:
127
0
        return FALSE;
128
0
    }
129
0
  }
130
131
0
  return treatReadResult(ptr, readBytes);
132
0
}
133
134
static int transport_bio_named_read(BIO* bio, char* buf, int size)
135
0
{
136
0
  WINPR_ASSERT(bio);
137
0
  WINPR_ASSERT(buf);
138
139
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
140
0
  if (!buf)
141
0
    return 0;
142
143
0
  BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_READ);
144
145
0
  if (ptr->blocking)
146
0
  {
147
0
    while (!ringbuffer_used(&ptr->readBuffer))
148
0
    {
149
0
      if (ptr->lastOpClosed)
150
0
        return 0;
151
152
0
      if (ptr->opInProgress)
153
0
      {
154
0
        DWORD status = WaitForSingleObjectEx(ptr->readEvent, 500, TRUE);
155
0
        switch (status)
156
0
        {
157
0
          case WAIT_TIMEOUT:
158
0
          case WAIT_IO_COMPLETION:
159
0
            continue;
160
0
          case WAIT_OBJECT_0:
161
0
            break;
162
0
          default:
163
0
            return -1;
164
0
        }
165
166
0
        DWORD readBytes = 0;
167
0
        if (!GetOverlappedResult(ptr->hFile, &ptr->readOverlapped, &readBytes, FALSE))
168
0
        {
169
0
          WLog_ERR(TAG, "GetOverlappedResult blocking(lastError=%" PRIu32 ")",
170
0
                   GetLastError());
171
0
          return -1;
172
0
        }
173
174
0
        if (!treatReadResult(ptr, readBytes))
175
0
        {
176
0
          WLog_ERR(TAG, "treatReadResult blocking");
177
0
          return -1;
178
0
        }
179
0
      }
180
0
    }
181
0
  }
182
0
  else
183
0
  {
184
0
    if (ptr->opInProgress)
185
0
    {
186
0
      DWORD status = WaitForSingleObject(ptr->readEvent, 0);
187
0
      switch (status)
188
0
      {
189
0
        case WAIT_OBJECT_0:
190
0
          break;
191
0
        case WAIT_TIMEOUT:
192
0
          BIO_set_flags(bio, (BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_READ));
193
0
          return -1;
194
0
        default:
195
0
          WLog_ERR(TAG, "error WaitForSingleObject(readEvent)=0x%" PRIx32 "", status);
196
0
          return -1;
197
0
      }
198
199
0
      DWORD readBytes = 0;
200
0
      if (!GetOverlappedResult(ptr->hFile, &ptr->readOverlapped, &readBytes, FALSE))
201
0
      {
202
0
        WLog_ERR(TAG, "GetOverlappedResult non blocking(lastError=%" PRIu32 ")",
203
0
                 GetLastError());
204
0
        return -1;
205
0
      }
206
207
0
      if (!treatReadResult(ptr, readBytes))
208
0
      {
209
0
        WLog_ERR(TAG, "error treatReadResult non blocking");
210
0
        return -1;
211
0
      }
212
0
    }
213
0
  }
214
215
0
  SSIZE_T ret = -1;
216
0
  if (size >= 0)
217
0
  {
218
0
    size_t rsize = ringbuffer_used(&ptr->readBuffer);
219
0
    if (rsize <= SSIZE_MAX)
220
0
      ret = MIN(size, (SSIZE_T)rsize);
221
0
  }
222
0
  if ((size >= 0) && ret)
223
0
  {
224
0
    DataChunk chunks[2] = { 0 };
225
0
    const int nchunks =
226
0
        ringbuffer_peek(&ptr->readBuffer, chunks, WINPR_ASSERTING_INT_CAST(size_t, ret));
227
0
    for (int i = 0; i < nchunks; i++)
228
0
    {
229
0
      memcpy(buf, chunks[i].data, chunks[i].size);
230
0
      buf += chunks[i].size;
231
0
    }
232
233
0
    ringbuffer_commit_read_bytes(&ptr->readBuffer, WINPR_ASSERTING_INT_CAST(size_t, ret));
234
235
0
    WLog_VRB(TAG, "(%d)=%" PRIdz " nchunks=%d", size, ret, nchunks);
236
0
  }
237
238
0
  if (!ringbuffer_used(&ptr->readBuffer))
239
0
  {
240
0
    if (!ptr->opInProgress && !doReadOp(ptr))
241
0
    {
242
0
      WLog_ERR(TAG, "error rearming read");
243
0
      return -1;
244
0
    }
245
0
  }
246
247
0
  if (ret <= 0)
248
0
    BIO_set_flags(bio, (BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_READ));
249
250
0
  WINPR_ASSERT(ret <= INT32_MAX);
251
0
  return (int)ret;
252
0
}
253
254
static int transport_bio_named_puts(BIO* bio, const char* str)
255
0
{
256
0
  WINPR_ASSERT(bio);
257
0
  WINPR_ASSERT(str);
258
259
0
  return transport_bio_named_write(bio, str, (int)strnlen(str, INT32_MAX));
260
0
}
261
262
static int transport_bio_named_gets(BIO* bio, char* str, int size)
263
0
{
264
0
  WINPR_ASSERT(bio);
265
0
  WINPR_ASSERT(str);
266
267
0
  return transport_bio_named_read(bio, str, size);
268
0
}
269
270
static long transport_bio_named_ctrl(BIO* bio, int cmd, long arg1, void* arg2)
271
0
{
272
0
  WINPR_ASSERT(bio);
273
274
0
  int status = -1;
275
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
276
277
0
  switch (cmd)
278
0
  {
279
0
    case BIO_C_SET_SOCKET:
280
0
    case BIO_C_GET_SOCKET:
281
0
      return -1;
282
0
    case BIO_C_GET_EVENT:
283
0
      if (!BIO_get_init(bio) || !arg2)
284
0
        return 0;
285
286
0
      *((HANDLE*)arg2) = ptr->readEvent;
287
0
      return 1;
288
0
    case BIO_C_SET_HANDLE:
289
0
      BIO_set_init(bio, 1);
290
0
      if (!BIO_get_init(bio) || !arg2)
291
0
        return 0;
292
293
0
      ptr->hFile = (HANDLE)arg2;
294
0
      ptr->blocking = TRUE;
295
0
      if (!doReadOp(ptr))
296
0
        return -1;
297
0
      return 1;
298
0
    case BIO_C_SET_NONBLOCK:
299
0
    {
300
0
      WLog_DBG(TAG, "BIO_C_SET_NONBLOCK");
301
0
      ptr->blocking = FALSE;
302
0
      return 1;
303
0
    }
304
0
    case BIO_C_WAIT_READ:
305
0
    {
306
0
      WLog_DBG(TAG, "BIO_C_WAIT_READ");
307
0
      return 1;
308
0
    }
309
310
0
    case BIO_C_WAIT_WRITE:
311
0
    {
312
0
      WLog_DBG(TAG, "BIO_C_WAIT_WRITE");
313
0
      return 1;
314
0
    }
315
316
0
    default:
317
0
      break;
318
0
  }
319
320
0
  switch (cmd)
321
0
  {
322
0
    case BIO_CTRL_GET_CLOSE:
323
0
      status = BIO_get_shutdown(bio);
324
0
      break;
325
326
0
    case BIO_CTRL_SET_CLOSE:
327
0
      BIO_set_shutdown(bio, (int)arg1);
328
0
      status = 1;
329
0
      break;
330
331
0
    case BIO_CTRL_DUP:
332
0
      status = 1;
333
0
      break;
334
335
0
    case BIO_CTRL_FLUSH:
336
0
      status = 1;
337
0
      break;
338
339
0
    default:
340
0
      status = 0;
341
0
      break;
342
0
  }
343
344
0
  return status;
345
0
}
346
347
static void BIO_NAMED_free(WINPR_BIO_NAMED* ptr)
348
0
{
349
0
  if (!ptr)
350
0
    return;
351
352
0
  if (ptr->hFile)
353
0
  {
354
0
    (void)CloseHandle(ptr->hFile);
355
0
    ptr->hFile = NULL;
356
0
  }
357
358
0
  if (ptr->readEvent)
359
0
  {
360
0
    (void)CloseHandle(ptr->readEvent);
361
0
    ptr->readEvent = NULL;
362
0
  }
363
364
0
  ringbuffer_destroy(&ptr->readBuffer);
365
0
  free(ptr);
366
0
}
367
368
static int transport_bio_named_uninit(BIO* bio)
369
0
{
370
0
  WINPR_ASSERT(bio);
371
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
372
373
0
  BIO_NAMED_free(ptr);
374
375
0
  BIO_set_init(bio, 0);
376
0
  BIO_set_flags(bio, 0);
377
0
  return 1;
378
0
}
379
380
static int transport_bio_named_new(BIO* bio)
381
0
{
382
0
  WINPR_ASSERT(bio);
383
384
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)calloc(1, sizeof(WINPR_BIO_NAMED));
385
0
  if (!ptr)
386
0
    return 0;
387
388
0
  if (!ringbuffer_init(&ptr->readBuffer, 0xfffff))
389
0
    goto error;
390
391
0
  ptr->readEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
392
0
  if (!ptr->readEvent || ptr->readEvent == INVALID_HANDLE_VALUE)
393
0
    goto error;
394
395
0
  ptr->readOverlapped.hEvent = ptr->readEvent;
396
397
0
  BIO_set_data(bio, ptr);
398
0
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
399
0
  return 1;
400
401
0
error:
402
0
  BIO_NAMED_free(ptr);
403
0
  return 0;
404
0
}
405
406
static int transport_bio_named_free(BIO* bio)
407
0
{
408
0
  WINPR_BIO_NAMED* ptr = NULL;
409
410
0
  if (!bio)
411
0
    return 0;
412
413
0
  transport_bio_named_uninit(bio);
414
415
0
  ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
416
0
  if (ptr)
417
0
    BIO_set_data(bio, NULL);
418
419
0
  return 1;
420
0
}
421
422
static BIO_METHOD* BIO_s_namedpipe(void)
423
0
{
424
0
  static BIO_METHOD* bio_methods = NULL;
425
426
0
  if (bio_methods == NULL)
427
0
  {
428
0
    if (!(bio_methods = BIO_meth_new(BIO_TYPE_NAMEDPIPE, "NamedPipe")))
429
0
      return NULL;
430
431
0
    BIO_meth_set_write(bio_methods, transport_bio_named_write);
432
0
    BIO_meth_set_read(bio_methods, transport_bio_named_read);
433
0
    BIO_meth_set_puts(bio_methods, transport_bio_named_puts);
434
0
    BIO_meth_set_gets(bio_methods, transport_bio_named_gets);
435
0
    BIO_meth_set_ctrl(bio_methods, transport_bio_named_ctrl);
436
0
    BIO_meth_set_create(bio_methods, transport_bio_named_new);
437
0
    BIO_meth_set_destroy(bio_methods, transport_bio_named_free);
438
0
  }
439
440
0
  return bio_methods;
441
0
}
442
443
typedef NTSTATUS (*WinStationCreateChildSessionTransportFn)(WCHAR* path, DWORD len);
444
static BOOL createChildSessionTransport(HANDLE* pFile)
445
0
{
446
0
  WINPR_ASSERT(pFile);
447
448
0
  HANDLE hModule = NULL;
449
0
  BOOL ret = FALSE;
450
0
  *pFile = INVALID_HANDLE_VALUE;
451
452
0
  BOOL childEnabled = 0;
453
0
  if (!WTSIsChildSessionsEnabled(&childEnabled))
454
0
  {
455
0
    WLog_ERR(TAG, "error when calling WTSIsChildSessionsEnabled");
456
0
    goto out;
457
0
  }
458
459
0
  if (!childEnabled)
460
0
  {
461
0
    WLog_INFO(TAG, "child sessions aren't enabled");
462
0
    if (!WTSEnableChildSessions(TRUE))
463
0
    {
464
0
      WLog_ERR(TAG, "error when calling WTSEnableChildSessions");
465
0
      goto out;
466
0
    }
467
0
    WLog_INFO(TAG, "successfully enabled child sessions");
468
0
  }
469
470
0
  hModule = LoadLibraryA("winsta.dll");
471
0
  if (!hModule)
472
0
    return FALSE;
473
0
  WCHAR pipePath[0x80] = { 0 };
474
0
  char pipePathA[0x80] = { 0 };
475
476
0
  WinStationCreateChildSessionTransportFn createChildSessionFn = GetProcAddressAs(
477
0
      hModule, "WinStationCreateChildSessionTransport", WinStationCreateChildSessionTransportFn);
478
0
  if (!createChildSessionFn)
479
0
  {
480
0
    WLog_ERR(TAG, "unable to retrieve WinStationCreateChildSessionTransport function");
481
0
    goto out;
482
0
  }
483
484
0
  HRESULT hStatus = createChildSessionFn(pipePath, 0x80);
485
0
  if (!SUCCEEDED(hStatus))
486
0
  {
487
0
    WLog_ERR(TAG, "error 0x%x when creating childSessionTransport", hStatus);
488
0
    goto out;
489
0
  }
490
491
0
  const BYTE startOfPath[] = { '\\', 0, '\\', 0, '.', 0, '\\', 0 };
492
0
  if (_wcsncmp(pipePath, (const WCHAR*)startOfPath, 4))
493
0
  {
494
    /* when compiled under 32 bits, the path may miss "\\.\" at the beginning of the string
495
     * so add it if it's not there
496
     */
497
0
    size_t len = _wcslen(pipePath);
498
0
    if (len > 0x80 - (4 + 1))
499
0
    {
500
0
      WLog_ERR(TAG, "pipePath is too long to be adjusted");
501
0
      goto out;
502
0
    }
503
504
0
    memmove(pipePath + 4, pipePath, (len + 1) * sizeof(WCHAR));
505
0
    memcpy(pipePath, startOfPath, 8);
506
0
  }
507
508
0
  (void)ConvertWCharNToUtf8(pipePath, 0x80, pipePathA, sizeof(pipePathA));
509
0
  WLog_DBG(TAG, "child session is at '%s'", pipePathA);
510
511
0
  HANDLE f = CreateFileW(pipePath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
512
0
                         FILE_FLAG_OVERLAPPED, NULL);
513
0
  if (f == INVALID_HANDLE_VALUE)
514
0
  {
515
0
    WLog_ERR(TAG, "error when connecting to local named pipe");
516
0
    goto out;
517
0
  }
518
519
0
  *pFile = f;
520
0
  ret = TRUE;
521
522
0
out:
523
0
  FreeLibrary(hModule);
524
0
  return ret;
525
0
}
526
527
BIO* createChildSessionBio(void)
528
0
{
529
0
  HANDLE f = INVALID_HANDLE_VALUE;
530
0
  if (!createChildSessionTransport(&f))
531
0
    return NULL;
532
533
0
  BIO* lowLevelBio = BIO_new(BIO_s_namedpipe());
534
0
  if (!lowLevelBio)
535
0
  {
536
0
    (void)CloseHandle(f);
537
0
    return NULL;
538
0
  }
539
540
0
  BIO_set_handle(lowLevelBio, f);
541
0
  BIO* bufferedBio = BIO_new(BIO_s_buffered_socket());
542
543
0
  if (!bufferedBio)
544
0
  {
545
0
    BIO_free_all(lowLevelBio);
546
0
    return NULL;
547
0
  }
548
549
0
  bufferedBio = BIO_push(bufferedBio, lowLevelBio);
550
551
0
  return bufferedBio;
552
0
}