Coverage Report

Created: 2026-11-10 06:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/libfreerdp/crypto/tls.c
Line
Count
Source
1
/**
2
 * FreeRDP: A Remote Desktop Protocol Implementation
3
 * Transport Layer Security
4
 *
5
 * Copyright 2011-2012 Marc-Andre Moreau <marcandre.moreau@gmail.com>
6
 * Copyright 2023 Armin Novak <anovak@thincast.com>
7
 * Copyright 2023 Thincast Technologies GmbH
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
#include <freerdp/config.h>
23
24
#include "../core/settings.h"
25
26
#include <winpr/assert.h>
27
#include <string.h>
28
#include <errno.h>
29
30
#include <winpr/crt.h>
31
#include <winpr/winpr.h>
32
#include <winpr/string.h>
33
#include <winpr/sspi.h>
34
#include <winpr/ssl.h>
35
#include <winpr/json.h>
36
37
#include <winpr/stream.h>
38
#include <freerdp/utils/ringbuffer.h>
39
40
#include <freerdp/crypto/certificate.h>
41
#include <freerdp/crypto/certificate_data.h>
42
#include <freerdp/utils/helpers.h>
43
44
#include <freerdp/log.h>
45
#include "../crypto/tls.h"
46
#include "../crypto/x509_utils.h"
47
#include "../core/tcp.h"
48
49
#include "opensslcompat.h"
50
#include "certificate.h"
51
#include "privatekey.h"
52
#include "../core/utils.h"
53
54
#ifdef WINPR_HAVE_POLL_H
55
#include <poll.h>
56
#endif
57
58
#ifdef FREERDP_HAVE_VALGRIND_MEMCHECK_H
59
#include <valgrind/memcheck.h>
60
#endif
61
62
0
#define TAG FREERDP_TAG("crypto")
63
64
/**
65
 * Earlier Microsoft iOS RDP clients have sent a null or even double null
66
 * terminated hostname in the SNI TLS extension.
67
 * If the length indicator does not equal the hostname strlen OpenSSL
68
 * will abort (see openssl:ssl/t1_lib.c).
69
 * Here is a tcpdump segment of Microsoft Remote Desktop Client Version
70
 * 8.1.7 running on an iPhone 4 with iOS 7.1.2 showing the transmitted
71
 * SNI hostname TLV blob when connection to server "abcd":
72
 * 00                  name_type 0x00 (host_name)
73
 * 00 06               length_in_bytes 0x0006
74
 * 61 62 63 64 00 00   host_name "abcd\0\0"
75
 *
76
 * Currently the only (runtime) workaround is setting an openssl tls
77
 * extension debug callback that sets the SSL context's servername_done
78
 * to 1 which effectively disables the parsing of that extension type.
79
 *
80
 * Nowadays this workaround is not required anymore but still can be
81
 * activated by adding the following define:
82
 *
83
 * #define MICROSOFT_IOS_SNI_BUG
84
 */
85
86
typedef struct
87
{
88
  SSL* ssl;
89
  CRITICAL_SECTION lock;
90
#ifdef WITH_TLS_DATA_LIMIT
91
  UINT64 rxBytes;      /* plaintext bytes read since the last rekey */
92
  UINT64 txBytes;      /* plaintext bytes written since the last rekey */
93
  BOOL rekeyAvailable; /* FALSE once we learn the connection is not TLS 1.3 */
94
  BOOL cutPending;     /* TRUE once a TLS 1.3 rekey failed; tear the connection down */
95
#endif
96
} BIO_RDP_TLS;
97
98
#ifdef WITH_TLS_DATA_LIMIT
99
/* Per-direction plaintext byte threshold before refreshing the TLS traffic keys,
100
 * to stay within AEAD cryptographic limits. RFC 8446 (TLS 1.3) ยง5.5 bounds
101
 * AES-GCM at 2^24.5 records (2^14 B) (~362 GiB). OpenSSL does not enforce this itself
102
 * (https://github.com/openssl/openssl/issues/23566). On TLS 1.3 the keys are
103
 * rekeyed in place (SSL_key_update); on other protocols a rekey is not possible. */
104
static const UINT64 TLS_DATA_LIMIT_BYTES = 388736063996ULL;
105
#endif
106
107
static INIT_ONCE g_BioMethodsOnce = INIT_ONCE_STATIC_INIT;
108
static BIO_METHOD* g_BioMethods = nullptr;
109
110
static INIT_ONCE secrets_file_idx_once = INIT_ONCE_STATIC_INIT;
111
static int secrets_file_idx = -1;
112
113
WINPR_ATTR_NODISCARD
114
static int tls_verify_certificate(rdpTls* tls, const rdpCertificate* cert, const char* hostname,
115
                                  UINT16 port);
116
117
static void tls_print_certificate_name_mismatch_error(const rdpCertificate* cert,
118
                                                      const char* hostname, UINT16 port);
119
120
static void tls_print_new_certificate_warn(rdpCertificateStore* store, const char* hostname,
121
                                           UINT16 port, const char* type, const char* fingerprint);
122
123
static void tls_print_certificate_error(rdpCertificateStore* store, rdpCertificateData* stored_data,
124
                                        const char* hostname, UINT16 port, const char* fingerprint);
125
126
static void free_tls_public_key(rdpTls* tls)
127
0
{
128
0
  WINPR_ASSERT(tls);
129
0
  free(tls->PublicKey);
130
0
  tls->PublicKey = nullptr;
131
0
  tls->PublicKeyLength = 0;
132
0
}
133
134
static void free_tls_bindings(SecPkgContext_Bindings* bindings)
135
0
{
136
0
  if (!bindings)
137
0
    return;
138
139
0
  free(bindings->Bindings);
140
0
  free(bindings);
141
0
}
142
143
#ifdef WITH_TLS_DATA_LIMIT
144
/* Must be called with tls->lock held, after a successful SSL_read/SSL_write of
145
 * `count` bytes in the given direction. Once a per-direction byte threshold is
146
 * crossed, refreshes the TLS 1.3 traffic keys in place; on a non-TLS-1.3
147
 * connection a rekey is not possible so it is disabled (the connection is kept).
148
 * If a TLS 1.3 rekey fails, flags the connection to be cut. */
149
static void bio_rdp_tls_account(BIO_RDP_TLS* tls, BOOL read, int count)
150
{
151
  UINT64* counter = read ? &tls->rxBytes : &tls->txBytes;
152
153
  if (!tls->rekeyAvailable || tls->cutPending)
154
    return;
155
156
  *counter += (UINT64)count;
157
  if (*counter < TLS_DATA_LIMIT_BYTES)
158
    return;
159
160
  if (SSL_version(tls->ssl) != TLS1_3_VERSION)
161
  {
162
    WLog_DBG(TAG, "TLS data limit reached but connection is not TLS 1.3; "
163
                  "rekey unavailable, keeping connection");
164
    tls->rekeyAvailable = FALSE;
165
    return;
166
  }
167
168
  if (SSL_key_update(tls->ssl, SSL_KEY_UPDATE_REQUESTED) != 1)
169
  {
170
    WLog_ERR(TAG, "SSL_key_update failed at TLS data limit; cutting connection");
171
    tls->cutPending = TRUE;
172
    return;
173
  }
174
175
  WLog_INFO(TAG, "TLS 1.3 key update requested at data limit (%" PRIu64 " bytes %s)", *counter,
176
            read ? "read" : "written");
177
  *counter = 0;
178
}
179
180
static void bio_rdp_tls_read_account(BIO_RDP_TLS* tls, int count)
181
{
182
  bio_rdp_tls_account(tls, TRUE, count);
183
}
184
185
static void bio_rdp_tls_write_account(BIO_RDP_TLS* tls, int count)
186
{
187
  bio_rdp_tls_account(tls, FALSE, count);
188
}
189
#endif
190
191
/* Say what a failed SSL_read or SSL_write means for the caller, with tls->lock held.
192
 *
193
 * BIO_should_retry() reads a flag the reading and the writing thread share, and the caller looks
194
 * at it after leaving the lock. So only a failure that cannot be retried may clear it: if a call
195
 * cleared it on the way in, the other thread would take its own retry for a broken connection. */
196
static void bio_rdp_tls_set_retry(BIO* bio, int error)
197
0
{
198
0
  switch (error)
199
0
  {
200
0
    case SSL_ERROR_WANT_READ:
201
0
      BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
202
0
      break;
203
204
0
    case SSL_ERROR_WANT_WRITE:
205
0
      BIO_set_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
206
0
      break;
207
208
0
    case SSL_ERROR_WANT_X509_LOOKUP:
209
0
      BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
210
0
      BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
211
0
      BIO_set_retry_reason(bio, BIO_RR_SSL_X509_LOOKUP);
212
0
      break;
213
214
0
    case SSL_ERROR_WANT_ACCEPT:
215
0
      BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
216
0
      BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
217
0
      BIO_set_retry_reason(bio, BIO_RR_ACCEPT);
218
0
      break;
219
220
0
    case SSL_ERROR_WANT_CONNECT:
221
0
      BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
222
0
      BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
223
0
      BIO_set_retry_reason(bio, BIO_RR_CONNECT);
224
0
      break;
225
226
0
    case SSL_ERROR_NONE:
227
0
    case SSL_ERROR_SSL:
228
0
    case SSL_ERROR_SYSCALL:
229
0
    case SSL_ERROR_ZERO_RETURN:
230
0
      BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
231
0
      break;
232
233
0
    default:
234
      /* nothing says this one can be retried */
235
0
      WLog_WARN(TAG, "unexpected SSL error %d: not retrying", error);
236
0
      BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
237
0
      break;
238
0
  }
239
0
}
240
241
WINPR_ATTR_NODISCARD
242
static int bio_rdp_tls_write(BIO* bio, const char* buf, int size)
243
0
{
244
0
  int error = 0;
245
0
  int status = 0;
246
0
  BIO_RDP_TLS* tls = (BIO_RDP_TLS*)BIO_get_data(bio);
247
248
0
  if (!buf || !tls)
249
0
    return 0;
250
251
#ifdef WITH_TLS_DATA_LIMIT
252
  if (tls->cutPending)
253
  {
254
    BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
255
    return -1;
256
  }
257
#endif
258
259
0
  EnterCriticalSection(&tls->lock);
260
0
  BIO_clear_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL);
261
0
  status = SSL_write(tls->ssl, buf, size);
262
0
  error = SSL_get_error(tls->ssl, status);
263
#ifdef WITH_TLS_DATA_LIMIT
264
  if (status > 0)
265
    bio_rdp_tls_write_account(tls, status);
266
#endif
267
268
0
  if (status <= 0)
269
0
    bio_rdp_tls_set_retry(bio, error);
270
0
  LeaveCriticalSection(&tls->lock);
271
272
0
  return status;
273
0
}
274
275
WINPR_ATTR_NODISCARD
276
static int bio_rdp_tls_read(BIO* bio, char* buf, int size)
277
0
{
278
0
  int error = 0;
279
0
  int status = 0;
280
0
  BIO_RDP_TLS* tls = (BIO_RDP_TLS*)BIO_get_data(bio);
281
282
0
  if (!buf || !tls)
283
0
    return 0;
284
285
#ifdef WITH_TLS_DATA_LIMIT
286
  if (tls->cutPending)
287
  {
288
    BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
289
    return -1;
290
  }
291
#endif
292
293
0
  EnterCriticalSection(&tls->lock);
294
0
  BIO_clear_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL);
295
0
  status = SSL_read(tls->ssl, buf, size);
296
0
  error = SSL_get_error(tls->ssl, status);
297
#ifdef WITH_TLS_DATA_LIMIT
298
  if (status > 0)
299
    bio_rdp_tls_read_account(tls, status);
