Coverage Report

Created: 2026-02-26 06:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/libfreerdp/core/childsession.c
Line
Count
Source
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
  const 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=%" PRIu32 " duration=%" PRIu64, size, ret, written,
72
0
           GetTickCount64() - start);
73
74
0
  if (written == 0)
75
0
  {
76
0
    WLog_VRB(TAG, "closed on write");
77
0
    return 0;
78
0
  }
79
80
0
  WINPR_ASSERT(written <= INT32_MAX);
81
0
  return (int)written;
82
0
}
83
84
static BOOL treatReadResult(WINPR_BIO_NAMED* ptr, DWORD readBytes)
85
0
{
86
0
  WLog_VRB(TAG, "treatReadResult(readBytes=%" PRIu32 ")", readBytes);
87
0
  ptr->opInProgress = FALSE;
88
0
  if (readBytes == 0)
89
0
  {
90
0
    WLog_VRB(TAG, "readBytes == 0");
91
0
    return TRUE;
92
0
  }
93
94
0
  if (!ringbuffer_write(&ptr->readBuffer, ptr->tmpReadBuffer, readBytes))
95
0
  {
96
0
    WLog_VRB(TAG, "ringbuffer_write()");
97
0
    return FALSE;
98
0
  }
99
100
0
  return SetEvent(ptr->readEvent);
101
0
}
102
103
static BOOL doReadOp(WINPR_BIO_NAMED* ptr)
104
0
{
105
0
  DWORD readBytes = 0;
106
107
0
  if (!ResetEvent(ptr->readEvent))
108
0
    return FALSE;
109
110
0
  ptr->opInProgress = TRUE;
111
0
  if (!ReadFile(ptr->hFile, ptr->tmpReadBuffer, sizeof(ptr->tmpReadBuffer), &readBytes,
112
0
                &ptr->readOverlapped))
113
0
  {
114
0
    DWORD error = GetLastError();
115
0
    switch (error)
116
0
    {
117
0
      case ERROR_NO_DATA:
118
0
        WLog_VRB(TAG, "No Data, unexpected");
119
0
        return TRUE;
120
0
      case ERROR_IO_PENDING:
121
0
        WLog_VRB(TAG, "ERROR_IO_PENDING");
122
0
        return TRUE;
123
0
      case ERROR_BROKEN_PIPE:
124
0
        WLog_VRB(TAG, "broken pipe");
125
0
        ptr->lastOpClosed = TRUE;
126
0
        return TRUE;
127
0
      default:
128
0
        return FALSE;
129
0
    }
130
0
  }
131
132
0
  return treatReadResult(ptr, readBytes);
133
0
}
134
135
static int transport_bio_named_read(BIO* bio, char* buf, int size)
136
0
{
137
0
  WINPR_ASSERT(bio);
138
0
  WINPR_ASSERT(buf);
139
140
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
141
0
  if (!buf)
142
0
    return 0;
143
144
0
  BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_READ);
145
146
0
  if (ptr->blocking)
147
0
  {
148
0
    while (!ringbuffer_used(&ptr->readBuffer))
149
0
    {
150
0
      if (ptr->lastOpClosed)
151
0
        return 0;
152
153
0
      if (ptr->opInProgress)
154
0
      {
155
0
        DWORD status = WaitForSingleObjectEx(ptr->readEvent, 500, TRUE);
156
0
        switch (status)
157
0
        {
158
0
          case WAIT_TIMEOUT:
159
0
          case WAIT_IO_COMPLETION:
160
0
            continue;
161
0
          case WAIT_OBJECT_0:
162
0
            break;
163
0
          default:
164
0
            return -1;
165
0
        }
166
167
0
        DWORD readBytes = 0;
168
0
        if (!GetOverlappedResult(ptr->hFile, &ptr->readOverlapped, &readBytes, FALSE))
169
0
        {
170
0
          WLog_ERR(TAG, "GetOverlappedResult blocking(lastError=%" PRIu32 ")",
171
0
                   GetLastError());
172
0
          return -1;
173
0
        }
174
175
0
        if (!treatReadResult(ptr, readBytes))
176
0
        {
177
0
          WLog_ERR(TAG, "treatReadResult blocking");
178
0
          return -1;
179
0
        }
180
0
      }
181
0
    }
182
0
  }
183
0
  else
