Coverage Report

Created: 2026-03-04 06:13

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