Coverage Report

Created: 2026-01-09 06:43

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