Coverage Report

Created: 2025-10-10 06:50

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
  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
  const int max = (INT_MAX > SIZE_MAX) ? SIZE_MAX : INT_MAX;
260
0
  const size_t len = strnlen(str, max);
261
0
  if (len >= max)
262
0
    return -1;
263
0
  return transport_bio_named_write(bio, str, WINPR_ASSERTING_INT_CAST(int, len));
264
0
}
265
266
static int transport_bio_named_gets(BIO* bio, char* str, int size)
267
0
{
268
0
  WINPR_ASSERT(bio);
269
0
  WINPR_ASSERT(str);
270
271
0
  return transport_bio_named_read(bio, str, size);
272
0
}
273
274
static long transport_bio_named_ctrl(BIO* bio, int cmd, long arg1, void* arg2)
275
0
{
276
0
  WINPR_ASSERT(bio);
277
278
0
  int status = -1;
279
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
280
281
0
  switch (cmd)
282
0
  {
283
0
    case BIO_C_SET_SOCKET:
284
0
    case BIO_C_GET_SOCKET:
285
0
      return -1;
286
0
    case BIO_C_GET_EVENT:
287
0
      if (!BIO_get_init(bio) || !arg2)
288
0
        return 0;
289
290
0
      *((HANDLE*)arg2) = ptr->readEvent;
291
0
      return 1;
292
0
    case BIO_C_SET_HANDLE:
293
0
      BIO_set_init(bio, 1);
294
0
      if (!BIO_get_init(bio) || !arg2)
295
0
        return 0;
296
297
0
      ptr->hFile = (HANDLE)arg2;
298
0
      ptr->blocking = TRUE;
299
0
      if (!doReadOp(ptr))
300
0
        return -1;
301
0
      return 1;
302
0
    case BIO_C_SET_NONBLOCK:
303
0
    {
304
0
      WLog_DBG(TAG, "BIO_C_SET_NONBLOCK");
305
0
      ptr->blocking = FALSE;
306
0
      return 1;
307
0
    }
308
0
    case BIO_C_WAIT_READ:
309
0
    {
310
0
      WLog_DBG(TAG, "BIO_C_WAIT_READ");
311
0
      return 1;
312
0
    }
313
314
0
    case BIO_C_WAIT_WRITE:
315
0
    {
316
0
      WLog_DBG(TAG, "BIO_C_WAIT_WRITE");
317
0
      return 1;
318
0
    }
319
320
0
    default:
321
0
      break;
322
0
  }
323
324
0
  switch (cmd)
325
0
  {
326
0
    case BIO_CTRL_GET_CLOSE:
327
0
      status = BIO_get_shutdown(bio);
328
0
      break;
329
330
0
    case BIO_CTRL_SET_CLOSE:
331
0
      BIO_set_shutdown(bio, (int)arg1);
332
0
      status = 1;
333
0
      break;
334
335
0
    case BIO_CTRL_DUP:
336
0
      status = 1;
337
0
      break;
338
339
0
    case BIO_CTRL_FLUSH:
340
0
      status = 1;
341
0
      break;
342
343
0
    default:
344
0
      status = 0;
345
0
      break;
346
0
  }
347
348
0
  return status;
349
0
}
350
351
static void BIO_NAMED_free(WINPR_BIO_NAMED* ptr)
352
0
{
353
0
  if (!ptr)
354
0
    return;
355
356
0
  if (ptr->hFile)
357
0
  {
358
0
    (void)CloseHandle(ptr->hFile);
359
0
    ptr->hFile = NULL;
360
0
  }
361
362
0
  if (ptr->readEvent)
363
0
  {
364
0
    (void)CloseHandle(ptr->readEvent);
365
0
    ptr->readEvent = NULL;
366
0
  }
367
368
0
  ringbuffer_destroy(&ptr->readBuffer);
369
0
  free(ptr);
370
0
}
371
372
static int transport_bio_named_uninit(BIO* bio)
373
0
{
374
0
  WINPR_ASSERT(bio);
375
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
376
377
0
  BIO_NAMED_free(ptr);
378
379
0
  BIO_set_init(bio, 0);
380
0
  BIO_set_flags(bio, 0);
381
0
  return 1;
382
0
}
383
384
static int transport_bio_named_new(BIO* bio)
385
0
{
386
0
  WINPR_ASSERT(bio);
387
388
0
  WINPR_BIO_NAMED* ptr = (WINPR_BIO_NAMED*)calloc(1, sizeof(WINPR_BIO_NAMED));
389
0
  if (!ptr)
390
0
    return 0;
391
392
0
  if (!ringbuffer_init(&ptr->readBuffer, 0xfffff))
393
0
    goto error;
394
395
0
  ptr->readEvent = CreateEventA(NULL, TRUE, FALSE, NULL);
396
0
  if (!ptr->readEvent || ptr->readEvent == INVALID_HANDLE_VALUE)
397
0
    goto error;
398
399
0
  ptr->readOverlapped.hEvent = ptr->readEvent;
400
401
0
  BIO_set_data(bio, ptr);
402
0
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
403
0
  return 1;
404
405
0
error:
406
0
  BIO_NAMED_free(ptr);
407
0
  return 0;
408
0
}
409
410
static int transport_bio_named_free(BIO* bio)
411
0
{
412
0
  WINPR_BIO_NAMED* ptr = NULL;
413
414
0
  if (!bio)
415
0
    return 0;
416
417
0
  transport_bio_named_uninit(bio);
418
419
0
  ptr = (WINPR_BIO_NAMED*)BIO_get_data(bio);
420
0
  if (ptr)
421
0
    BIO_set_data(bio, NULL);
422
423
0
  return 1;
424
0
}
425
426
static BIO_METHOD* BIO_s_namedpipe(void)
427
0
{
428
0
  static BIO_METHOD* bio_methods = NULL;
429
430
0
  if (bio_methods == NULL)
431
0
  {
432
0
    if (!(bio_methods = BIO_meth_new(BIO_TYPE_NAMEDPIPE, "NamedPipe")))
433
0
      return NULL;
434
435
0
    BIO_meth_set_write(bio_methods, transport_bio_named_write);
436
0
    BIO_meth_set_read(bio_methods, transport_bio_named_read);
437
0
    BIO_meth_set_puts(bio_methods, transport_bio_named_puts);
438
0
    BIO_meth_set_gets(bio_methods, transport_bio_named_gets);
439
0
    BIO_meth_set_ctrl(bio_methods, transport_bio_named_ctrl);
440
0
    BIO_meth_set_create(bio_methods, transport_bio_named_new);
441
0
    BIO_meth_set_destroy(bio_methods, transport_bio_named_free);
442
0
  }
443
444
0
  return bio_methods;
445
0
}
446
447
typedef NTSTATUS (*WinStationCreateChildSessionTransportFn)(WCHAR* path, DWORD len);
448
static BOOL createChildSessionTransport(HANDLE* pFile)
449
0
{
450
0
  WINPR_ASSERT(pFile);
451
452
0
  HANDLE hModule = NULL;
453
0
  BOOL ret = FALSE;
454
0
  *pFile = INVALID_HANDLE_VALUE;
455
456
0
  BOOL childEnabled = 0;
457
0
  if (!WTSIsChildSessionsEnabled(&childEnabled))
458
0
  {
459
0
    WLog_ERR(TAG, "error when calling WTSIsChildSessionsEnabled");
460
0
    goto out;
461
0
  }
462
463
0
  if (!childEnabled)
464
0
  {
465
0
    WLog_INFO(TAG, "child sessions aren't enabled");
466
0
    if (!WTSEnableChildSessions(TRUE))
467
0
    {
468
0
      WLog_ERR(TAG, "error when calling WTSEnableChildSessions");
469
0
      goto out;
470
0
    }
471
0
    WLog_INFO(TAG, "successfully enabled child sessions");
472
0
  }
473
474
0
  hModule = LoadLibraryA("winsta.dll");
475
0
  if (!hModule)
476
0
    return FALSE;
477
0
  WCHAR pipePath[0x80] = { 0 };
478
0
  char pipePathA[0x80] = { 0 };
479
480
0
  WinStationCreateChildSessionTransportFn createChildSessionFn = GetProcAddressAs(
481
0
      hModule, "WinStationCreateChildSessionTransport", WinStationCreateChildSessionTransportFn);
482
0
  if (!createChildSessionFn)
483
0
  {
484
0
    WLog_ERR(TAG, "unable to retrieve WinStationCreateChildSessionTransport function");
485
0
    goto out;
486
0
  }
487
488
0
  HRESULT hStatus = createChildSessionFn(pipePath, 0x80);
489
0
  if (!SUCCEEDED(hStatus))
490
0
  {
491
0
    WLog_ERR(TAG, "error 0x%x when creating childSessionTransport", hStatus);
492
0
    goto out;
493
0
  }
494
495
0
  const BYTE startOfPath[] = { '\\', 0, '\\', 0, '.', 0, '\\', 0 };
496
0
  if (_wcsncmp(pipePath, (const WCHAR*)startOfPath, 4))
497
0
  {
498
    /* when compiled under 32 bits, the path may miss "\\.\" at the beginning of the string
499
     * so add it if it's not there
500
     */
501
0
    size_t len = _wcslen(pipePath);
502
0
    if (len > 0x80 - (4 + 1))
503
0
    {
504
0
      WLog_ERR(TAG, "pipePath is too long to be adjusted");
505
0
      goto out;
506
0
    }
507
508
0
    memmove(pipePath + 4, pipePath, (len + 1) * sizeof(WCHAR));
509
0
    memcpy(pipePath, startOfPath, 8);
510
0
  }
511
512
0
  (void)ConvertWCharNToUtf8(pipePath, 0x80, pipePathA, sizeof(pipePathA));
513
0
  WLog_DBG(TAG, "child session is at '%s'", pipePathA);
514
515
0
  HANDLE f = CreateFileW(pipePath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING,
516
0
                         FILE_FLAG_OVERLAPPED, NULL);
517
0
  if (f == INVALID_HANDLE_VALUE)
518
0
  {
519
0
    WLog_ERR(TAG, "error when connecting to local named pipe");
520
0
    goto out;
521
0
  }
522
523
0
  *pFile = f;
524
0
  ret = TRUE;
525
526
0
out:
527
0
  FreeLibrary(hModule);
528
0
  return ret;
529
0
}
530
531
BIO* createChildSessionBio(void)
532
0
{
533
0
  HANDLE f = INVALID_HANDLE_VALUE;
534
0
  if (!createChildSessionTransport(&f))
535
0
    return NULL;
536
537
0
  BIO* lowLevelBio = BIO_new(BIO_s_namedpipe());
538
0
  if (!lowLevelBio)
539
0
  {
540
0
    (void)CloseHandle(f);
541
0
    return NULL;
542
0
  }
543
544
0
  BIO_set_handle(lowLevelBio, f);
545
0
  BIO* bufferedBio = BIO_new(BIO_s_buffered_socket());
546
547
0
  if (!bufferedBio)
548
0
  {
549
0
    BIO_free_all(lowLevelBio);
550
0
    return NULL;
551
0
  }
552
553
0
  bufferedBio = BIO_push(bufferedBio, lowLevelBio);
554
555
0
  return bufferedBio;
556
0
}