184
0
  {
185
0
    if (ptr->opInProgress)
186
0
    {
187
0
      DWORD status = WaitForSingleObject(ptr->readEvent, 0);
188
0
      switch (status)
189
0
      {
190
0
        case WAIT_OBJECT_0:
191
0
          break;
192
0
        case WAIT_TIMEOUT:
193
0
          BIO_set_flags(bio, (BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_READ));
194
0
          return -1;
195
0
        default:
196
0
          WLog_ERR(TAG, "error WaitForSingleObject(readEvent)=0x%" PRIx32 "", status);
197
0
          return -1;
198
0
      }
199
200
0
      DWORD readBytes = 0;
201
0
      if (!GetOverlappedResult(ptr->hFile, &ptr->readOverlapped, &readBytes, FALSE))
202
0
      {
203
0
        WLog_ERR(TAG, "GetOverlappedResult non blocking(lastError=%" PRIu32 ")",
204
0
                 GetLastError());
205
0
        return -1;
206
0
      }
207
208
0
      if (!treatReadResult(ptr, readBytes))
209
0
      {
210
0
        WLog_ERR(TAG, "error treatReadResult non blocking");
211
0
        return -1;
212
0
      }
213
0
    }
214
0
  }
215
216
0
  SSIZE_T ret = -1;
217
0
  if (size >= 0)
218
0
  {
219
0
    size_t rsize = ringbuffer_used(&ptr->readBuffer);
220
0
    if (rsize <= SSIZE_MAX)
221
0
      ret = MIN(size, (SSIZE_T)rsize);
222
0
  }
223
0
  if ((size >= 0) && ret)
224
0
  {
225
0
    DataChunk chunks[2] = WINPR_C_ARRAY_INIT;
226
0
    const int nchunks =
227
0
        ringbuffer_peek(&ptr->readBuffer, chunks, WINPR_ASSERTING_INT_CAST(size_t, ret));
228
0
    for (int i = 0; i < nchunks; i++)
229
0
    {
230
0
      memcpy(buf, chunks[i].data, chunks[i].size);
231
0
      buf += chunks[i].size;
232
0
    }
233
234
0
    ringbuffer_commit_read_bytes(&ptr->readBuffer, WINPR_ASSERTING_INT_CAST(size_t, ret));
235
236
0
    WLog_VRB(TAG, "(%d)=%" PRIdz " nchunks=%d", size, ret, nchunks);
237
0
  }
238
239
0
  if (!ringbuffer_used(&ptr->readBuffer))
240
0
  {
241
0
    if (!ptr->opInProgress && !doReadOp(ptr))
242
0
    {
243
0
      WLog_ERR(TAG, "error rearming read");
244
0
      return -1;
245
0
    }
246
0
  }
247
248
0
  if (ret <= 0)
249
0
    BIO_set_flags(bio, (BIO_FLAGS_SHOULD_RETRY | BIO_FLAGS_READ));
250
251
0
  WINPR_ASSERT(ret <= INT32_MAX);
252
0
  return (int)ret;