300
#endif
301
302
0
  if (status <= 0)
303
0
    bio_rdp_tls_set_retry(bio, error);
304
0
  LeaveCriticalSection(&tls->lock);
305
306
#ifdef FREERDP_HAVE_VALGRIND_MEMCHECK_H
307
308
  if (status > 0)
309
  {
310
    VALGRIND_MAKE_MEM_DEFINED(buf, status);
311
  }
312
313
#endif
314
0
  return status;
315
0
}
316
317
WINPR_ATTR_NODISCARD
318
static int bio_rdp_tls_puts(BIO* bio, const char* str)
319
0
{
320
0
  if (!str)
321
0
    return 0;
322
323
0
  const size_t max = (INT_MAX > SIZE_MAX) ? SIZE_MAX : INT_MAX;
324
0
  const size_t size = strnlen(str, max);
325
0
  if (size >= max)
326
0
    return -1;
327
0
  ERR_clear_error();
328
0
  return BIO_write(bio, str, (int)size);
329
0
}
330
331
WINPR_ATTR_NODISCARD
332
static int bio_rdp_tls_gets(WINPR_ATTR_UNUSED BIO* bio, WINPR_ATTR_UNUSED char* str,
333
                            WINPR_ATTR_UNUSED int size)
334
0
{
335
0
  return 1;
336
0
}
337
338
WINPR_ATTR_NODISCARD
339
static long bio_rdp_tls_ctrl(BIO* bio, int cmd, long num, void* ptr)
340
0
{
341
0
  BIO* ssl_rbio = nullptr;
342
0
  BIO* ssl_wbio = nullptr;
343
0
  BIO* next_bio = nullptr;
344
0
  long status = -1;
345
0
  BIO_RDP_TLS* tls = (BIO_RDP_TLS*)BIO_get_data(bio);
346
347
0
  if (!tls)
348
0
    return 0;
349
350
0
  if (!tls->ssl && (cmd != BIO_C_SET_SSL))
351
0
    return 0;
352
353
0
  next_bio = BIO_next(bio);
354
0
  ssl_rbio = tls->ssl ? SSL_get_rbio(tls->ssl) : nullptr;
355
0
  ssl_wbio = tls->ssl ? SSL_get_wbio(tls->ssl) : nullptr;
356
357
0
  switch (cmd)
358
0
  {
359
0
    case BIO_CTRL_RESET:
360
0
      SSL_shutdown(tls->ssl);
361
362
0
      if (SSL_in_connect_init(tls->ssl))
363
0
        SSL_set_connect_state(tls->ssl);
364
0
      else if (SSL_in_accept_init(tls->ssl))
365
0
        SSL_set_accept_state(tls->ssl);
366
367
0
      SSL_clear(tls->ssl);
368
369
0
      if (next_bio)
370
0
        status = BIO_ctrl(next_bio, cmd, num, ptr);
371
0
      else if (ssl_rbio)
372
0
        status = BIO_ctrl(ssl_rbio, cmd, num, ptr);
373
0
      else
374
0
        status = 1;
375
376
0
      break;
377
378
0
    case BIO_C_GET_FD:
379
0
      status = BIO_ctrl(ssl_rbio, cmd, num, ptr);
380
0
      break;
381
382
0
    case BIO_CTRL_INFO:
383
0
      status = 0;
384
0
      break;
385
386
0
    case BIO_CTRL_SET_CALLBACK:
387
0
      status = 0;
388
0
      break;
389
390
0
    case BIO_CTRL_GET_CALLBACK:
391
      /* The OpenSSL API is horrible here:
392
       * we get a function pointer returned and have to cast it to ULONG_PTR
393
       * to return the value to the caller.
394
       *
395
       * This, of course, is something compilers warn about. So silence it by casting */
396
0
      {
397
0
        void* vptr = WINPR_FUNC_PTR_CAST(SSL_get_info_callback(tls->ssl), void*);
398
0
        *((void**)ptr) = vptr;
399
0
        status = 1;
400
0
      }
401
0
      break;
402
403
0
    case BIO_C_SSL_MODE:
404
0
      if (num)
405
0
        SSL_set_connect_state(tls->ssl);
406
0
      else
407
0
        SSL_set_accept_state(tls->ssl);
408
409
0
      status = 1;
410
0
      break;
411
412
0
    case BIO_CTRL_GET_CLOSE:
413
0
      status = BIO_get_shutdown(bio);
414
0
      break;
415
416
0
    case BIO_CTRL_SET_CLOSE:
417
0
      BIO_set_shutdown(bio, (int)num);
418
0
      status = 1;
419
0
      break;
420
421
0
    case BIO_CTRL_WPENDING:
422
0
      EnterCriticalSection(&tls->lock);
423
0
      status = BIO_ctrl(ssl_wbio, cmd, num, ptr);
424
0
      LeaveCriticalSection(&tls->lock);
425
0
      break;
426
427
0
    case BIO_CTRL_PENDING:
428
0
      status = SSL_pending(tls->ssl);
429
430
0
      if (status == 0)
431
0
        status = BIO_pending(ssl_rbio);
432
433
0
      break;
434
435
0
    case BIO_CTRL_FLUSH:
436
      /* A flush writes out the BIO below, just like SSL_write and SSL_read do,
437
       * so it must be serialized with them by the same lock. */
438
0
      EnterCriticalSection(&tls->lock);
439
0
      status = BIO_ctrl(ssl_wbio, cmd, num, ptr);
440
0
      BIO_copy_next_retry(bio);
441
0
      LeaveCriticalSection(&tls->lock);
442
0
      if (status != 1)
443
0
        WLog_DBG(TAG, "BIO_ctrl returned %ld", status);
444
0
      status = 1;
445
0
      break;
446
447
0
    case BIO_CTRL_PUSH:
448
0
      if (next_bio && (next_bio != ssl_rbio))
449
0
      {
450
#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
451
    (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
452
        SSL_set_bio(tls->ssl, next_bio, next_bio);
453
        CRYPTO_add(&(bio->next_bio->references), 1, CRYPTO_LOCK_BIO);
454
#else
455
        /*
456
         * We are going to pass ownership of next to the SSL object...but
457
         * we don't own a reference to pass yet - so up ref
458
         */
459
0
        BIO_up_ref(next_bio);
460
0
        SSL_set_bio(tls->ssl, next_bio, next_bio);
461
0
#endif
462
0
      }
463
464
0
      status = 1;
465
0
      break;
466
467
0
    case BIO_CTRL_POP:
468
469
      /* Only detach if we are the BIO explicitly being popped */
470
0
      if (bio == ptr)
471
0
      {
472
0
        if (ssl_rbio != ssl_wbio)
473
0
          BIO_free_all(ssl_wbio);
474
475
#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
476
    (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
477
478
        if (next_bio)
479
          CRYPTO_add(&(bio->next_bio->references), -1, CRYPTO_LOCK_BIO);
480
481
        tls->ssl->wbio = tls->ssl->rbio = nullptr;
482
#else
483
        /* OpenSSL 1.1: This will also clear the reference we obtained during push */
484
0
        SSL_set_bio(tls->ssl, nullptr, nullptr);
485
0
#endif
486
0
      }
487
488
0
      status = 1;
489
0
      break;
490
491
0
    case BIO_C_GET_SSL:
492
0
      if (ptr)
493
0
      {
494
0
        *((SSL**)ptr) = tls->ssl;
495
0
        status = 1;
496
0
      }
497
498
0
      break;
499
500
0
    case BIO_C_SET_SSL:
501
0
      BIO_set_shutdown(bio, (int)num);
502
503
0
      if (ptr)
504
0
      {
505
0
        tls->ssl = (SSL*)ptr;
506
0
        ssl_rbio = SSL_get_rbio(tls->ssl);
507
0
      }
508
509
0
      if (ssl_rbio)
510
0
      {
511
0
        if (next_bio)
512
0
          BIO_push(ssl_rbio, next_bio);
513
514
0
        BIO_set_next(bio, ssl_rbio);
515
#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
516
    (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
517
        CRYPTO_add(&(ssl_rbio->references), 1, CRYPTO_LOCK_BIO);
518
#else
519
0
        BIO_up_ref(ssl_rbio);
520
0
#endif
521
0
      }
522
523
0
      BIO_set_init(bio, 1);
524
0
      status = 1;
525
0
      break;
526
527
0
    case BIO_C_DO_STATE_MACHINE:
528
0
      BIO_clear_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_WRITE | BIO_FLAGS_IO_SPECIAL);
529
0
      BIO_set_retry_reason(bio, 0);
530
0
      status = SSL_do_handshake(tls->ssl);
531
532
0
      if (status <= 0)
533
0
      {
534
0
        const int err = (status < INT32_MIN) ? INT32_MIN : (int)status;
535
0
        switch (SSL_get_error(tls->ssl, err))
536
0
        {
537
0
          case SSL_ERROR_WANT_READ:
538
0
            BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
539
0
            break;
540
541
0
          case SSL_ERROR_WANT_WRITE:
542
0
            BIO_set_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
543
0
            break;
544
545
0
          case SSL_ERROR_WANT_CONNECT:
546
0
            BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY);
547
0
            BIO_set_retry_reason(bio, BIO_get_retry_reason(next_bio));
548
0
            break;
549
550
0
          default:
551
0
            BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
552
0
            break;
553
0
        }
554
0
      }
555
556
0
      break;
557
558
0
    default:
559
0
      status = BIO_ctrl(ssl_rbio, cmd, num, ptr);
560
0
      break;
561
0
  }
562
563
0
  return status;
564
0
}
565
566
WINPR_ATTR_NODISCARD
567
static int bio_rdp_tls_new(BIO* bio)
568
0
{
569
0
  BIO_RDP_TLS* tls = nullptr;
570
0
  BIO_set_flags(bio, BIO_FLAGS_SHOULD_RETRY);
571
572
0
  if (!(tls = calloc(1, sizeof(BIO_RDP_TLS))))
573
0
    return 0;
574
575
0
  if (!InitializeCriticalSectionAndSpinCount(&tls->lock, 4000))
576
0
  {
577
0
    free(tls);
578
0
    return -1;
579
0
  }
580
581
#ifdef WITH_TLS_DATA_LIMIT
582
  /* counters/cutPending zeroed by calloc; rekey is assumed possible until we
583
   * observe a non-TLS-1.3 connection at the data limit. */
584
  tls->rekeyAvailable = TRUE;
585
#endif
586
587
0
  BIO_set_data(bio, (void*)tls);
588
0
  return 1;
589
0
}
590
591
WINPR_ATTR_NODISCARD
592
static int bio_rdp_tls_free(BIO* bio)
593
0
{
594
0
  BIO_RDP_TLS* tls = nullptr;
595
596
0
  if (!bio)
597
0
    return 0;
598
599
0
  tls = (BIO_RDP_TLS*)BIO_get_data(bio);
600
601
0
  if (!tls)
602
0
    return 0;
603
604
0
  BIO_set_data(bio, nullptr);
605
0
  if (BIO_get_shutdown(bio))
606
0
  {
607
0
    if (BIO_get_init(bio) && tls->ssl)
608
0
    {
609
0
      SSL_shutdown(tls->ssl);
610
0
      SSL_free(tls->ssl);
611
0
    }
612
613
0
    BIO_set_init(bio, 0);
614
0
    BIO_set_flags(bio, 0);
615
0
  }
616
617
0
  DeleteCriticalSection(&tls->lock);
618
0
  free(tls);
619
620
0
  return 1;
621
0
}
622
623
WINPR_ATTR_NODISCARD
624
static long bio_rdp_tls_callback_ctrl(BIO* bio, int cmd, bio_info_cb* fp)
625
0
{
626
0
  long status = 0;
627
628
0
  if (!bio)
629
0
    return 0;
630
631
0
  BIO_RDP_TLS* tls = (BIO_RDP_TLS*)BIO_get_data(bio);
632
633
0
  if (!tls)
634
0
    return 0;
635
636
0
  switch (cmd)
637
0
  {
638
0
    case BIO_CTRL_SET_CALLBACK:
639
0
    {
640
0
      typedef void (*fkt_t)(const SSL*, int, int);
641
642
      /* Documented since https://www.openssl.org/docs/man1.1.1/man3/BIO_set_callback.html
643
       * the argument is not really of type bio_info_cb* and must be cast
644
       * to the required type */
645
646
0
      fkt_t fkt = WINPR_FUNC_PTR_CAST(fp, fkt_t);
647
0
      SSL_set_info_callback(tls->ssl, fkt);
648
0
      status = 1;
649
0
    }
650
0
    break;
651
652
0
    default:
653
0
      status = BIO_callback_ctrl(SSL_get_rbio(tls->ssl), cmd, fp);
654
0
      break;
655
0
  }
656
657
0
  return status;
658
0
}
659
660
0
#define BIO_TYPE_RDP_TLS 68
661
662
WINPR_ATTR_NODISCARD
663
static BOOL CALLBACK bio_rdp_tls_init_once(WINPR_ATTR_UNUSED PINIT_ONCE once,
664
                                           WINPR_ATTR_UNUSED PVOID param,
665
                                           WINPR_ATTR_UNUSED PVOID* context)
666
0
{
667
0
  g_BioMethods = BIO_meth_new(BIO_TYPE_RDP_TLS, "RdpTls");
668
0
  if (!g_BioMethods)
669
0
    return FALSE;
670
671
0
  if (BIO_meth_set_write(g_BioMethods, bio_rdp_tls_write) != 1)
672
0
    return FALSE;
673
0
  if (BIO_meth_set_read(g_BioMethods, bio_rdp_tls_read) != 1)
674
0
    return FALSE;
675
0
  if (BIO_meth_set_puts(g_BioMethods, bio_rdp_tls_puts) != 1)
676
0
    return FALSE;
677
0
  if (BIO_meth_set_gets(g_BioMethods, bio_rdp_tls_gets) != 1)
678
0
    return FALSE;
679
0
  if (BIO_meth_set_ctrl(g_BioMethods, bio_rdp_tls_ctrl) != 1)
680
0
    return FALSE;
681
0
  if (BIO_meth_set_create(g_BioMethods, bio_rdp_tls_new) != 1)
682
0
    return FALSE;
683
0
  if (BIO_meth_set_destroy(g_BioMethods, bio_rdp_tls_free) != 1)
684
0
    return FALSE;
685
0
  if (BIO_meth_set_callback_ctrl(g_BioMethods, bio_rdp_tls_callback_ctrl) != 1)
686
0
    return FALSE;
687
688
0
  return TRUE;
689
0
}
690
691
WINPR_ATTR_NODISCARD
692
static BIO_METHOD* BIO_s_rdp_tls(void)
693
0
{
694
0
  if (!InitOnceExecuteOnce(&g_BioMethodsOnce, bio_rdp_tls_init_once, nullptr, nullptr))
695
0
    return nullptr;
696
0
  return g_BioMethods;
697
0
}
698
699
WINPR_ATTR_MALLOC(BIO_free, 1)
700
static BIO* BIO_new_rdp_tls(SSL_CTX* ctx, int client)
701
0
{
702
0
  BIO* bio = BIO_new(BIO_s_rdp_tls());
703
704
0
  if (!bio)
705
0
    return nullptr;
706
707
0
  SSL* ssl = SSL_new(ctx);
708
709
0
  if (!ssl)
710
0
  {
711
0
    BIO_free_all(bio);
712
0
    return nullptr;
713
0
  }
714
715
0
  if (client)
716
0
    SSL_set_connect_state(ssl);
717
0
  else
718
0
    SSL_set_accept_state(ssl);
719
720
0
  BIO_set_ssl(bio, ssl, BIO_CLOSE);
721
0
  return bio;
722
0
}
723
724
WINPR_ATTR_MALLOC(freerdp_certificate_free, 1)
725
static rdpCertificate* tls_get_certificate(rdpTls* tls, BOOL peer)
726
0
{
727
0
  X509* remote_cert = nullptr;
728
729
0
  if (peer)
730
0
    remote_cert = SSL_get_peer_certificate(tls->ssl);
731
0
  else
732
0
    remote_cert = X509_dup(SSL_get_certificate(tls->ssl));
733
734
0
  if (!remote_cert)
735
0
  {
736
0
    WLog_ERR(TAG, "failed to get the server TLS certificate");
737
0
    return nullptr;
738
0
  }
739
740
  /* Get the peer's chain. If it does not exist, we're setting nullptr (clean data either way) */
741
0
  STACK_OF(X509)* chain = SSL_get_peer_cert_chain(tls->ssl);
742
0
  rdpCertificate* cert = freerdp_certificate_new_from_x509(remote_cert, chain);
743
0
  X509_free(remote_cert);
744
745
0
  return cert;
746
0
}
747
748
WINPR_ATTR_NODISCARD
749
static const char* tls_get_server_name(rdpTls* tls)
750
0
{
751
0
  return tls->serverName ? tls->serverName : tls->hostname;
752
0
}
753
754
0
#define TLS_SERVER_END_POINT "tls-server-end-point:"
755
756
WINPR_ATTR_MALLOC(free_tls_bindings, 1)
757
static SecPkgContext_Bindings* tls_get_channel_bindings(const rdpCertificate* cert)
758
0
{
759
0
  size_t CertificateHashLength = 0;
760
0
  BYTE* ChannelBindingToken = nullptr;
761
0
  SEC_CHANNEL_BINDINGS* ChannelBindings = nullptr;
762
0
  const size_t PrefixLength = strnlen(TLS_SERVER_END_POINT, ARRAYSIZE(TLS_SERVER_END_POINT));
763
764
0
  WINPR_ASSERT(cert);
765
766
  /* See https://www.rfc-editor.org/rfc/rfc5929 for details about hashes */
767
0
  WINPR_MD_TYPE alg = freerdp_certificate_get_signature_alg(cert);
768
0
  char* CertificateHash = nullptr;
769
0
  if (alg == WINPR_MD_NONE)
770
0
  {
771
    /* Ed25519, Ed448, ML-DSA, SLH-DSA: no hash in the signature algorithm */
772
0
    const X509* x509 =
773
0
        freerdp_certificate_get_x509(WINPR_CAST_CONST_PTR_AWAY(cert, rdpCertificate*));
774
0
    CertificateHash =
775
0
        (char*)x509_utils_get_hashless_signature_hash(x509, &CertificateHashLength);
776
0
  }
777
0
  else
778
0
  {
779
0
    const char* hash = nullptr;
780
0
    switch (alg)
781
0
    {
782
783
0
      case WINPR_MD_MD5:
784
0
      case WINPR_MD_SHA1:
785
0
        hash = winpr_md_type_to_string(WINPR_MD_SHA256);
786
0
        break;
787
0
      default:
788
0
        hash = winpr_md_type_to_string(alg);
789
0
        break;
790
0
    }
791
0
    if (!hash)
792
0
      return nullptr;
793
794
0
    CertificateHash = freerdp_certificate_get_hash(cert, hash, &CertificateHashLength);
795
0
  }
796
0
  if (!CertificateHash)
797
0
    return nullptr;
798
799
0
  const size_t ChannelBindingTokenLength = PrefixLength + CertificateHashLength;
800
0
  SecPkgContext_Bindings* ContextBindings = calloc(1, sizeof(SecPkgContext_Bindings));
801
802
0
  if (!ContextBindings)
803
0
    goto out_free;
804
805
0
  {
806
0
    const size_t slen = sizeof(SEC_CHANNEL_BINDINGS) + ChannelBindingTokenLength;
807
0
    if (slen > UINT32_MAX)
808
0
      goto out_free;
809
810
0
    ContextBindings->BindingsLength = (UINT32)slen;
811
0
  }
812
0
  ChannelBindings = (SEC_CHANNEL_BINDINGS*)calloc(1, ContextBindings->BindingsLength);
813
814
0
  if (!ChannelBindings)
815
0
    goto out_free;
816
817
0
  ContextBindings->Bindings = ChannelBindings;
818
0
  ChannelBindings->cbApplicationDataLength = (UINT32)ChannelBindingTokenLength;
819
0
  ChannelBindings->dwApplicationDataOffset = sizeof(SEC_CHANNEL_BINDINGS);
820
0
  ChannelBindingToken = &((BYTE*)ChannelBindings)[ChannelBindings->dwApplicationDataOffset];
821
0
  memcpy(ChannelBindingToken, TLS_SERVER_END_POINT, PrefixLength);
822
0
  memcpy(ChannelBindingToken + PrefixLength, CertificateHash, CertificateHashLength);
823
0
  free(CertificateHash);
824
0
  return ContextBindings;
825
0
out_free:
826
0
  free(CertificateHash);
827
0
  free(ContextBindings);
828
0
  return nullptr;
829
0
}
830
831
WINPR_ATTR_NODISCARD
832
static BOOL CALLBACK secrets_file_init_cb(WINPR_ATTR_UNUSED PINIT_ONCE once,
833
                                          WINPR_ATTR_UNUSED PVOID param,
834
                                          WINPR_ATTR_UNUSED PVOID* context)
835
0
{
836
0
  secrets_file_idx = SSL_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr);
837
838
0
  return (secrets_file_idx != -1);
839
0
}
840
841
static void SSLCTX_keylog_cb(const SSL* ssl, const char* line)
842
0
{
843
0
  char* dfile = nullptr;
844
845
0
  if (secrets_file_idx == -1)
846
0
    return;
847
848
0
  dfile = SSL_get_ex_data(ssl, secrets_file_idx);
849
0
  if (dfile)
850
0
  {
851
0
    FILE* f = winpr_fopen(dfile, "a+");
852
0
    if (f)
853
0
    {
854
0
      (void)fwrite(line, strlen(line), 1, f);
855
0
      (void)fwrite("\n", 1, 1, f);
856
0
      (void)fclose(f);
857
0
    }
858
0
  }
859
0
}
860
861
static void tls_reset(rdpTls* tls)
862
0
{
863
0
  WINPR_ASSERT(tls);
864
865
0
  if (tls->ctx)
866
0
  {
867
0
    SSL_CTX_free(tls->ctx);
868
0
    tls->ctx = nullptr;
869
0
  }
870
871
  /* tls->underlying is a stacked BIO under tls->bio.
872
   * BIO_free_all will free recursively. */
873
0
  if (tls->bio)
874
0
    BIO_free_all(tls->bio);
875
0
  else if (tls->underlying)
876
0
    BIO_free_all(tls->underlying);
877
0
  tls->bio = nullptr;
878
0
  tls->underlying = nullptr;
879
880
0
  free_tls_public_key(tls);
881
0
  free_tls_bindings(tls->Bindings);
882
0
  tls->Bindings = nullptr;
883
0
}
884
885
#if OPENSSL_VERSION_NUMBER >= 0x010000000L
886
WINPR_ATTR_NODISCARD
887
static BOOL tls_prepare(rdpTls* tls, BIO* underlying, const SSL_METHOD* method, int options,
888
                        BOOL clientMode)
