Coverage Report

Created: 2025-08-26 06:31

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