253
0
}
254
255
static int transport_bio_named_puts(BIO* bio, const char* str)
256
0
{
257
0
  WINPR_ASSERT(bio);
258
0
  WINPR_ASSERT(str);
259
260
0
  const size_t max = (INT_MAX > SIZE_MAX) ? SIZE_MAX : INT_MAX;
261
0
  const size_t len = strnlen(str, max);
262
0
  if (len >= max)
263
0
    return -1;
264
0
  return transport_bio_named_write(bio, str, WINPR_ASSERTING_INT_CAST(int, len));
265
0
}
266
267
static int transport_bio_named_gets(BIO* bio, char* str, int size)
268
0
{
269
0
  WINPR_ASSERT(bio);
270
0
  WINPR_ASSERT(str);
271
272
0
  return transport_bio_named_read(bio, str, size);
273
0
}
274
275
static long transport_bio_named_ctrl(BIO* bio, int cmd, long arg1, void* arg2)
276
0
{
277
0
  WINPR_ASSERT(bio);
278
279
0
  int status = -1;
280
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
281
282
0
  switch (cmd)
283
0
  {
284
0
    case BIO_C_SET_SOCKET:
285
0
    case BIO_C_GET_SOCKET:
286
0
      return -1;
287
0
    case BIO_C_GET_EVENT:
288
0
      if (!BIO_get_init(bio) || !arg2)
289
0
        return 0;
290
291
0
      *((HANDLE*)arg2) = ptr->readEvent;
292
0
      return 1;
293
0
    case BIO_C_SET_HANDLE:
294
0
      BIO_set_init(bio, 1);
295
0
      if (!BIO_get_init(bio) || !arg2)
296
0
        return 0;
297
298
0
      ptr->hFile = (HANDLE)arg2;
299
0
      ptr->blocking = TRUE;
300
0
      if (!doReadOp(ptr))
301
0
        return -1;
302
0
      return 1;
303
0
    case BIO_C_SET_NONBLOCK:
304
0
    {
305
0
      WLog_DBG(TAG, "BIO_C_SET_NONBLOCK");
306
0
      ptr->blocking = FALSE;
307
0
      return 1;
308
0
    }
309
0
    case BIO_C_WAIT_READ:
310
0
    {
311
0
      WLog_DBG(TAG, "BIO_C_WAIT_READ");
312
0
      return 1;
313
0
    }
314
315
0
    case BIO_C_WAIT_WRITE:
316
0
    {
317
0
      WLog_DBG(TAG, "BIO_C_WAIT_WRITE");
318
0
      return 1;
319
0
    }
320
321
0
    default:
322
0
      break;
323
0
  }
324
325
0
  switch (cmd)
326
0
  {
327
0
    case BIO_CTRL_GET_CLOSE:
328
0
      status = BIO_get_shutdown(bio);
329
0
      break;
330
331
0
    case BIO_CTRL_SET_CLOSE:
332
0
      BIO_set_shutdown(bio, (int)arg1);
333
0
      status = 1;
334
0
      break;
335
336
0
    case BIO_CTRL_DUP:
337
0
      status = 1;
338
0
      break;
339
340
0
    case BIO_CTRL_FLUSH:
341
0
      status = 1;
342
0
      break;
343
344
0
    default:
345
0
      status = 0;
346
0
      break;
347
0
  }
348
349
0
  return status;
350
0
}
351
352
static void BIO_NAMED_free(WINPR_BIO_NAMED* ptr)
353
0
{
354
0
  if (!ptr)
355
0
    return;
356
357
0
  if (ptr->hFile)
358
0
  {
359
0
    (void)CloseHandle(ptr->hFile);
360
0
    ptr->hFile = NULL;
361
0
  }
362
363
0
  if (ptr->readEvent)
364
0
  {
365
0
    (void)CloseHandle(ptr->readEvent);
366
0
    ptr->readEvent = NULL;
367
0
  }
368
369
0
  ringbuffer_destroy(&ptr->readBuffer);
370
0
  free(ptr);
371
0
}
372
373
static int transport_bio_named_uninit(BIO* bio)
374
0
{
375
0
  WINPR_ASSERT(bio);
376
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
377
378
0
  BIO_NAMED_free(ptr);
379
380
0
  BIO_set_init(bio, 0);
381
0
  BIO_set_flags(bio, 0);
382
0
  return 1;
383
0
}
384
385
static int transport_bio_named_new(BIO* bio)
386
0
{
387
0
  WINPR_ASSERT(bio);
388
389
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)calloc(1, sizeof(WINPR_BIO_NAMED));
390
0
  if (!ptr)
391
0
    return 0;
392
393
0
  if (!ringbuffer_init(&ptr->readBuffer, 0xfffff))
394
0
    goto error;
395
396
0
  ptr->readEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
397
0
  if (!ptr->readEvent || ptr->readEvent == INVALID_HANDLE_VALUE)
398
0
    goto error;
399
400
0
  ptr->readOverlapped.hEvent = ptr->readEvent;
401
402
0
  BIO_set_data(bio, ptr);
403
0
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
404
0
  return 1;
405
406
0
error:
407
0
  BIO_NAMED_free(ptr);
408
0
  return 0;