889
#else
890
WINPR_ATTR_NODISCARD
891
static BOOL tls_prepare(rdpTls* tls, BIO* underlying, SSL_METHOD* method, int options,
892
                        BOOL clientMode)
893
#endif
894
0
{
895
0
  WINPR_ASSERT(tls);
896
897
0
  rdpSettings* settings = tls->context->settings;
898
0
  WINPR_ASSERT(settings);
899
900
0
  tls_reset(tls);
901
0
  tls->ctx = SSL_CTX_new(method);
902
903
0
  tls->underlying = underlying;
904
905
0
  if (!tls->ctx)
906
0
  {
907
0
    WLog_ERR(TAG, "SSL_CTX_new failed");
908
0
    return FALSE;
909
0
  }
910
911
0
  SSL_CTX_set_mode(tls->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
912
0
  SSL_CTX_set_options(tls->ctx, WINPR_ASSERTING_INT_CAST(uint64_t, options));
913
0
  SSL_CTX_set_read_ahead(tls->ctx, 1);
914
0
#if OPENSSL_VERSION_NUMBER >= 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
915
0
  UINT16 version = freerdp_settings_get_uint16(settings, FreeRDP_TLSMinVersion);
916
0
  if (!SSL_CTX_set_min_proto_version(tls->ctx, version))
917
0
  {
918
0
    WLog_ERR(TAG, "SSL_CTX_set_min_proto_version %" PRIu16 " failed", version);
919
0
    return FALSE;
920
0
  }
921
0
  version = freerdp_settings_get_uint16(settings, FreeRDP_TLSMaxVersion);
922
0
  if (!SSL_CTX_set_max_proto_version(tls->ctx, version))
923
0
  {
924
0
    WLog_ERR(TAG, "SSL_CTX_set_max_proto_version %" PRIu16 " failed", version);
925
0
    return FALSE;
926
0
  }
927
0
#endif
928
0
#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
929
0
  SSL_CTX_set_security_level(tls->ctx, WINPR_ASSERTING_INT_CAST(int, settings->TlsSecLevel));
930
0
#endif
931
932
0
  if (settings->AllowedTlsCiphers)
933
0
  {
934
0
    if (!SSL_CTX_set_cipher_list(tls->ctx, settings->AllowedTlsCiphers))
935
0
    {
936
0
      WLog_ERR(TAG, "SSL_CTX_set_cipher_list %s failed", settings->AllowedTlsCiphers);
937
0
      return FALSE;
938
0
    }
939
0
  }
940
941
0
  tls->bio = BIO_new_rdp_tls(tls->ctx, clientMode);
942
943
0
  if (!tls->bio)
944
0
  {
945
0
    WLog_ERR(TAG, "unable to create TLS BIO");
946
0
    return FALSE;
947
0
  }
948
949
0
  if (BIO_get_ssl(tls->bio, &tls->ssl) < 0 || !tls->ssl)
950
0
  {
951
0
    WLog_ERR(TAG, "unable to retrieve the SSL of the connection");
952
0
    return FALSE;
953
0
  }
954
955
0
  if (settings->TlsSecretsFile)
956
0
  {
957
0
#if OPENSSL_VERSION_NUMBER >= 0x10101000L
958
0
    if (!InitOnceExecuteOnce(&secrets_file_idx_once, secrets_file_init_cb, nullptr, nullptr))
959
0
      return FALSE;
960
961
0
    if (secrets_file_idx != -1)
962
0
    {
963
0
      SSL_set_ex_data(tls->ssl, secrets_file_idx, settings->TlsSecretsFile);
964
0
      SSL_CTX_set_keylog_callback(tls->ctx, SSLCTX_keylog_cb);
965
0
    }
966
#else
967
    WLog_WARN(TAG, "Key-Logging not available - requires OpenSSL 1.1.1 or higher");
968
#endif
969
0
  }
970
971
0
  BIO_push(tls->bio, underlying);
972
0
  return TRUE;
973
0
}
974
975
static void
976
adjustSslOptions(WINPR_ATTR_UNUSED int* options) // NOLINT(readability-non-const-parameter)
977
0
{
978
0
  WINPR_ASSERT(options);
979
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
980
  *options |= SSL_OP_NO_SSLv2;
981
  *options |= SSL_OP_NO_SSLv3;
982
#endif
983
0
}
984
985
const SSL_METHOD* freerdp_tls_get_ssl_method(BOOL isDtls, BOOL isClient)
986
0
{
987
0
  if (isClient)
988
0
  {
989
0
    if (isDtls)
990
0
      return DTLS_client_method();
991
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
992
    return SSLv23_client_method();
993
#else
994
0
    return TLS_client_method();
995
0
#endif
996
0
  }
997
998
0
  if (isDtls)
999
0
    return DTLS_server_method();
1000
1001
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
1002
  return SSLv23_server_method();
1003
#else
1004
0
  return TLS_server_method();
1005
0
#endif
1006
0
}
1007
1008
TlsHandshakeResult freerdp_tls_connect_ex(rdpTls* tls, BIO* underlying, const SSL_METHOD* methods)
1009
0
{
1010
0
  WINPR_ASSERT(tls);
1011
1012
0
  int options = 0;
1013
  /**
1014
   * SSL_OP_NO_COMPRESSION:
1015
   *
1016
   * The Microsoft RDP server does not advertise support
1017
   * for TLS compression, but alternative servers may support it.
1018
   * This was observed between early versions of the FreeRDP server
1019
   * and the FreeRDP client, and caused major performance issues,
1020
   * which is why we're disabling it.
1021
   */
1022
0
#ifdef SSL_OP_NO_COMPRESSION
1023
0
  options |= SSL_OP_NO_COMPRESSION;
1024
0
#endif
1025
  /**
1026
   * SSL_OP_TLS_BLOCK_PADDING_BUG:
1027
   *
1028
   * The Microsoft RDP server does *not* support TLS padding.
1029
   * It absolutely needs to be disabled otherwise it won't work.
1030
   */
1031
0
  options |= SSL_OP_TLS_BLOCK_PADDING_BUG;
1032
  /**
1033
   * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:
1034
   *
1035
   * Just like TLS padding, the Microsoft RDP server does not
1036
   * support empty fragments. This needs to be disabled.
1037
   */
1038
0
  options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1039
1040
0
  tls->isClientMode = TRUE;
1041
0
  adjustSslOptions(&options);
1042
1043
0
  if (!tls_prepare(tls, underlying, methods, options, TRUE))
1044
0
    return TLS_HANDSHAKE_ERROR;
1045
1046
0
#if !defined(OPENSSL_NO_TLSEXT)
1047
0
  const char* str = tls_get_server_name(tls);
1048
0
  void* ptr = WINPR_CAST_CONST_PTR_AWAY(str, void*);
1049
0
  SSL_set_tlsext_host_name(tls->ssl, ptr);
1050
0
#endif
1051
1052
0
  return freerdp_tls_handshake(tls);
1053
0
}
1054
1055
static int bio_err_print(const char* str, size_t len, void* u)
1056
0
{
1057
0
  wLog* log = u;
1058
0
  WLog_Print(log, WLOG_ERROR, "[BIO_do_handshake] %s [%" PRIuz "]", str, len);
1059
0
  return 0;
1060
0
}
1061
1062
TlsHandshakeResult freerdp_tls_handshake(rdpTls* tls)
1063
0
{
1064
0
  TlsHandshakeResult ret = TLS_HANDSHAKE_ERROR;
1065
1066
0
  WINPR_ASSERT(tls);
1067
0
  const long status = BIO_do_handshake(tls->bio);
1068
0
  if (status != 1)
1069
0
  {
1070
0
    if (!BIO_should_retry(tls->bio))
1071
0
    {
1072
0
      wLog* log = WLog_Get(TAG);
1073
0
      WLog_Print(log, WLOG_ERROR, "BIO_do_handshake failed");
1074
0
      ERR_print_errors_cb(bio_err_print, log);
1075
0
      return TLS_HANDSHAKE_ERROR;
1076
0
    }
1077
1078
0
    return TLS_HANDSHAKE_CONTINUE;
1079
0
  }
1080
1081
0
  int verify_status = 0;
1082
0
  rdpCertificate* cert = tls_get_certificate(tls, tls->isClientMode);
1083
1084
0
  if (!cert)
1085
0
  {
1086
0
    WLog_ERR(TAG, "tls_get_certificate failed to return the server certificate.");
1087
0
    return TLS_HANDSHAKE_ERROR;
1088
0
  }
1089
1090
0
  do
1091
0
  {
1092
0
    free_tls_bindings(tls->Bindings);
1093
0
    tls->Bindings = tls_get_channel_bindings(cert);
1094
0
    if (!tls->Bindings)
1095
0
    {
1096
0
      WLog_ERR(TAG, "unable to retrieve bindings");
1097
0
      break;
1098
0
    }
1099
1100
0
    free_tls_public_key(tls);
1101
0
    if (!freerdp_certificate_get_public_key(cert, &tls->PublicKey, &tls->PublicKeyLength))
1102
0
    {
1103
0
      WLog_ERR(TAG,
1104
0
               "freerdp_certificate_get_public_key failed to return the server public key.");
1105
0
      break;
1106
0
    }
1107
1108
    /* server-side NLA needs public keys (keys from us, the server) but no certificate verify */
1109
0
    ret = TLS_HANDSHAKE_SUCCESS;
1110
1111
0
    if (tls->isClientMode)
1112
0
    {
1113
0
      WINPR_ASSERT(tls->port <= UINT16_MAX);
1114
0
      verify_status =
1115
0
          tls_verify_certificate(tls, cert, tls_get_server_name(tls), (UINT16)tls->port);
1116
1117
0
      if (verify_status < 1)
1118
0
      {
1119
0
        WLog_ERR(TAG, "certificate not trusted, aborting.");
1120
0
        freerdp_tls_send_alert(tls);
1121
0
        ret = TLS_HANDSHAKE_VERIFY_ERROR;
1122
0
      }
1123
0
    }
1124
0
  } while (0);
1125
1126
0
  freerdp_certificate_free(cert);
1127
0
  return ret;
1128
0
}
1129
1130
static int pollAndHandshake(rdpTls* tls)
1131
0
{
1132
0
  WINPR_ASSERT(tls);
1133
1134
0
  do
1135
0
  {
1136
0
    HANDLE events[] = { freerdp_abort_event(tls->context), nullptr };
1137
0
    DWORD status = 0;
1138
0
    if (BIO_get_event(tls->bio, &events[1]) < 0)
1139
0
    {
1140
0
      WLog_ERR(TAG, "unable to retrieve BIO associated event");
1141
0
      return -1;
1142
0
    }
1143
1144
0
    if (!events[1])
1145
0
    {
1146
0
      WLog_ERR(TAG, "unable to retrieve BIO event");
1147
0
      return -1;
1148
0
    }
1149
1150
0
    status = WaitForMultipleObjectsEx(ARRAYSIZE(events), events, FALSE, INFINITE, TRUE);
1151
0
    switch (status)
1152
0
    {
1153
0
      case WAIT_OBJECT_0 + 1:
1154
0
        break;
1155
0
      case WAIT_OBJECT_0:
1156
0
        WLog_DBG(TAG, "Abort event set, cancel connect");
1157
0
        return -1;
1158
0
      case WAIT_TIMEOUT:
1159
0
      case WAIT_IO_COMPLETION:
1160
0
        continue;
1161
0
      default:
1162
0
        WLog_ERR(TAG, "error during WaitForSingleObject(): 0x%08" PRIX32 "", status);
1163
0
        return -1;
1164
0
    }
1165
1166
0
    TlsHandshakeResult result = freerdp_tls_handshake(tls);
1167
0
    switch (result)
1168
0
    {
1169
0
      case TLS_HANDSHAKE_CONTINUE:
1170
0
        break;
1171
0
      case TLS_HANDSHAKE_SUCCESS:
1172
0
        return 1;
1173
0
      case TLS_HANDSHAKE_ERROR:
1174
0
      case TLS_HANDSHAKE_VERIFY_ERROR:
1175
0
      default:
1176
0
        return -1;
1177
0
    }
1178
0
  } while (TRUE);
1179
0
}
1180
1181
int freerdp_tls_connect(rdpTls* tls, BIO* underlying)
1182
0
{
1183
0
  const SSL_METHOD* method = freerdp_tls_get_ssl_method(FALSE, TRUE);
1184
1185
0
  WINPR_ASSERT(tls);
1186
0
  TlsHandshakeResult result = freerdp_tls_connect_ex(tls, underlying, method);
1187
0
  switch (result)
1188
0
  {
1189
0
    case TLS_HANDSHAKE_SUCCESS:
1190
0
      return 1;
1191
0
    case TLS_HANDSHAKE_CONTINUE:
1192
0
      break;
1193
0
    case TLS_HANDSHAKE_ERROR:
1194
0
    case TLS_HANDSHAKE_VERIFY_ERROR:
1195
0
      return -1;
1196
0
    default:
1197
0
      return -1;
1198
0
  }
1199
1200
0
  return pollAndHandshake(tls);
1201
0
}
1202
1203
#if defined(MICROSOFT_IOS_SNI_BUG) && !defined(OPENSSL_NO_TLSEXT) && \
1204
    !defined(LIBRESSL_VERSION_NUMBER)
1205
static void tls_openssl_tlsext_debug_callback(SSL* s, int client_server, int type,
1206
                                              unsigned char* data, int len, void* arg)
1207
{
1208
  if (type == TLSEXT_TYPE_server_name)
1209
  {
1210
    WLog_DBG(TAG, "Client uses SNI (extension disabled)");
1211
    s->servername_done = 2;
1212
  }
1213
}
1214
#endif
1215
1216
BOOL freerdp_tls_accept(rdpTls* tls, BIO* underlying, rdpSettings* settings)
1217
0
{
1218
0
  WINPR_ASSERT(tls);
1219
0
  TlsHandshakeResult res =
1220
0
      freerdp_tls_accept_ex(tls, underlying, settings, freerdp_tls_get_ssl_method(FALSE, FALSE));
1221
0
  switch (res)
1222
0
  {
1223
0
    case TLS_HANDSHAKE_SUCCESS:
1224
0
      return TRUE;
1225
0
    case TLS_HANDSHAKE_CONTINUE:
1226
0
      break;
1227
0
    case TLS_HANDSHAKE_ERROR:
1228
0
    case TLS_HANDSHAKE_VERIFY_ERROR:
1229
0
    default:
1230
0
      return FALSE;
1231
0
  }
1232
1233
0
  return pollAndHandshake(tls) > 0;
1234
0
}
1235
1236
TlsHandshakeResult freerdp_tls_accept_ex(rdpTls* tls, BIO* underlying, rdpSettings* settings,
1237
                                         const SSL_METHOD* methods)
1238
0
{
1239
0
  WINPR_ASSERT(tls);
1240
1241
0
  int options = 0;
1242
0
  int status = 0;
1243
1244
  /**
1245
   * SSL_OP_NO_SSLv2:
1246
   *
1247
   * We only want SSLv3 and TLSv1, so disable SSLv2.
1248
   * SSLv3 is used by, eg. Microsoft RDC for Mac OS X.
1249
   */
1250
0
  options |= SSL_OP_NO_SSLv2;
1251
  /**
1252
   * SSL_OP_NO_COMPRESSION:
1253
   *
1254
   * The Microsoft RDP server does not advertise support
1255
   * for TLS compression, but alternative servers may support it.
1256
   * This was observed between early versions of the FreeRDP server
1257
   * and the FreeRDP client, and caused major performance issues,
1258
   * which is why we're disabling it.
1259
   */
1260
0
#ifdef SSL_OP_NO_COMPRESSION
1261
0
  options |= SSL_OP_NO_COMPRESSION;
1262
0
#endif
1263
  /**
1264
   * SSL_OP_TLS_BLOCK_PADDING_BUG:
1265
   *
1266
   * The Microsoft RDP server does *not* support TLS padding.
1267
   * It absolutely needs to be disabled otherwise it won't work.
1268
   */
1269
0
  options |= SSL_OP_TLS_BLOCK_PADDING_BUG;
1270
  /**
1271
   * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:
1272
   *
1273
   * Just like TLS padding, the Microsoft RDP server does not
1274
   * support empty fragments. This needs to be disabled.
1275
   */
1276
0
  options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
1277
1278
  /**
1279
   * SSL_OP_NO_RENEGOTIATION
1280
   *
1281
   * Disable SSL client site renegotiation.
1282
   */
1283
1284
0
#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && (OPENSSL_VERSION_NUMBER < 0x30000000L) && \
1285
0
    !defined(LIBRESSL_VERSION_NUMBER)
1286
0
  options |= SSL_OP_NO_RENEGOTIATION;
1287
0
#endif
1288
1289
0
  if (!tls_prepare(tls, underlying, methods, options, FALSE))
1290
0
    return TLS_HANDSHAKE_ERROR;
1291
1292
0
  const rdpPrivateKey* key = freerdp_settings_get_pointer(settings, FreeRDP_RdpServerRsaKey);
1293
0
  if (!key)
1294
0
  {
1295
0
    WLog_ERR(TAG, "invalid private key");
1296
0
    return TLS_HANDSHAKE_ERROR;
1297
0
  }
1298
1299
0
  EVP_PKEY* privkey = freerdp_key_get_evp_pkey(key);
1300
0
  if (!privkey)
1301
0
  {
1302
0
    WLog_ERR(TAG, "invalid private key");
1303
0
    return TLS_HANDSHAKE_ERROR;
1304
0
  }
1305
1306
0
  status = SSL_use_PrivateKey(tls->ssl, privkey);
1307
  /* The local reference to the private key will anyway go out of
1308
   * scope; so the reference count should be decremented whether
1309
   * SSL_use_PrivateKey succeeds or fails.
1310
   */
1311
0
  EVP_PKEY_free(privkey);
1312
1313
0
  if (status <= 0)
1314
0
  {
1315
0
    WLog_ERR(TAG, "SSL_CTX_use_PrivateKey_file failed");
1316
0
    return TLS_HANDSHAKE_ERROR;
1317
0
  }
1318
1319
0
  rdpCertificate* cert =
1320
0
      freerdp_settings_get_pointer_writable(settings, FreeRDP_RdpServerCertificate);
1321
0
  if (!cert)
1322
0
  {
1323
0
    WLog_ERR(TAG, "invalid certificate");
1324
0
    return TLS_HANDSHAKE_ERROR;
1325
0
  }
1326
1327
0
  status = SSL_use_certificate(tls->ssl, freerdp_certificate_get_x509(cert));
1328
1329
0
  if (status <= 0)
1330
0
  {
1331
0
    WLog_ERR(TAG, "SSL_use_certificate_file failed");
1332
0
    return TLS_HANDSHAKE_ERROR;
1333
0
  }
1334
1335
0
  const size_t cnt = freerdp_certificate_get_chain_len(cert);
1336
0
  for (size_t x = 0; x < cnt; x++)
1337
0
  {
1338
0
    X509* xcert = freerdp_certificate_get_chain_at(cert, x);
1339
0
    WINPR_ASSERT(xcert);
1340
0
    const long rc = SSL_add1_chain_cert(tls->ssl, xcert);
1341
0
    if (rc != 1)
1342
0
    {
1343
0
      WLog_ERR(TAG, "SSL_add1_chain_cert failed");
1344
0
      return TLS_HANDSHAKE_ERROR;
1345
0
    }
1346
0
  }
1347
1348
#if defined(MICROSOFT_IOS_SNI_BUG) && !defined(OPENSSL_NO_TLSEXT) && \
1349
    !defined(LIBRESSL_VERSION_NUMBER)
1350
  SSL_set_tlsext_debug_callback(tls->ssl, tls_openssl_tlsext_debug_callback);
1351
#endif
1352
1353
0
  return freerdp_tls_handshake(tls);
1354
0
}
1355
1356
BOOL freerdp_tls_send_alert(rdpTls* tls)
1357
0
{
1358
0
  WINPR_ASSERT(tls);
1359
1360
0
  if (!tls)
1361
0
    return FALSE;
1362
1363
0
  if (!tls->ssl)
1364
0
    return TRUE;
1365
1366
  /**
1367
   * FIXME: The following code does not work on OpenSSL > 1.1.0 because the
1368
   *        SSL struct is opaque now
1369
   */
1370
#if (!defined(LIBRESSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER < 0x10100000L)) || \
1371
    (defined(LIBRESSL_VERSION_NUMBER) && (LIBRESSL_VERSION_NUMBER <= 0x2080300fL))
1372
1373
  if (tls->alertDescription != TLS_ALERT_DESCRIPTION_CLOSE_NOTIFY)
1374
  {
1375
    /**
1376
     * OpenSSL doesn't really expose an API for sending a TLS alert manually.
1377
     *
1378
     * The following code disables the sending of the default "close notify"
1379
     * and then proceeds to force sending a custom TLS alert before shutting down.
1380
     *
1381
     * Manually sending a TLS alert is necessary in certain cases,
1382
     * like when server-side NLA results in an authentication failure.
1383
     */
1384
    SSL_SESSION* ssl_session = SSL_get_session(tls->ssl);
1385
    SSL_CTX* ssl_ctx = SSL_get_SSL_CTX(tls->ssl);
1386
    SSL_set_quiet_shutdown(tls->ssl, 1);
1387
1388
    if ((tls->alertLevel == TLS_ALERT_LEVEL_FATAL) && (ssl_session))
1389
      SSL_CTX_remove_session(ssl_ctx, ssl_session);
1390
1391
    tls->ssl->s3->alert_dispatch = 1;
1392
    tls->ssl->s3->send_alert[0] = tls->alertLevel;
1393
    tls->ssl->s3->send_alert[1] = tls->alertDescription;
1394
1395
    if (tls->ssl->s3->wbuf.left == 0)
1396
      tls->ssl->method->ssl_dispatch_alert(tls->ssl);
1397
  }
1398
1399
#endif
1400
0
  return TRUE;
1401
0
}
1402
1403
int freerdp_tls_write_all(rdpTls* tls, const BYTE* data, size_t length)
1404
0
{
1405
0
  WINPR_ASSERT(tls);
1406
0
  size_t offset = 0;
1407
0
  BIO* bio = tls->bio;
1408
1409
0
  if (length > INT32_MAX)
1410
0
    return -1;
1411
1412
0
  while (offset < length)
1413
0
  {
1414
0
    ERR_clear_error();
1415
0
    const int status = BIO_write(bio, &data[offset], (int)(length - offset));
1416
1417
0
    if (status > 0)
1418
0
      offset += (size_t)status;
1419
0
    else
1420
0
    {
1421
0
      if (!BIO_should_retry(bio))
1422
0
        return -1;
1423
1424
0
      if (BIO_write_blocked(bio))
1425
0
      {
1426
0
        const long rc = BIO_wait_write(bio, 100);
1427
0
        if (rc < 0)
1428
0
          return -1;
1429
0
      }
1430
0
      else if (BIO_read_blocked(bio))
1431
0
        return -2; /* Abort write, there is data that must be read */
1432
0
      else
1433
0
        USleep(100);
1434
0
    }
1435
0
  }
1436
1437
0
  return (int)length;
1438
0
}
1439
1440
int freerdp_tls_set_alert_code(rdpTls* tls, int level, int description)
1441
0
{
1442
0
  WINPR_ASSERT(tls);
1443
0
  tls->alertLevel = level;
1444
0
  tls->alertDescription = description;
1445
0
  return 0;
1446
0
}
1447
1448
WINPR_ATTR_NODISCARD
1449
static BOOL is_redirected(rdpTls* tls)
1450
0
{
1451
0
  rdpSettings* settings = tls->context->settings;
1452
1453
0
  if (settings->GatewayArmTransport)
1454
0
    return TRUE;
1455
1456
0
  if (LB_NOREDIRECT & settings->RedirectionFlags)
1457
0
    return FALSE;
1458
1459
0
  return settings->RedirectionFlags != 0;
1460
0
}
1461
1462
WINPR_ATTR_NODISCARD
1463
static BOOL is_accepted(rdpTls* tls, const rdpCertificate* cert)
1464
0
{
1465
0
  WINPR_ASSERT(tls);
1466
0
  WINPR_ASSERT(tls->context);
1467
0
  WINPR_ASSERT(cert);
1468
0
  rdpSettings* settings = tls->context->settings;
1469
0
  WINPR_ASSERT(settings);
1470
1471
0
  FreeRDP_Settings_Keys_String keyAccepted = FreeRDP_AcceptedCert;
1472
0
  FreeRDP_Settings_Keys_UInt32 keyLength = FreeRDP_AcceptedCertLength;
1473
1474
0
  if (tls->isGatewayTransport)
1475
0
  {
1476
0
    keyAccepted = FreeRDP_GatewayAcceptedCert;
1477
0
    keyLength = FreeRDP_GatewayAcceptedCertLength;
1478
0
  }
1479
0
  else if (is_redirected(tls))
1480
0
  {
1481
0
    keyAccepted = FreeRDP_RedirectionAcceptedCert;
1482
0
    keyLength = FreeRDP_RedirectionAcceptedCertLength;
1483
0
  }
1484
1485
0
  const char* AcceptedKey = freerdp_settings_get_string(settings, keyAccepted);
1486
0
  const UINT32 AcceptedKeyLength = freerdp_settings_get_uint32(settings, keyLength);
1487
1488
0
  if ((AcceptedKeyLength > 0) && AcceptedKey)
1489
0
  {
1490
0
    BOOL accepted = FALSE;
1491
0
    size_t pemLength = 0;
1492
0
    char* pem = freerdp_certificate_get_pem_ex(cert, &pemLength, FALSE);
1493
0
    if (pem && (AcceptedKeyLength == pemLength))
1494
0
    {
1495
0
      if (memcmp(AcceptedKey, pem, AcceptedKeyLength) == 0)
1496
0
        accepted = TRUE;
1497
0
    }
1498
0
    free(pem);
1499
0
    if (accepted)
1500
0
      return TRUE;
1501
0
  }
1502
1503
0
  if (!freerdp_settings_set_string(settings, keyAccepted, nullptr))
1504
0
    WLog_WARN(TAG, "freerdp_settings_set_string(settings, keyAccepted=%d, nullptr) failed",
1505
0
              keyAccepted);
1506
0
  if (!freerdp_settings_set_uint32(settings, keyLength, 0))
1507
0
    WLog_WARN(TAG, "freerdp_settings_set_uint32(settings, keyLength=%d, 0) failed", keyLength);
1508
1509
0
  return FALSE;
1510
0
}
1511
1512
WINPR_ATTR_NODISCARD
1513
static BOOL compare_fingerprint(const char* fp, const char* hash, const rdpCertificate* cert,
1514
                                BOOL separator)
1515
0
{
1516
0
  BOOL equal = 0;
1517
0
  char* strhash = nullptr;
1518
1519
0
  WINPR_ASSERT(fp);
1520
0
  WINPR_ASSERT(hash);
1521
0
  WINPR_ASSERT(cert);
1522
1523
0
  strhash = freerdp_certificate_get_fingerprint_by_hash_ex(cert, hash, separator);
1524
0
  if (!strhash)
1525
0
    return FALSE;
1526
1527
0
  equal = (_stricmp(strhash, fp) == 0);
1528
0
  free(strhash);
1529
0
  return equal;
1530
0
}
1531
1532
WINPR_ATTR_NODISCARD
1533
static BOOL compare_fingerprint_all(const char* fp, const char* hash, const rdpCertificate* cert)
1534
0
{
1535
0
  WINPR_ASSERT(fp);
1536
0
  WINPR_ASSERT(hash);
1537
0
  WINPR_ASSERT(cert);
1538
0
  if (compare_fingerprint(fp, hash, cert, FALSE))
1539
0
    return TRUE;
1540
0
  if (compare_fingerprint(fp, hash, cert, TRUE))
1541
0
    return TRUE;
1542
0
  return FALSE;
1543
0
}
1544
1545
WINPR_ATTR_NODISCARD
1546
static BOOL is_accepted_fingerprint(const rdpCertificate* cert,
1547
                                    const char* CertificateAcceptedFingerprints)
1548
0
{
1549
0
  WINPR_ASSERT(cert);
1550
1551
0
  BOOL rc = FALSE;
1552
0
  if (CertificateAcceptedFingerprints)
1553
0
  {
1554
0
    char* context = nullptr;
1555
0
    char* copy = _strdup(CertificateAcceptedFingerprints);
1556
0
    char* cur = strtok_s(copy, ",", &context);
1557
0
    while (cur)
1558
0
    {
1559
0
      char* subcontext = nullptr;
1560
0
      const char* h = strtok_s(cur, ":", &subcontext);
1561
1562
0
      if (!h)
1563
0
        goto next;
1564
1565
0
      {
1566
0
        const char* fp = h + strlen(h) + 1;
1567
0
        if (compare_fingerprint_all(fp, h, cert))
1568
0
        {
1569
0
          rc = TRUE;
1570
0
          break;
1571
0
        }
1572
0
      }
1573
0
    next:
1574
0
      cur = strtok_s(nullptr, ",", &context);
1575
0
    }
1576
0
    free(copy);
1577
0
  }
1578
1579
0
  return rc;
1580
0
}
1581
1582
WINPR_ATTR_NODISCARD
1583
static BOOL accept_cert(rdpTls* tls, const rdpCertificate* cert)
1584
0
{
1585
0
  WINPR_ASSERT(tls);
1586
0
  WINPR_ASSERT(tls->context);
1587
0
  WINPR_ASSERT(cert);
1588
1589
0
  FreeRDP_Settings_Keys_String id = FreeRDP_AcceptedCert;
1590
0
  FreeRDP_Settings_Keys_UInt32 lid = FreeRDP_AcceptedCertLength;
1591
1592
0
  rdpSettings* settings = tls->context->settings;
1593
0
  WINPR_ASSERT(settings);
1594
1595
0
  if (tls->isGatewayTransport)
1596
0
  {
1597
0
    id = FreeRDP_GatewayAcceptedCert;
1598
0
    lid = FreeRDP_GatewayAcceptedCertLength;
1599
0
  }
1600
0
  else if (is_redirected(tls))
1601
0
  {
1602
0
    id = FreeRDP_RedirectionAcceptedCert;
1603
0
    lid = FreeRDP_RedirectionAcceptedCertLength;
1604
0
  }
1605
1606
0
  size_t pemLength = 0;
1607
0
  char* pem = freerdp_certificate_get_pem_ex(cert, &pemLength, FALSE);
1608
0
  BOOL rc = FALSE;
1609
0
  if (pemLength <= UINT32_MAX)
1610
0
  {
1611
0
    if (freerdp_settings_set_string_len(settings, id, pem, pemLength))
1612
0
      rc = freerdp_settings_set_uint32(settings, lid, (UINT32)pemLength);
1613
0
  }
1614
0
  free(pem);
1615
0
  return rc;
1616
0
}
1617
1618
WINPR_ATTR_NODISCARD
1619
static BOOL tls_extract_full_pem(const rdpCertificate* cert, BYTE** PublicKey,
1620
                                 size_t* PublicKeyLength)
1621
0
{
1622
0
  if (!cert || !PublicKey)
1623
0
    return FALSE;
1624
0
  *PublicKey = (BYTE*)freerdp_certificate_get_pem(cert, PublicKeyLength);
1625
0
  return *PublicKey != nullptr;
1626
0
}
1627
1628
WINPR_ATTR_NODISCARD
1629
static int tls_config_parse_bool(WINPR_JSON* json, const char* opt)
1630
0
{
1631
0
  WINPR_JSON* val = WINPR_JSON_GetObjectItemCaseSensitive(json, opt);
1632
0
  if (!val || !WINPR_JSON_IsBool(val))
1633
0
    return -1;
1634
1635
0
  if (WINPR_JSON_IsTrue(val))
1636
0
    return 1;
1637
0
  return 0;
1638
0
}
1639
1640
WINPR_ATTR_NODISCARD
1641
static int tls_config_check_allowed_hashed(const char* configfile, const rdpCertificate* cert,
1642
                                           WINPR_JSON* json)
1643
0
{
1644
0
  WINPR_ASSERT(configfile);
1645
0
  WINPR_ASSERT(cert);
1646
0
  WINPR_ASSERT(json);
1647
1648
0
  WINPR_JSON* db = WINPR_JSON_GetObjectItemCaseSensitive(json, "certificate-db");
1649
0
  if (!db || !WINPR_JSON_IsArray(db))
1650
0
    return 0;
1651
1652
0
  for (size_t x = 0; x < WINPR_JSON_GetArraySize(db); x++)
1653
0
  {
1654
0
    WINPR_JSON* cur = WINPR_JSON_GetArrayItem(db, x);
1655
0
    if (!cur || !WINPR_JSON_IsObject(cur))
1656
0
    {
1657
0
      WLog_WARN(TAG,
1658
0
                "[%s] invalid certificate-db entry at position %" PRIuz ": not a JSON object",
1659
0
                configfile, x);
1660
0
      continue;
1661
0
    }
1662
1663
0
    WINPR_JSON* key = WINPR_JSON_GetObjectItemCaseSensitive(cur, "type");
1664
0
    if (!key || !WINPR_JSON_IsString(key))
1665
0
    {
1666
0
      WLog_WARN(TAG,
1667
0
                "[%s] invalid certificate-db entry at position %" PRIuz
1668
0
                ": invalid 'type' element, expected type string",
1669
0
                configfile, x);
1670
0
      continue;
1671
0
    }
1672
0
    WINPR_JSON* val = WINPR_JSON_GetObjectItemCaseSensitive(cur, "hash");
1673
0
    if (!val || !WINPR_JSON_IsString(val))
1674
0
    {
1675
0
      WLog_WARN(TAG,
1676
0
                "[%s] invalid certificate-db entry at position %" PRIuz
1677
0
                ": invalid 'hash' element, expected type string",
1678
0
                configfile, x);
1679
0
      continue;
1680
0
    }
1681
1682
0
    const char* skey = WINPR_JSON_GetStringValue(key);
1683
0
    const char* sval = WINPR_JSON_GetStringValue(val);
1684
1685
0
    char* hash = freerdp_certificate_get_fingerprint_by_hash_ex(cert, skey, FALSE);
1686
0
    if (!hash)
1687
0
    {
1688
0
      WLog_WARN(TAG,
1689
0
                "[%s] invalid certificate-db entry at position %" PRIuz
1690
0
                ": hash type '%s' not supported by certificate",
1691
0
                configfile, x, skey);
1692
0
      continue;
1693
0
    }
1694
1695
0
    const int cmp = _stricmp(hash, sval);
1696
0
    free(hash);
1697
1698
0
    if (cmp == 0)
1699
0
      return 1;
1700
0
  }
1701
1702
0
  return 0;
1703
0
}
1704
1705
WINPR_ATTR_NODISCARD
1706
static int tls_config_check_certificate(const rdpCertificate* cert, BOOL* pAllowUserconfig)
1707
0
{
1708
0
  WINPR_ASSERT(cert);
1709
0
  WINPR_ASSERT(pAllowUserconfig);
1710
1711
0
  int rc = 0;
1712
0
  const char configfile[] = "certificates.json";
1713
0
  WINPR_JSON* json = freerdp_GetJSONConfigFile(TRUE, configfile);
1714
1715
0
  if (!json)
1716
0
  {
1717
0
    WLog_DBG(TAG, "No or no valid configuration file for certificate handling, asking user");
1718
0
    goto fail;
1719
0
  }
1720
1721
0
  if (tls_config_parse_bool(json, "deny") > 0)
1722
0
  {
1723
0
    WLog_WARN(TAG, "[%s] certificate denied by configuration", configfile);
1724
0
    rc = -1;
1725
0
    goto fail;
1726
0
  }
1727
1728
0
  if (tls_config_parse_bool(json, "ignore") > 0)
1729
0
  {
1730
0
    WLog_WARN(TAG, "[%s] certificate ignored by configuration", configfile);
1731
0
    rc = 1;
1732
0
    goto fail;
1733
0
  }
1734
1735
0
  if (tls_config_check_allowed_hashed(configfile, cert, json) > 0)
1736
0
  {
1737
0
    WLog_WARN(TAG, "[%s] certificate manually accepted by configuration", configfile);
1738
0
    rc = 1;
1739
0
    goto fail;
1740
0
  }
1741
1742
0
  if (tls_config_parse_bool(json, "deny-userconfig") > 0)
1743
0
  {
1744
0
    WLog_WARN(TAG, "[%s] configuration denies user to accept certificates", configfile);
1745
0
    rc = -1;
1746
0
    goto fail;
1747
0
  }
1748
1749
0
fail:
1750
1751
0
  *pAllowUserconfig = (rc == 0);
1752
0
  WINPR_JSON_Delete(json);
1753
0
  return rc;
1754
0
}
1755
1756
int tls_verify_certificate(rdpTls* tls, const rdpCertificate* cert, const char* hostname,
1757
                           UINT16 port)
1758
0
{
1759
0
  int match = 0;
1760
0
  size_t length = 0;
1761
0
  BOOL certificate_status = 0;
1762
0
  char* common_name = nullptr;
1763
0
  size_t common_name_length = 0;
1764
0
  int verification_status = -1;
1765
0
  BOOL hostname_match = FALSE;
1766
0
  rdpCertificateData* certificate_data = nullptr;
1767
0
  BYTE* pemCert = nullptr;
1768
0
  DWORD flags = VERIFY_CERT_FLAG_NONE;
1769
1770
0
  WINPR_ASSERT(tls);
1771
1772
0
  rdpContext* context = tls->context;
1773
0
  WINPR_ASSERT(context);
1774
1775
0
  freerdp* instance = context->instance;
1776
0
  WINPR_ASSERT(instance);
1777
1778
0
  const rdpSettings* settings = context->settings;
1779
0
  WINPR_ASSERT(settings);
1780
1781
0
  if (freerdp_shall_disconnect_context(context))
1782
0
    return -1;
1783
1784
0
  if (!tls_extract_full_pem(cert, &pemCert, &length))
1785
0
    goto end;
1786
1787
  /* Check, if we already accepted this key. */
1788
0
  if (is_accepted(tls, cert))
1789
0
  {
1790
0
    verification_status = 1;
1791
0
    goto end;
1792
0
  }
1793
1794
0
  if (is_accepted_fingerprint(cert, settings->CertificateAcceptedFingerprints))
1795
0
  {
1796
0
    verification_status = 1;
1797
0
    goto end;
1798
0
  }
1799
1800
0
  if (tls->isGatewayTransport || is_redirected(tls))
1801
0
    flags |= VERIFY_CERT_FLAG_LEGACY;
1802
1803
0
  if (tls->isGatewayTransport)
1804
0
    flags |= VERIFY_CERT_FLAG_GATEWAY;
1805
1806
0
  if (is_redirected(tls))
1807
0
    flags |= VERIFY_CERT_FLAG_REDIRECT;
1808
1809
  /* Certificate management is done by the application */
1810
0
  if (settings->ExternalCertificateManagement)
1811
0
  {
1812
0
    if (instance->VerifyX509Certificate)
1813
0
      verification_status =
1814
0
          instance->VerifyX509Certificate(instance, pemCert, length, hostname, port, flags);
1815
0
    else
1816
0
      WLog_ERR(TAG, "No VerifyX509Certificate callback registered!");
1817
1818
0
    if (verification_status > 0)
1819
0
    {
1820
0
      if (!accept_cert(tls, cert))
1821
0
        goto end;
1822
0
    }
1823
0
    else if (verification_status < 0)
1824
0
    {
1825
0
      WLog_ERR(TAG, "VerifyX509Certificate failed: (length = %" PRIuz ") status: [%d] %s",
1826
0
               length, verification_status, pemCert);
1827
0
      goto end;
1828
0
    }
1829
0
  }
1830
  /* ignore certificate verification if user explicitly required it (discouraged) */
1831
0
  else if (freerdp_settings_get_bool(settings, FreeRDP_IgnoreCertificate))
1832
0
  {
1833
0
    WLog_WARN(TAG, "[DANGER] Certificate not checked, /cert:ignore in use.");
1834
0
    WLog_WARN(TAG, "[DANGER] This prevents MITM attacks from being detected!");
1835
0
    WLog_WARN(TAG,
1836
0
              "[DANGER] Avoid using this unless in a secure LAN (=no internet) environment");
1837
0
    verification_status = 1; /* success! */
1838
0
  }
1839
0
  else if (!tls->isGatewayTransport && (settings->AuthenticationLevel == 0))
1840
0
    verification_status = 1; /* success! */
1841
0
  else
1842
0
  {
1843
    /* if user explicitly specified a certificate name, use it instead of the hostname */
1844
0
    if (!tls->isGatewayTransport && settings->CertificateName)
1845
0
      hostname = settings->CertificateName;
1846
1847
    /* attempt verification using OpenSSL and the ~/.freerdp/certs certificate store */
1848
0
    certificate_status = freerdp_certificate_verify(
1849
0
        cert, freerdp_certificate_store_get_certs_path(tls->certificate_store));
1850
    /* verify certificate name match */
1851
0
    certificate_data = freerdp_certificate_data_new(hostname, port, cert);
1852
0
    if (!certificate_data)
1853
0
      goto end;
1854
    /* extra common name and alternative names */
1855
0
    common_name = freerdp_certificate_get_common_name(cert, &common_name_length);
1856
1857
0
    const size_t hostlen = strlen(hostname);
1858
0
    if (freerdp_certificate_matches_hostname(cert, hostname, hostlen))
1859
0
      hostname_match = TRUE;
1860
1861
    /* if the certificate is valid and the certificate name matches, verification succeeds
1862
     */
1863
0
    if (certificate_status && hostname_match)
1864
0
      verification_status = 1; /* success! */
1865
1866
0
    if (!hostname_match)
1867
0
      flags |= VERIFY_CERT_FLAG_MISMATCH;
1868
1869
0
    BOOL allowUserconfig = TRUE;
1870
0
    if (!certificate_status || !hostname_match)
1871
0
      verification_status = tls_config_check_certificate(cert, &allowUserconfig);
1872
1873
    /* verification could not succeed with OpenSSL, use known_hosts file and prompt user for
1874
     * manual verification */
1875
0
    if (allowUserconfig && (!certificate_status || !hostname_match))
1876
0
    {
1877
0
      DWORD accept_certificate = 0;
1878
0
      size_t pem_length = 0;
1879
0
      char* issuer = freerdp_certificate_get_issuer(cert);
1880
0
      char* subject = freerdp_certificate_get_subject(cert);
1881
0
      char* pem = freerdp_certificate_get_pem(cert, &pem_length);
1882
1883
0
      if (!pem)
1884
0
        goto end;
1885
1886
      /* search for matching entry in known_hosts file */
1887
0
      match =
1888
0
          freerdp_certificate_store_contains_data(tls->certificate_store, certificate_data);
1889
1890
0
      if (match == 1)
1891
0
      {
1892
        /* no entry was found in known_hosts file, prompt user for manual verification
1893
         */
1894
0
        if (!hostname_match)
1895
0
          tls_print_certificate_name_mismatch_error(cert, hostname, port);
1896
1897
0
        {
1898
0
          const char* type = "";
1899
0
          if (freerdp_settings_get_bool(settings, FreeRDP_AutoAcceptCertificate))
1900
0
            type = "tofo (auto-accept)";
1901
1902
0
          if (freerdp_settings_get_bool(settings, FreeRDP_AutoDenyCertificate))
1903
0
            type = "strict (auto-deny)";
1904
1905
0
          if (freerdp_settings_get_bool(settings, FreeRDP_IgnoreCertificate))
1906
0
            type = "ignore (no check)";
1907
1908
0
          char* efp = freerdp_certificate_get_fingerprint(cert);
1909
0
          tls_print_new_certificate_warn(tls->certificate_store, hostname, port, type,
1910
0
                                         efp);
1911
0
          free(efp);
1912
0
        }
1913
1914
0
#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
1915
0
        WINPR_PRAGMA_DIAG_PUSH
1916
0
        WINPR_PRAGMA_DIAG_IGNORED_DEPRECATED_DECL
1917
0
#endif
1918
1919
        /* Automatically accept certificate on first use */
1920
0
        if (settings->AutoAcceptCertificate)
1921
0
        {
1922
0
          WLog_INFO(TAG, "No certificate stored, automatically accepting.");
1923
0
          accept_certificate = 1;
1924
0
        }
1925
0
        else if (settings->AutoDenyCertificate)
1926
0
        {
1927
0
          WLog_INFO(TAG, "No certificate stored, automatically denying.");
1928
0
          accept_certificate = 0;
1929
0
        }
1930
0
        else if (instance->VerifyX509Certificate)
1931
0
        {
1932
0
          int rc = instance->VerifyX509Certificate(instance, pemCert, pem_length,
1933
0
                                                   hostname, port, flags);
1934
1935
0
          if (rc == 1)
1936
0
            accept_certificate = 1;
1937
0
          else if (rc > 1)
1938
0
            accept_certificate = 2;
1939
0
          else
1940
0
            accept_certificate = 0;
1941
0
        }
1942
0
        else if (instance->VerifyCertificateEx)
1943
0
        {
1944
0
          const BOOL use_pem =
1945
0
              freerdp_settings_get_bool(settings, FreeRDP_CertificateCallbackPreferPEM);
1946
0
          char* fp = nullptr;
1947
0
          DWORD cflags = flags;
1948
0
          if (use_pem)
1949
0
          {
1950
0
            cflags |= VERIFY_CERT_FLAG_FP_IS_PEM;
1951
0
            fp = pem;
1952
0
          }
1953
0
          else
1954
0
            fp = freerdp_certificate_get_fingerprint(cert);
1955
0
          accept_certificate = instance->VerifyCertificateEx(
1956
0
              instance, hostname, port, common_name, subject, issuer, fp, cflags);
1957
0
          if (!use_pem)
1958
0
            free(fp);
1959
0
        }
1960
0
#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
1961
0
        else if (instance->VerifyCertificate)
1962
0
        {
1963
0
          char* fp = freerdp_certificate_get_fingerprint(cert);
1964
1965
0
          WLog_WARN(TAG, "The VerifyCertificate callback is deprecated, migrate your "
1966
0
                         "application to VerifyCertificateEx");
1967
0
          accept_certificate = instance->VerifyCertificate(instance, common_name, subject,
1968
0
                                                           issuer, fp, !hostname_match);
1969
0
          free(fp);
1970
0
        }
1971
0
#endif
1972
0
      }
1973
0
      else if (match == -1)
1974
0
      {
1975
0
        rdpCertificateData* stored_data =
1976
0
            freerdp_certificate_store_load_data(tls->certificate_store, hostname, port);
1977
        /* entry was found in known_hosts file, but fingerprint does not match. ask user
1978
         * to use it */
1979
0
        {
1980
0
          char* efp = freerdp_certificate_get_fingerprint(cert);
1981
0
          tls_print_certificate_error(tls->certificate_store, stored_data, hostname, port,
1982
0
                                      efp);
1983
0
          free(efp);
1984
0
        }
1985
1986
0
        if (!stored_data)
1987
0
          WLog_WARN(TAG, "Failed to get certificate entry for %s:%" PRIu16 "", hostname,
1988
0
                    port);
1989
1990
0
        if (settings->AutoDenyCertificate)
1991
0
        {
1992
0
          WLog_INFO(TAG, "No certificate stored, automatically denying.");
1993
0
          accept_certificate = 0;
1994
0
        }
1995
0
        else if (instance->VerifyX509Certificate)
1996
0
        {
1997
0
          const int rc =
1998
0
              instance->VerifyX509Certificate(instance, pemCert, pem_length, hostname,
1999
0
                                              port, flags | VERIFY_CERT_FLAG_CHANGED);
2000
2001
0
          if (rc == 1)
2002
0
            accept_certificate = 1;
2003
0
          else if (rc > 1)
2004
0
            accept_certificate = 2;
2005
0
          else
2006
0
            accept_certificate = 0;
2007
0
        }
2008
0
        else if (instance->VerifyChangedCertificateEx)
2009
0
        {
2010
0
          DWORD cflags = flags | VERIFY_CERT_FLAG_CHANGED;
2011
0
          const char* old_subject = freerdp_certificate_data_get_subject(stored_data);
2012
0
          const char* old_issuer = freerdp_certificate_data_get_issuer(stored_data);
2013
0
          const char* old_fp = freerdp_certificate_data_get_fingerprint(stored_data);
2014
0
          const char* old_pem = freerdp_certificate_data_get_pem(stored_data);
2015
0
          const BOOL fpIsAllocated =
2016
0
              !old_pem ||
2017
0
              !freerdp_settings_get_bool(settings, FreeRDP_CertificateCallbackPreferPEM);
2018
0
          char* fp = nullptr;
2019
0
          if (!fpIsAllocated)
2020
0
          {
2021
0
            cflags |= VERIFY_CERT_FLAG_FP_IS_PEM;
2022
0
            fp = pem;
2023
0
            old_fp = old_pem;
2024
0
          }
2025
0
          else
2026
0
          {
2027
0
            fp = freerdp_certificate_get_fingerprint(cert);
2028
0
          }
2029
0
          accept_certificate = instance->VerifyChangedCertificateEx(
2030
0
              instance, hostname, port, common_name, subject, issuer, fp, old_subject,
2031
0
              old_issuer, old_fp, cflags);
2032
0
          if (fpIsAllocated)
2033
0
            free(fp);
2034
0
        }
2035
0
#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
2036
0
        else if (instance->VerifyChangedCertificate)
2037
0
        {
2038
0
          char* fp = freerdp_certificate_get_fingerprint(cert);
2039
0
          const char* old_subject = freerdp_certificate_data_get_subject(stored_data);
2040
0
          const char* old_issuer = freerdp_certificate_data_get_issuer(stored_data);
2041
0
          const char* old_fingerprint =
2042
0
              freerdp_certificate_data_get_fingerprint(stored_data);
2043
2044
0
          WLog_WARN(TAG, "The VerifyChangedCertificate callback is deprecated, migrate "
2045
0
                         "your application to VerifyChangedCertificateEx");
2046
0
          accept_certificate = instance->VerifyChangedCertificate(
2047
0
              instance, common_name, subject, issuer, fp, old_subject, old_issuer,
2048
0
              old_fingerprint);
2049
0
          free(fp);
2050
0
        }
2051
0
#endif
2052
2053
0
        freerdp_certificate_data_free(stored_data);
2054
0
      }
2055
0
      else if (match == 0)
2056
0
        accept_certificate = 2; /* success! */
2057
2058
0
#if !defined(WITHOUT_FREERDP_3x_DEPRECATED)
2059
0
      WINPR_PRAGMA_DIAG_POP
2060
0
#endif
2061
2062
      /* Save certificate or do a simple accept / reject */
2063
0
      switch (accept_certificate)
2064
0
      {
2065
0
        case 1:
2066
2067
          /* user accepted certificate, add entry in known_hosts file */
2068
0
          verification_status = freerdp_certificate_store_save_data(
2069
0
                                    tls->certificate_store, certificate_data)
2070
0
                                    ? 1
2071
0
                                    : -1;
2072
0
          break;
2073
2074
0
        case 2:
2075
          /* user did accept temporary, do not add to known hosts file */
2076
0
          verification_status = 1;
2077
0
          break;
2078
2079
0
        default:
2080
          /* user did not accept, abort and do not add entry in known_hosts file */
2081
0
          verification_status = -1; /* failure! */
2082
0
          break;
2083
0
      }
2084
2085
0
      free(issuer);
2086
0
      free(subject);
2087
0
      free(pem);
2088
0
    }
2089
2090
0
    if (verification_status > 0)
2091
0
    {
2092
0
      if (!accept_cert(tls, cert))
2093
0
        goto end;
2094
0
    }
2095
0
  }
2096
2097
0
end:
2098
0
  freerdp_certificate_data_free(certificate_data);
2099
0
  free(common_name);
2100
0
  free(pemCert);
2101
0
  return verification_status;
2102
0
}
2103
2104
void tls_print_new_certificate_warn(rdpCertificateStore* store, const char* hostname, UINT16 port,
2105
                                    const char* type, const char* fingerprint)
2106
0
{
2107
0
  char* path = freerdp_certificate_store_get_cert_path(store, hostname, port);
2108
2109
0
  WLog_ERR(TAG, "The host key for %s:%" PRIu16 " has changed", hostname, port);
2110
0
  WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
2111
0
  WLog_ERR(TAG, "@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
2112
0
  WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
2113
0
  WLog_ERR(TAG, "IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
2114
0
  WLog_ERR(TAG, "Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
2115
0
  WLog_ERR(TAG, "It is also possible that a host key has just been changed.");
2116
0
  WLog_ERR(TAG, "The fingerprint for the host key sent by the remote host is %s", fingerprint);
2117
0
  WLog_ERR(TAG, "Please contact your system administrator.");
2118
0
  WLog_ERR(TAG, "Add correct host key in %s to get rid of this message.", path);
2119
0
  WLog_ERR(TAG, "Host key for %s has changed and you have requested %s checking.", hostname,
2120
0
           type);
2121
0
  WLog_ERR(TAG, "Host key verification failed.");
2122
2123
0
  free(path);
2124
0
}
2125
2126
void tls_print_certificate_error(rdpCertificateStore* store,
2127
                                 WINPR_ATTR_UNUSED rdpCertificateData* stored_data,
2128
                                 const char* hostname, UINT16 port, const char* fingerprint)
2129
0
{
2130
0
  char* path = freerdp_certificate_store_get_cert_path(store, hostname, port);
2131
2132
0
  WLog_ERR(TAG, "New host key for %s:%" PRIu16, hostname, port);
2133
0
  WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
2134
0
  WLog_ERR(TAG, "@    WARNING: NEW HOST IDENTIFICATION!     @");
2135
0
  WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
2136
2137
0
  WLog_ERR(TAG, "The fingerprint for the host key sent by the remote host is %s", fingerprint);
2138
0
  WLog_ERR(TAG, "Please contact your system administrator.");
2139
0
  WLog_ERR(TAG, "Add correct host key in %s to get rid of this message.", path);
2140
2141
0
  free(path);
2142
0
}
2143
2144
void tls_print_certificate_name_mismatch_error(const rdpCertificate* cert, const char* hostname,
2145
                                               UINT16 port)
2146
0
{
2147
0
  WINPR_ASSERT(nullptr != hostname);
2148
0
  WINPR_ASSERT(cert);
2149
2150
0
  size_t common_name_length = 0;
2151
0
  char* common_name = freerdp_certificate_get_common_name(cert, &common_name_length);
2152
2153
0
  size_t dnscount = 0;
2154
0
  size_t* dnslengths = nullptr;
2155
0
  char** dnsnames = freerdp_certificate_get_dns_names(cert, &dnscount, &dnslengths);
2156
2157
0
  size_t ipcount = 0;
2158
0
  size_t* iplengths = nullptr;
2159
0
  char** ipnames = freerdp_certificate_get_ip_names(cert, &ipcount, &iplengths);
2160
2161
0
  size_t count = dnscount;
2162
0
  char** names = dnsnames;
2163
0
  const BOOL isIP = utils_is_valid_ip(hostname);
2164
0
  if (isIP)
2165
0
  {
2166
0
    count = ipcount;
2167
0
    names = ipnames;
2168
0
  }
2169
2170
0
  WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
2171
0
  WLog_ERR(TAG, "@           WARNING: CERTIFICATE NAME MISMATCH!           @");
2172
0
  WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
2173
0
  WLog_ERR(TAG, "The hostname used for this connection (%s:%" PRIu16 ") ", hostname, port);
2174
0
  WLog_ERR(TAG, "does not match %s given in the certificate:",
2175
0
           count < 1 ? "the name" : "any of the names");
2176
0
  WLog_ERR(TAG, "Common Name (CN):");
2177
0
  WLog_ERR(TAG, "\t%s", common_name ? common_name : "no CN found in certificate");
2178
2179
0
  if (count > 0)
2180
0
  {
2181
0
    WINPR_ASSERT(nullptr != names);
2182
0
    WLog_ERR(TAG, "Alternative names:");
2183
2184
0
    for (size_t index = 0; index < count; index++)
2185
0
    {
2186
0
      WINPR_ASSERT(names[index]);
2187
0
      WLog_ERR(TAG, "\t %s", names[index]);
2188
0
    }
2189
0
  }
2190
2191
0
  WLog_ERR(TAG, "A valid certificate for the wrong name should NOT be trusted!");
2192
2193
0
  freerdp_certificate_free_dns_names(dnscount, dnslengths, dnsnames);
2194
0
  freerdp_certificate_free_ip_names(ipcount, iplengths, ipnames);
2195
0
  winpr_znfree(common_name, common_name_length);
2196
0
}
2197
2198
rdpTls* freerdp_tls_new(rdpContext* context)
2199
0
{
2200
0
  rdpTls* tls = nullptr;
2201
0
  tls = (rdpTls*)calloc(1, sizeof(rdpTls));
2202
2203
0
  if (!tls)
2204
0
    return nullptr;
2205
2206
0
  tls->context = context;
2207
2208
0
  if (!freerdp_settings_get_bool(tls->context->settings, FreeRDP_ServerMode))
2209
0
  {
2210
0
    tls->certificate_store = freerdp_certificate_store_new(tls->context->settings);
2211
2212
0
    if (!tls->certificate_store)
2213
0
      goto out_free;
2214
0
  }
2215
2216
0
  tls->alertLevel = TLS_ALERT_LEVEL_WARNING;
2217
0
  tls->alertDescription = TLS_ALERT_DESCRIPTION_CLOSE_NOTIFY;
2218
0
  return tls;
2219
0
out_free:
2220
0
  free(tls);
2221
0
  return nullptr;
2222
0
}
2223
2224
void freerdp_tls_free(rdpTls* tls)
2225
0
{
2226
0
  if (!tls)
2227
0
    return;
2228
2229
0
  tls_reset(tls);
2230
2231
0
  if (tls->certificate_store)
2232
0
  {
2233
0
    freerdp_certificate_store_free(tls->certificate_store);
2234
0
    tls->certificate_store = nullptr;
2235
0
  }
2236
2237
0
  free(tls);
2238
0
}