409
0
}
410
411
static int transport_bio_named_free(BIO* bio)
412
0
{
413
0
  WINPR_BIO_NAMED* ptr = NULL;
414
415
0
  if (!bio)
416
0
    return 0;
417
418
0
  transport_bio_named_uninit(bio);
419
420
0
  ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
421
0
  if (ptr)
422
0
    BIO_set_data(bio, NULL);
423
424
0
  return 1;
425
0
}
426
427
static BIO_METHOD* BIO_s_namedpipe(void)
428
0
{
429
0
  static BIO_METHOD* bio_methods = NULL;
430
431
0
  if (bio_methods == NULL)
432
0
  {
433
0
    if (!(bio_methods = BIO_meth_new(BIO_TYPE_NAMEDPIPE, "NamedPipe")))
434
0
      return NULL;
435
436
0
    BIO_meth_set_write(bio_methods, transport_bio_named_write);
437
0
    BIO_meth_set_read(bio_methods, transport_bio_named_read);
438
0
    BIO_meth_set_puts(bio_methods, transport_bio_named_puts);
439
0
    BIO_meth_set_gets(bio_methods, transport_bio_named_gets);
440
0
    BIO_meth_set_ctrl(bio_methods, transport_bio_named_ctrl);
441
0
    BIO_meth_set_create(bio_methods, transport_bio_named_new);
442
0
    BIO_meth_set_destroy(bio_methods, transport_bio_named_free);
443
0
  }
444
445
0
  return bio_methods;
446
0
}
447
448
typedef NTSTATUS (*WinStationCreateChildSessionTransportFn)(WCHAR* path, DWORD len);
449
static BOOL createChildSessionTransport(HANDLE* pFile)
450
0
{
451
0
  WINPR_ASSERT(pFile);
452
453
0
  HANDLE hModule = NULL;
454
0
  BOOL ret = FALSE;
455
0
  *pFile = INVALID_HANDLE_VALUE;
456
457
0
  BOOL childEnabled = 0;
458
0
  if (!WTSIsChildSessionsEnabled(&childEnabled))
459
0
  {
460
0
    WLog_ERR(TAG, "error when calling WTSIsChildSessionsEnabled");
461
0
    goto out;
462
0
  }
463
464
0
  if (!childEnabled)
465
0
  {
466
0
    WLog_INFO(TAG, "child sessions aren't enabled");
467
0
    if (!WTSEnableChildSessions(TRUE))
468
0
    {
469
0
      WLog_ERR(TAG, "error when calling WTSEnableChildSessions");
470
0
      goto out;
471
0
    }
472
0
    WLog_INFO(TAG, "successfully enabled child sessions");
473
0
  }
474
475
0
  hModule = LoadLibraryA("winsta.dll");
476
0
  if (!hModule)
477
0
    return FALSE;
478
479
0
  {
480
0
    WCHAR pipePath[0x80] = WINPR_C_ARRAY_INIT;
481
0
    char pipePathA[0x80] = WINPR_C_ARRAY_INIT;
482
483
0
    {
484
0
      WinStationCreateChildSessionTransportFn createChildSessionFn =
485
0
          GetProcAddressAs(hModule, "WinStationCreateChildSessionTransport",
486
0
                           WinStationCreateChildSessionTransportFn);
487
0
      if (!createChildSessionFn)
488
0
      {
489
0
        WLog_ERR(TAG, "unable to retrieve WinStationCreateChildSessionTransport function");
490
0
        goto out;
491
0
      }
492
493
0
      {
494
0
        HRESULT hStatus = createChildSessionFn(pipePath, 0x80);
495
0
        if (!SUCCEEDED(hStatus))
496
0
        {
497
0
          WLog_ERR(TAG, "error 0x%08x when creating childSessionTransport",
498
0
                   WINPR_CXX_COMPAT_CAST(unsigned, hStatus));
499
0
          goto out;
500
0
        }
501
0
      }
502
0
    }
503
504
0
    {
505
0
      const BYTE startOfPath[] = { '\\', 0, '\\', 0, '.', 0, '\\', 0 };
506
0
      if (_wcsncmp(pipePath, (const WCHAR*)startOfPath, 4))
507
0
      {
508
        /* when compiled under 32 bits, the path may miss "\\.\" at the beginning of the
509
         * string so add it if it's not there
510
         */
511
0
        size_t len = _wcslen(pipePath);
512
0
        if (len > 0x80 - (4 + 1))
513
0
        {
514
0
          WLog_ERR(TAG, "pipePath is too long to be adjusted");
515
0
          goto out;
516
0
        }
517
518
0
        memmove(pipePath + 4, pipePath, (len + 1) * sizeof(WCHAR));
519
0
        memcpy(pipePath, startOfPath, 8);
520
0
      }
521
0
    }
522
523
0
    (void)ConvertWCharNToUtf8(pipePath, 0x80, pipePathA, sizeof(pipePathA));
524
0
    WLog_DBG(TAG, "child session is at '%s'", pipePathA);
525
526
0
    {
527
0
      HANDLE f = CreateFileW(pipePath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
528
0
                             FILE_FLAG_OVERLAPPED, NULL);
529
0
      if (f == INVALID_HANDLE_VALUE)
530
0
      {
531
0
        WLog_ERR(TAG, "error when connecting to local named pipe");
532
0
        goto out;
533
0
      }
534
535
0
      *pFile = f;
536
0
    }
537
0
  }
538
539
0
  ret = TRUE;
540
541
0
out:
542
0
  FreeLibrary(hModule);
543
0
  return ret;
544
0
}
545
546
BIO* createChildSessionBio(void)
547
0
{
548
0
  HANDLE f = INVALID_HANDLE_VALUE;
549
0
  if (!createChildSessionTransport(&f))
550
0
    return NULL;
551
552
0
  BIO* lowLevelBio = BIO_new(BIO_s_namedpipe());
553
0
  if (!lowLevelBio)
554
0
  {
555
0
    (void)CloseHandle(f);
556
0
    return NULL;
557
0
  }
558
559
0
  BIO_set_handle(lowLevelBio, f);
560
0
  BIO* bufferedBio = BIO_new(BIO_s_buffered_socket());
561
562
0
  if (!bufferedBio)
563
0
  {
564
0
    BIO_free_all(lowLevelBio);
565
0
    return NULL;
566
0
  }
567
568
0
  bufferedBio = BIO_push(bufferedBio, lowLevelBio);
569
570
0
  return bufferedBio;
571
0
}