47fda026b593d7ae98927cac9c2e7b1653dbced0
[platform/upstream/freerdp.git] / libfreerdp / crypto / tls.c
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  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *               http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23
24 #include <assert.h>
25 #include <string.h>
26
27 #include <winpr/crt.h>
28 #include <winpr/sspi.h>
29 #include <winpr/ssl.h>
30
31 #include <winpr/stream.h>
32 #include <freerdp/utils/ringbuffer.h>
33
34 #include <freerdp/log.h>
35 #include <freerdp/crypto/tls.h>
36 #include "../core/tcp.h"
37
38 #ifdef HAVE_POLL_H
39 #include <poll.h>
40 #endif
41
42 #ifdef HAVE_VALGRIND_MEMCHECK_H
43 #include <valgrind/memcheck.h>
44 #endif
45
46 #define TAG FREERDP_TAG("crypto")
47
48 struct _BIO_RDP_TLS
49 {
50         SSL* ssl;
51 };
52 typedef struct _BIO_RDP_TLS BIO_RDP_TLS;
53
54 long bio_rdp_tls_callback(BIO* bio, int mode, const char* argp, int argi, long argl, long ret)
55 {
56         return 1;
57 }
58
59 static int bio_rdp_tls_write(BIO* bio, const char* buf, int size)
60 {
61         int status;
62         BIO_RDP_TLS* tls = (BIO_RDP_TLS*) bio->ptr;
63
64         if (!buf || !tls)
65                 return 0;
66
67         BIO_clear_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL);
68
69         status = SSL_write(tls->ssl, buf, size);
70
71         if (status <= 0)
72         {
73                 switch (SSL_get_error(tls->ssl, status))
74                 {
75                         case SSL_ERROR_NONE:
76                                 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
77                                 break;
78
79                         case SSL_ERROR_WANT_WRITE:
80                                 BIO_set_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
81                                 break;
82
83                         case SSL_ERROR_WANT_READ:
84                                 BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
85                                 break;
86
87                         case SSL_ERROR_WANT_X509_LOOKUP:
88                                 BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
89                                 bio->retry_reason = BIO_RR_SSL_X509_LOOKUP;
90                                 break;
91
92                         case SSL_ERROR_WANT_CONNECT:
93                                 BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
94                                 bio->retry_reason = BIO_RR_CONNECT;
95                                 break;
96
97                         case SSL_ERROR_SYSCALL:
98                                 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
99                                 break;
100
101                         case SSL_ERROR_SSL:
102                                 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
103                                 break;
104                 }
105         }
106
107         return status;
108 }
109
110 static int bio_rdp_tls_read(BIO* bio, char* buf, int size)
111 {
112         int status;
113         BIO_RDP_TLS* tls = (BIO_RDP_TLS*) bio->ptr;
114
115         if (!buf || !tls)
116                 return 0;
117
118         BIO_clear_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_READ | BIO_FLAGS_IO_SPECIAL);
119
120         status = SSL_read(tls->ssl, buf, size);
121
122         if (status <= 0)
123         {
124                 switch (SSL_get_error(tls->ssl, status))
125                 {
126                         case SSL_ERROR_NONE:
127                                 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
128                                 break;
129
130                         case SSL_ERROR_WANT_READ:
131                                 BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
132                                 break;
133
134                         case SSL_ERROR_WANT_WRITE:
135                                 BIO_set_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
136                                 break;
137
138                         case SSL_ERROR_WANT_X509_LOOKUP:
139                                 BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
140                                 bio->retry_reason = BIO_RR_SSL_X509_LOOKUP;
141                                 break;
142
143                         case SSL_ERROR_WANT_ACCEPT:
144                                 BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
145                                 bio->retry_reason = BIO_RR_ACCEPT;
146                                 break;
147
148                         case SSL_ERROR_WANT_CONNECT:
149                                 BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL);
150                                 bio->retry_reason = BIO_RR_CONNECT;
151                                 break;
152
153                         case SSL_ERROR_SSL:
154                                 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
155                                 break;
156
157                         case SSL_ERROR_ZERO_RETURN:
158                                 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
159                                 break;
160
161                         case SSL_ERROR_SYSCALL:
162                 if (WSAGetLastError() == WSAEWOULDBLOCK)
163                 {
164                     BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
165                     break;
166                 }
167                                 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
168                                 break;
169                 }
170         }
171
172 #ifdef HAVE_VALGRIND_MEMCHECK_H
173         if (status > 0)
174         {
175                 VALGRIND_MAKE_MEM_DEFINED(buf, status);
176         }
177 #endif
178
179         return status;
180 }
181
182 static int bio_rdp_tls_puts(BIO* bio, const char* str)
183 {
184         int size;
185         int status;
186
187         if (!str)
188                 return 0;
189
190         size = strlen(str);
191         status = BIO_write(bio, str, size);
192
193         return status;
194 }
195
196 static int bio_rdp_tls_gets(BIO* bio, char* str, int size)
197 {
198         return 1;
199 }
200
201 static long bio_rdp_tls_ctrl(BIO* bio, int cmd, long num, void* ptr)
202 {
203         BIO* rbio;
204         int status = -1;
205         BIO_RDP_TLS* tls = (BIO_RDP_TLS*) bio->ptr;
206
207         if (!tls)
208                 return 0;
209
210         if (!tls->ssl && (cmd != BIO_C_SET_SSL))
211                 return 0;
212
213         switch (cmd)
214         {
215                 case BIO_CTRL_RESET:
216                         SSL_shutdown(tls->ssl);
217
218                         if (tls->ssl->handshake_func == tls->ssl->method->ssl_connect)
219                                 SSL_set_connect_state(tls->ssl);
220                         else if (tls->ssl->handshake_func == tls->ssl->method->ssl_accept)
221                                 SSL_set_accept_state(tls->ssl);
222
223                         SSL_clear(tls->ssl);
224
225                         if (bio->next_bio)
226                                 status = BIO_ctrl(bio->next_bio, cmd, num, ptr);
227                         else if (tls->ssl->rbio)
228                                 status = BIO_ctrl(tls->ssl->rbio, cmd, num, ptr);
229                         else
230                                 status = 1;
231                         break;
232
233                 case BIO_C_GET_FD:
234                         status = BIO_ctrl(tls->ssl->rbio, cmd, num, ptr);
235                         break;
236
237                 case BIO_CTRL_INFO:
238                         status = 0;
239                         break;
240
241                 case BIO_CTRL_SET_CALLBACK:
242                         status = 0;
243                         break;
244
245                 case BIO_CTRL_GET_CALLBACK:
246                         *((ULONG_PTR*) ptr) = (ULONG_PTR) SSL_get_info_callback(tls->ssl);
247                         status = 1;
248                         break;
249
250                 case BIO_C_SSL_MODE:
251                         if (num)
252                                 SSL_set_connect_state(tls->ssl);
253                         else
254                                 SSL_set_accept_state(tls->ssl);
255                         status = 1;
256                         break;
257
258                 case BIO_CTRL_GET_CLOSE:
259                         status = bio->shutdown;
260                         break;
261
262                 case BIO_CTRL_SET_CLOSE:
263                         bio->shutdown = (int) num;
264                         status = 1;
265                         break;
266
267                 case BIO_CTRL_WPENDING:
268                         status = BIO_ctrl(tls->ssl->wbio, cmd, num, ptr);
269                         break;
270
271                 case BIO_CTRL_PENDING:
272                         status = SSL_pending(tls->ssl);
273                         if (status == 0)
274                                 status = BIO_pending(tls->ssl->rbio);
275                         break;
276
277                 case BIO_CTRL_FLUSH:
278                         BIO_clear_retry_flags(bio);
279                         status = BIO_ctrl(tls->ssl->wbio, cmd, num, ptr);
280                         BIO_copy_next_retry(bio);
281                         status = 1;
282                         break;
283
284                 case BIO_CTRL_PUSH:
285                         if (bio->next_bio && (bio->next_bio != tls->ssl->rbio))
286                         {
287                                 SSL_set_bio(tls->ssl, bio->next_bio, bio->next_bio);
288                                 CRYPTO_add(&(bio->next_bio->references), 1, CRYPTO_LOCK_BIO);
289                         }
290                         status = 1;
291                         break;
292
293                 case BIO_CTRL_POP:
294                         if (bio == ptr)
295                         {
296                                 if (tls->ssl->rbio != tls->ssl->wbio)
297                                         BIO_free_all(tls->ssl->wbio);
298
299                                 if (bio->next_bio)
300                                         CRYPTO_add(&(bio->next_bio->references), -1, CRYPTO_LOCK_BIO);
301
302                                 tls->ssl->wbio = tls->ssl->rbio = NULL;
303                         }
304                         status = 1;
305                         break;
306
307                 case BIO_C_GET_SSL:
308                         if (ptr)
309                         {
310                                 *((SSL**) ptr) = tls->ssl;
311                                 status = 1;
312                         }
313                         break;
314
315                 case BIO_C_SET_SSL:
316                         bio->shutdown = (int) num;
317
318                         if (ptr)
319                                 tls->ssl = (SSL*) ptr;
320
321                         rbio = SSL_get_rbio(tls->ssl);
322
323                         if (rbio)
324                         {
325                                 if (bio->next_bio)
326                                         BIO_push(rbio, bio->next_bio);
327
328                                 bio->next_bio = rbio;
329                                 CRYPTO_add(&(rbio->references), 1, CRYPTO_LOCK_BIO);
330                         }
331
332                         bio->init = 1;
333                         status = 1;
334                         break;
335
336                 case BIO_C_DO_STATE_MACHINE:
337                         BIO_clear_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_WRITE | BIO_FLAGS_IO_SPECIAL);
338                         bio->retry_reason = 0;
339
340                         status = SSL_do_handshake(tls->ssl);
341
342                         if (status <= 0)
343                         {
344                                 switch (SSL_get_error(tls->ssl, status))
345                                 {
346                                         case SSL_ERROR_WANT_READ:
347                                                 BIO_set_flags(bio, BIO_FLAGS_READ | BIO_FLAGS_SHOULD_RETRY);
348                                                 break;
349
350                                         case SSL_ERROR_WANT_WRITE:
351                                                 BIO_set_flags(bio, BIO_FLAGS_WRITE | BIO_FLAGS_SHOULD_RETRY);
352                                                 break;
353
354                                         case SSL_ERROR_WANT_CONNECT:
355                                                 BIO_set_flags(bio, BIO_FLAGS_IO_SPECIAL | BIO_FLAGS_SHOULD_RETRY);
356                                                 bio->retry_reason = bio->next_bio->retry_reason;
357                                                 break;
358
359                                         default:
360                                                 BIO_clear_flags(bio, BIO_FLAGS_SHOULD_RETRY);
361                                                 break;
362                                 }
363                         }
364                         break;
365
366                 default:
367                         status = BIO_ctrl(tls->ssl->rbio, cmd, num, ptr);
368                         break;
369         }
370
371         return status;
372 }
373
374 static int bio_rdp_tls_new(BIO* bio)
375 {
376         BIO_RDP_TLS* tls;
377
378         bio->init = 0;
379         bio->num = 0;
380         bio->flags = BIO_FLAGS_SHOULD_RETRY;
381         bio->next_bio = NULL;
382
383         tls = calloc(1, sizeof(BIO_RDP_TLS));
384
385         if (!tls)
386                 return 0;
387
388         bio->ptr = (void*) tls;
389
390         return 1;
391 }
392
393 static int bio_rdp_tls_free(BIO* bio)
394 {
395         BIO_RDP_TLS* tls;
396
397         if (!bio)
398                 return 0;
399
400         tls = (BIO_RDP_TLS*) bio->ptr;
401
402         if (!tls)
403                 return 0;
404
405         if (bio->shutdown)
406         {
407                 if (bio->init && tls->ssl)
408                 {
409                         SSL_shutdown(tls->ssl);
410                         SSL_free(tls->ssl);
411                 }
412
413                 bio->init = 0;
414                 bio->flags = 0;
415         }
416
417         free(tls);
418
419         return 1;
420 }
421
422 static long bio_rdp_tls_callback_ctrl(BIO* bio, int cmd, bio_info_cb* fp)
423 {
424         int status = 0;
425         BIO_RDP_TLS* tls;
426
427         if (!bio)
428                 return 0;
429
430         tls = (BIO_RDP_TLS*) bio->ptr;
431
432         if (!tls)
433                 return 0;
434
435         switch (cmd)
436         {
437                 case BIO_CTRL_SET_CALLBACK:
438                         SSL_set_info_callback(tls->ssl, (void (*)(const SSL *, int, int)) fp);
439                         status = 1;
440                         break;
441
442                 default:
443                         status = BIO_callback_ctrl(tls->ssl->rbio, cmd, fp);
444                         break;
445         }
446
447         return status;
448 }
449
450 #define BIO_TYPE_RDP_TLS        68
451
452 static BIO_METHOD bio_rdp_tls_methods =
453 {
454         BIO_TYPE_RDP_TLS,
455         "RdpTls",
456         bio_rdp_tls_write,
457         bio_rdp_tls_read,
458         bio_rdp_tls_puts,
459         bio_rdp_tls_gets,
460         bio_rdp_tls_ctrl,
461         bio_rdp_tls_new,
462         bio_rdp_tls_free,
463         bio_rdp_tls_callback_ctrl,
464 };
465
466 BIO_METHOD* BIO_s_rdp_tls(void)
467 {
468         return &bio_rdp_tls_methods;
469 }
470
471 BIO* BIO_new_rdp_tls(SSL_CTX* ctx, int client)
472 {
473         BIO* bio;
474         SSL* ssl;
475
476         bio = BIO_new(BIO_s_rdp_tls());
477
478         if (!bio)
479                 return NULL;
480
481         ssl = SSL_new(ctx);
482
483         if (!ssl)
484         {
485                 BIO_free(bio);
486                 return NULL;
487         }
488
489         if (client)
490                 SSL_set_connect_state(ssl);
491         else
492                 SSL_set_accept_state(ssl);
493
494         BIO_set_ssl(bio, ssl, BIO_CLOSE);
495
496         return bio;
497 }
498
499 static CryptoCert tls_get_certificate(rdpTls* tls, BOOL peer)
500 {
501         CryptoCert cert;
502         X509* remote_cert;
503         STACK_OF(X509) *chain;
504
505         if (peer)
506                 remote_cert = SSL_get_peer_certificate(tls->ssl);
507         else
508                 remote_cert = X509_dup( SSL_get_certificate(tls->ssl) );
509
510         if (!remote_cert)
511         {
512                 WLog_ERR(TAG, "failed to get the server TLS certificate");
513                 return NULL;
514         }
515
516         cert = malloc(sizeof(*cert));
517         if (!cert)
518         {
519                 X509_free(remote_cert);
520                 return NULL;
521         }
522
523         cert->px509 = remote_cert;
524
525         /* Get the peer's chain. If it does not exist, we're setting NULL (clean data either way) */
526         chain = SSL_get_peer_cert_chain(tls->ssl);
527         cert->px509chain = chain;
528
529         return cert;
530 }
531
532 static void tls_free_certificate(CryptoCert cert)
533 {
534         X509_free(cert->px509);
535         free(cert);
536 }
537
538 #define TLS_SERVER_END_POINT    "tls-server-end-point:"
539
540 SecPkgContext_Bindings* tls_get_channel_bindings(X509* cert)
541 {
542         int PrefixLength;
543         BYTE CertificateHash[32];
544         UINT32 CertificateHashLength;
545         BYTE* ChannelBindingToken;
546         UINT32 ChannelBindingTokenLength;
547         SEC_CHANNEL_BINDINGS* ChannelBindings;
548         SecPkgContext_Bindings* ContextBindings;
549
550         ZeroMemory(CertificateHash, sizeof(CertificateHash));
551         X509_digest(cert, EVP_sha256(), CertificateHash, &CertificateHashLength);
552
553         PrefixLength = strlen(TLS_SERVER_END_POINT);
554         ChannelBindingTokenLength = PrefixLength + CertificateHashLength;
555
556         ContextBindings = (SecPkgContext_Bindings*) calloc(1, sizeof(SecPkgContext_Bindings));
557         if (!ContextBindings)
558                 return NULL;
559
560         ContextBindings->BindingsLength = sizeof(SEC_CHANNEL_BINDINGS) + ChannelBindingTokenLength;
561         ChannelBindings = (SEC_CHANNEL_BINDINGS*) calloc(1, ContextBindings->BindingsLength);
562         if (!ChannelBindings)
563                 goto out_free;
564         ContextBindings->Bindings = ChannelBindings;
565
566         ChannelBindings->cbApplicationDataLength = ChannelBindingTokenLength;
567         ChannelBindings->dwApplicationDataOffset = sizeof(SEC_CHANNEL_BINDINGS);
568         ChannelBindingToken = &((BYTE*) ChannelBindings)[ChannelBindings->dwApplicationDataOffset];
569
570         strcpy((char*) ChannelBindingToken, TLS_SERVER_END_POINT);
571         CopyMemory(&ChannelBindingToken[PrefixLength], CertificateHash, CertificateHashLength);
572
573         return ContextBindings;
574
575 out_free:
576         free(ContextBindings);
577         return NULL;
578 }
579
580
581 #if defined(__APPLE__)
582 BOOL tls_prepare(rdpTls* tls, BIO* underlying, SSL_METHOD* method, int options, BOOL clientMode)
583 #else
584 BOOL tls_prepare(rdpTls* tls, BIO* underlying, const SSL_METHOD* method, int options, BOOL clientMode)
585 #endif
586 {
587         rdpSettings* settings = tls->settings;
588
589         tls->ctx = SSL_CTX_new(method);
590
591         if (!tls->ctx)
592         {
593                 WLog_ERR(TAG, "SSL_CTX_new failed");
594                 return FALSE;
595         }
596
597         SSL_CTX_set_mode(tls->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
598
599         SSL_CTX_set_options(tls->ctx, options);
600         SSL_CTX_set_read_ahead(tls->ctx, 1);
601
602         if (settings->AllowedTlsCiphers)
603         {
604                 if (!SSL_CTX_set_cipher_list(tls->ctx, settings->AllowedTlsCiphers))
605                 {
606                         WLog_ERR(TAG, "SSL_CTX_set_cipher_list %s failed", settings->AllowedTlsCiphers);
607                         return FALSE;
608                 }
609         }
610
611         tls->bio = BIO_new_rdp_tls(tls->ctx, clientMode);
612
613         if (BIO_get_ssl(tls->bio, &tls->ssl) < 0)
614         {
615                 WLog_ERR(TAG, "unable to retrieve the SSL of the connection");
616                 return FALSE;
617         }
618
619         BIO_push(tls->bio, underlying);
620         tls->underlying = underlying;
621
622         return TRUE;
623 }
624
625 int tls_do_handshake(rdpTls* tls, BOOL clientMode)
626 {
627         CryptoCert cert;
628         int verify_status, status;
629
630         do
631         {
632 #ifdef HAVE_POLL_H
633                 struct pollfd pollfds;
634 #else
635                 struct timeval tv;
636                 fd_set rset;
637 #endif
638                 int fd;
639
640                 status = BIO_do_handshake(tls->bio);
641
642                 if (status == 1)
643                         break;
644
645                 if (!BIO_should_retry(tls->bio))
646                         return -1;
647
648                 /* we select() only for read even if we should test both read and write
649                  * depending of what have blocked */
650                 fd = BIO_get_fd(tls->bio, NULL);
651
652                 if (fd < 0)
653                 {
654                         WLog_ERR(TAG, "unable to retrieve BIO fd");
655                         return -1;
656                 }
657
658 #ifdef HAVE_POLL_H
659                 pollfds.fd = fd;
660                 pollfds.events = POLLIN;
661                 pollfds.revents = 0;
662
663                 do
664                 {
665                         status = poll(&pollfds, 1, 10 * 1000);
666                 }
667                 while ((status < 0) && (errno == EINTR));
668 #else
669                 FD_ZERO(&rset);
670                 FD_SET(fd, &rset);
671                 tv.tv_sec = 0;
672                 tv.tv_usec = 10 * 1000; /* 10ms */
673
674                 status = _select(fd + 1, &rset, NULL, NULL, &tv);
675 #endif
676                 if (status < 0)
677                 {
678                         WLog_ERR(TAG, "error during select()");
679                         return -1;
680                 }
681         }
682         while (TRUE);
683
684         cert = tls_get_certificate(tls, clientMode);
685         if (!cert)
686         {
687                 WLog_ERR(TAG, "tls_get_certificate failed to return the server certificate.");
688                 return -1;
689         }
690
691         tls->Bindings = tls_get_channel_bindings(cert->px509);
692         if (!tls->Bindings)
693         {
694                 WLog_ERR(TAG, "unable to retrieve bindings");
695                 verify_status = -1;
696                 goto out;
697         }
698
699         if (!crypto_cert_get_public_key(cert, &tls->PublicKey, &tls->PublicKeyLength))
700         {
701                 WLog_ERR(TAG, "crypto_cert_get_public_key failed to return the server public key.");
702                 verify_status = -1;
703                 goto out;
704         }
705
706         /* Note: server-side NLA needs public keys (keys from us, the server) but no
707          *              certificate verify
708          */
709         verify_status = 1;
710         if (clientMode)
711         {
712                 verify_status = tls_verify_certificate(tls, cert, tls->hostname, tls->port);
713
714                 if (verify_status < 1)
715                 {
716                         WLog_ERR(TAG, "certificate not trusted, aborting.");
717                         tls_send_alert(tls);
718                         verify_status = 0;
719                 }
720         }
721
722 out:
723         tls_free_certificate(cert);
724
725         return verify_status;
726 }
727
728 int tls_connect(rdpTls* tls, BIO* underlying)
729 {
730         int options = 0;
731
732         /**
733          * SSL_OP_NO_COMPRESSION:
734          *
735          * The Microsoft RDP server does not advertise support
736          * for TLS compression, but alternative servers may support it.
737          * This was observed between early versions of the FreeRDP server
738          * and the FreeRDP client, and caused major performance issues,
739          * which is why we're disabling it.
740          */
741 #ifdef SSL_OP_NO_COMPRESSION
742         options |= SSL_OP_NO_COMPRESSION;
743 #endif
744
745         /**
746          * SSL_OP_TLS_BLOCK_PADDING_BUG:
747          *
748          * The Microsoft RDP server does *not* support TLS padding.
749          * It absolutely needs to be disabled otherwise it won't work.
750          */
751         options |= SSL_OP_TLS_BLOCK_PADDING_BUG;
752
753         /**
754          * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:
755          *
756          * Just like TLS padding, the Microsoft RDP server does not
757          * support empty fragments. This needs to be disabled.
758          */
759         options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
760
761         if (!tls_prepare(tls, underlying, TLSv1_client_method(), options, TRUE))
762                 return FALSE;
763
764         return tls_do_handshake(tls, TRUE);
765 }
766
767 #ifndef OPENSSL_NO_TLSEXT
768 static void tls_openssl_tlsext_debug_callback(SSL *s, int client_server,
769                                               int type, unsigned char *data, int len, void *arg)
770 {
771         /* see code comment in tls_accept() below */
772
773         if (type == TLSEXT_TYPE_server_name) {
774                 WLog_DBG(TAG, "Client uses SNI (extension disabled)");
775                 s->servername_done = 2;
776         }
777 }
778 #endif
779
780 BOOL tls_accept(rdpTls* tls, BIO* underlying, const char* cert_file, const char* privatekey_file)
781 {
782         long options = 0;
783
784         /**
785          * SSL_OP_NO_SSLv2:
786          *
787          * We only want SSLv3 and TLSv1, so disable SSLv2.
788          * SSLv3 is used by, eg. Microsoft RDC for Mac OS X.
789          */
790         options |= SSL_OP_NO_SSLv2;
791
792         /**
793          * SSL_OP_NO_COMPRESSION:
794          *
795          * The Microsoft RDP server does not advertise support
796          * for TLS compression, but alternative servers may support it.
797          * This was observed between early versions of the FreeRDP server
798          * and the FreeRDP client, and caused major performance issues,
799          * which is why we're disabling it.
800          */
801 #ifdef SSL_OP_NO_COMPRESSION
802         options |= SSL_OP_NO_COMPRESSION;
803 #endif
804
805         /**
806          * SSL_OP_TLS_BLOCK_PADDING_BUG:
807          *
808          * The Microsoft RDP server does *not* support TLS padding.
809          * It absolutely needs to be disabled otherwise it won't work.
810          */
811         options |= SSL_OP_TLS_BLOCK_PADDING_BUG;
812
813         /**
814          * SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS:
815          *
816          * Just like TLS padding, the Microsoft RDP server does not
817          * support empty fragments. This needs to be disabled.
818          */
819         options |= SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
820
821         if (!tls_prepare(tls, underlying, SSLv23_server_method(), options, FALSE))
822                 return FALSE;
823
824         if (SSL_use_RSAPrivateKey_file(tls->ssl, privatekey_file, SSL_FILETYPE_PEM) <= 0)
825         {
826                 WLog_ERR(TAG, "SSL_CTX_use_RSAPrivateKey_file failed");
827                 WLog_ERR(TAG, "PrivateKeyFile: %s", privatekey_file);
828                 return FALSE;
829         }
830
831         if (SSL_use_certificate_file(tls->ssl, cert_file, SSL_FILETYPE_PEM) <= 0)
832         {
833                 WLog_ERR(TAG, "SSL_use_certificate_file failed");
834                 return FALSE;
835         }
836
837 #ifndef OPENSSL_NO_TLSEXT
838         /**
839          * The Microsoft iOS clients eventually send a null or even double null
840          * terminated hostname in the SNI TLS extension!
841          * If the length indicator does not equal the hostname strlen OpenSSL
842          * will abort (see openssl:ssl/t1_lib.c).
843          * Here is a tcpdump segment of Microsoft Remote Desktop Client Version
844          * 8.1.7 running on an iPhone 4 with iOS 7.1.2 showing the transmitted
845          * SNI hostname TLV blob when connection to server "abcd":
846          * 00                  name_type 0x00 (host_name)
847          * 00 06               length_in_bytes 0x0006
848          * 61 62 63 64 00 00   host_name "abcd\0\0"
849          *
850          * Currently the only (runtime) workaround is setting an openssl tls
851          * extension debug callback that sets the SSL context's servername_done
852          * to 1 which effectively disables the parsing of that extension type.
853          */
854
855         SSL_set_tlsext_debug_callback(tls->ssl, tls_openssl_tlsext_debug_callback);
856 #endif
857
858         return tls_do_handshake(tls, FALSE) > 0;
859 }
860
861 BOOL tls_send_alert(rdpTls* tls)
862 {
863         if (!tls)
864                 return FALSE;
865
866         if (!tls->ssl)
867                 return TRUE;
868
869         if (tls->alertDescription != TLS_ALERT_DESCRIPTION_CLOSE_NOTIFY)
870         {
871                 /**
872                  * OpenSSL doesn't really expose an API for sending a TLS alert manually.
873                  *
874                  * The following code disables the sending of the default "close notify"
875                  * and then proceeds to force sending a custom TLS alert before shutting down.
876                  *
877                  * Manually sending a TLS alert is necessary in certain cases,
878                  * like when server-side NLA results in an authentication failure.
879                  */
880
881                 SSL_set_quiet_shutdown(tls->ssl, 1);
882
883                 if ((tls->alertLevel == TLS_ALERT_LEVEL_FATAL) && (tls->ssl->session))
884                         SSL_CTX_remove_session(tls->ssl->ctx, tls->ssl->session);
885
886                 tls->ssl->s3->alert_dispatch = 1;
887                 tls->ssl->s3->send_alert[0] = tls->alertLevel;
888                 tls->ssl->s3->send_alert[1] = tls->alertDescription;
889
890                 if (tls->ssl->s3->wbuf.left == 0)
891                         tls->ssl->method->ssl_dispatch_alert(tls->ssl);
892         }
893         return TRUE;
894 }
895
896
897 BIO *findBufferedBio(BIO *front)
898 {
899         BIO *ret = front;
900
901         while (ret)
902         {
903                 if (BIO_method_type(ret) == BIO_TYPE_BUFFERED)
904                         return ret;
905                 ret = ret->next_bio;
906         }
907
908         return ret;
909 }
910
911 int tls_write_all(rdpTls* tls, const BYTE* data, int length)
912 {
913         int status;
914         int offset = 0;
915         BIO* bio = tls->bio;
916
917         while (offset < length)
918         {
919                 status = BIO_write(bio, &data[offset], length - offset);
920
921                 if (status > 0)
922                 {
923                         offset += status;
924                 }
925                 else
926                 {
927                         if (!BIO_should_retry(bio))
928                                 return -1;
929
930                         if (BIO_write_blocked(bio))
931                                 status = BIO_wait_write(bio, 100);
932                         else if (BIO_read_blocked(bio))
933                                 status = BIO_wait_read(bio, 100);
934                         else
935                                 USleep(100);
936
937                         if (status < 0)
938                                 return -1;
939                 }
940         }
941
942         return length;
943 }
944
945 int tls_set_alert_code(rdpTls* tls, int level, int description)
946 {
947         tls->alertLevel = level;
948         tls->alertDescription = description;
949
950         return 0;
951 }
952
953 BOOL tls_match_hostname(char *pattern, int pattern_length, char *hostname)
954 {
955         if (strlen(hostname) == pattern_length)
956         {
957                 if (_strnicmp( hostname, pattern, pattern_length) == 0)
958                         return TRUE;
959         }
960
961         if ((pattern_length > 2) && (pattern[0] == '*') && (pattern[1] == '.') && (((int) strlen(hostname)) >= pattern_length))
962         {
963                 char* check_hostname = &hostname[strlen(hostname) - pattern_length + 1];
964
965                 if (_strnicmp( check_hostname, &pattern[1], pattern_length - 1) == 0)
966                 {
967                         return TRUE;
968                 }
969         }
970
971         return FALSE;
972 }
973
974 int tls_verify_certificate(rdpTls* tls, CryptoCert cert, char* hostname, int port)
975 {
976         int match;
977         int index;
978         char* common_name = NULL;
979         int common_name_length = 0;
980         char** alt_names = NULL;
981         int alt_names_count = 0;
982         int* alt_names_lengths = NULL;
983         BOOL certificate_status;
984         BOOL hostname_match = FALSE;
985         BOOL verification_status = FALSE;
986         rdpCertificateData* certificate_data;
987
988         if (tls->settings->ExternalCertificateManagement)
989         {
990                 BIO* bio;
991                 int status;
992                 int length;
993                 int offset;
994                 BYTE* pemCert;
995                 freerdp* instance = (freerdp*) tls->settings->instance;
996
997                 /**
998                  * Don't manage certificates internally, leave it up entirely to the external client implementation
999                  */
1000
1001                 bio = BIO_new(BIO_s_mem());
1002
1003                 if (!bio)
1004                 {
1005                         WLog_ERR(TAG, "BIO_new() failure");
1006                         return -1;
1007                 }
1008
1009                 status = PEM_write_bio_X509(bio, cert->px509);
1010
1011                 if (status < 0)
1012                 {
1013                         WLog_ERR(TAG, "PEM_write_bio_X509 failure: %d", status);
1014                         return -1;
1015                 }
1016
1017                 offset = 0;
1018                 length = 2048;
1019                 pemCert = (BYTE*) malloc(length + 1);
1020                 if (!pemCert)
1021                 {
1022                         WLog_ERR(TAG, "error allocating pemCert");
1023                         return -1;
1024                 }
1025
1026                 status = BIO_read(bio, pemCert, length);
1027
1028                 if (status < 0)
1029                 {
1030                         WLog_ERR(TAG, "failed to read certificate");
1031                         return -1;
1032                 }
1033
1034                 offset += status;
1035
1036                 while (offset >= length)
1037                 {
1038                         int new_len;
1039                         BYTE *new_cert;
1040
1041                         new_len = length * 2;
1042                         new_cert = (BYTE*) realloc(pemCert, new_len + 1);
1043                         if (!new_cert)
1044                                 return -1;
1045                         length = new_len;
1046                         pemCert = new_cert;
1047
1048                         status = BIO_read(bio, &pemCert[offset], length);
1049
1050                         if (status < 0)
1051                                 break;
1052
1053                         offset += status;
1054                 }
1055
1056                 if (status < 0)
1057                 {
1058                         WLog_ERR(TAG, "failed to read certificate");
1059                         return -1;
1060                 }
1061
1062                 length = offset;
1063                 pemCert[length] = '\0';
1064
1065                 status = -1;
1066
1067                 if (instance->VerifyX509Certificate)
1068                 {
1069                         status = instance->VerifyX509Certificate(instance, pemCert, length, hostname, port, tls->isGatewayTransport);
1070                 }
1071
1072                 WLog_ERR(TAG, "(length = %d) status: %d%s",     length, status, pemCert);
1073
1074                 free(pemCert);
1075                 BIO_free(bio);
1076
1077                 if (status < 0)
1078                         return -1;
1079
1080                 return (status == 0) ? 0 : 1;
1081         }
1082
1083         /* ignore certificate verification if user explicitly required it (discouraged) */
1084         if (tls->settings->IgnoreCertificate)
1085                 return 1;  /* success! */
1086
1087         /* if user explicitly specified a certificate name, use it instead of the hostname */
1088         if (tls->settings->CertificateName)
1089                 hostname = tls->settings->CertificateName;
1090
1091         /* attempt verification using OpenSSL and the ~/.freerdp/certs certificate store */
1092         certificate_status = x509_verify_certificate(cert, tls->certificate_store->path);
1093
1094         /* verify certificate name match */
1095         certificate_data = crypto_get_certificate_data(cert->px509, hostname, port);
1096
1097
1098         /* extra common name and alternative names */
1099         common_name = crypto_cert_subject_common_name(cert->px509, &common_name_length);
1100         alt_names = crypto_cert_subject_alt_name(cert->px509, &alt_names_count, &alt_names_lengths);
1101
1102         /* compare against common name */
1103
1104         if (common_name)
1105         {
1106                 if (tls_match_hostname(common_name, common_name_length, hostname))
1107                         hostname_match = TRUE;
1108         }
1109
1110         /* compare against alternative names */
1111
1112         if (alt_names)
1113         {
1114                 for (index = 0; index < alt_names_count; index++)
1115                 {
1116                         if (tls_match_hostname(alt_names[index], alt_names_lengths[index], hostname))
1117                         {
1118                                 hostname_match = TRUE;
1119                                 break;
1120                         }
1121                 }
1122         }
1123
1124         /* if the certificate is valid and the certificate name matches, verification succeeds */
1125         if (certificate_status && hostname_match)
1126         {
1127                 if (common_name)
1128                 {
1129                         free(common_name);
1130                         common_name = NULL;
1131                 }
1132
1133                 verification_status = TRUE; /* success! */
1134         }
1135
1136         /* if the certificate is valid but the certificate name does not match, warn user, do not accept */
1137         if (certificate_status && !hostname_match)
1138                 tls_print_certificate_name_mismatch_error(hostname, port,
1139                                                           common_name, alt_names,
1140                                                           alt_names_count);
1141
1142         /* verification could not succeed with OpenSSL, use known_hosts file and prompt user for manual verification */
1143
1144         if (!certificate_status)
1145         {
1146                 char* issuer;
1147                 char* subject;
1148                 char* fingerprint;
1149                 freerdp* instance = (freerdp*) tls->settings->instance;
1150                 BOOL accept_certificate = FALSE;
1151
1152                 issuer = crypto_cert_issuer(cert->px509);
1153                 subject = crypto_cert_subject(cert->px509);
1154                 fingerprint = crypto_cert_fingerprint(cert->px509);
1155
1156                 /* search for matching entry in known_hosts file */
1157                 match = certificate_data_match(tls->certificate_store, certificate_data);
1158
1159                 if (match == 1)
1160                 {
1161                         /* no entry was found in known_hosts file, prompt user for manual verification */
1162                         if (!hostname_match)
1163                                 tls_print_certificate_name_mismatch_error(
1164                                                         hostname, port,
1165                                                         common_name, alt_names,
1166                                                         alt_names_count);
1167
1168                         if (instance->VerifyCertificate)
1169                         {
1170                                 accept_certificate = instance->VerifyCertificate(instance, subject, issuer, fingerprint);
1171                         }
1172
1173                         if (!accept_certificate)
1174                         {
1175                                 /* user did not accept, abort and do not add entry in known_hosts file */
1176                                 verification_status = FALSE; /* failure! */
1177                         }
1178                         else
1179                         {
1180                                 /* user accepted certificate, add entry in known_hosts file */
1181                                 verification_status = certificate_data_print(tls->certificate_store, certificate_data);
1182                         }
1183                 }
1184                 else if (match == -1)
1185                 {
1186                         char* old_subject = NULL;
1187                         char* old_issuer = NULL;
1188                         char* old_fingerprint = NULL;
1189
1190                         /* entry was found in known_hosts file, but fingerprint does not match. ask user to use it */
1191                         tls_print_certificate_error(hostname, port, fingerprint,
1192                                                     tls->certificate_store->file);
1193
1194                         if (!certificate_get_stored_data(tls->certificate_store,
1195                                                          certificate_data, &old_subject,
1196                                                          &old_issuer, &old_fingerprint))
1197                                 WLog_WARN(TAG, "Failed to get certificate entry for %s:hu",
1198                                           hostname, port);
1199
1200                         if (instance->VerifyChangedCertificate)
1201                         {
1202                                 accept_certificate = instance->VerifyChangedCertificate(
1203                                                              instance, subject, issuer,
1204                                                              fingerprint, old_subject, old_issuer,
1205                                                              old_fingerprint);
1206                         }
1207
1208                         free(old_fingerprint);
1209
1210                         if (!accept_certificate)
1211                         {
1212                                 /* user did not accept, abort and do not change known_hosts file */
1213                                 verification_status = FALSE;  /* failure! */
1214                         }
1215                         else
1216                         {
1217                                 /* user accepted new certificate, add replace fingerprint for this host in known_hosts file */
1218                                 verification_status = certificate_data_replace(tls->certificate_store, certificate_data);
1219                         }
1220                 }
1221                 else if (match == 0)
1222                 {
1223                         verification_status = TRUE; /* success! */
1224                 }
1225
1226                 free(issuer);
1227                 free(subject);
1228                 free(fingerprint);
1229         }
1230
1231         certificate_data_free(certificate_data);
1232
1233 #ifndef _WIN32
1234         free(common_name);
1235 #endif
1236
1237         if (alt_names)
1238                 crypto_cert_subject_alt_name_free(alt_names_count, alt_names_lengths,
1239                                                   alt_names);
1240
1241         return (verification_status == 0) ? 0 : 1;
1242 }
1243
1244 void tls_print_certificate_error(char* hostname, UINT16 port, char* fingerprint,
1245                                  char *hosts_file)
1246 {
1247         WLog_ERR(TAG, "The host key for %s:%hu has changed", hostname, port);
1248         WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1249         WLog_ERR(TAG, "@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @");
1250         WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1251         WLog_ERR(TAG, "IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!");
1252         WLog_ERR(TAG, "Someone could be eavesdropping on you right now (man-in-the-middle attack)!");
1253         WLog_ERR(TAG, "It is also possible that a host key has just been changed.");
1254         WLog_ERR(TAG, "The fingerprint for the host key sent by the remote host is%s", fingerprint);
1255         WLog_ERR(TAG, "Please contact your system administrator.");
1256         WLog_ERR(TAG, "Add correct host key in %s to get rid of this message.", hosts_file);
1257         WLog_ERR(TAG, "Host key for %s has changed and you have requested strict checking.", hostname);
1258         WLog_ERR(TAG, "Host key verification failed.");
1259 }
1260
1261 void tls_print_certificate_name_mismatch_error(char* hostname, UINT16 port,
1262                                                char* common_name, char** alt_names,
1263                                                int alt_names_count)
1264 {
1265         int index;
1266
1267         assert(NULL != hostname);
1268         WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1269         WLog_ERR(TAG, "@           WARNING: CERTIFICATE NAME MISMATCH!           @");
1270         WLog_ERR(TAG, "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
1271         WLog_ERR(TAG, "The hostname used for this connection (%s:%hu) ",
1272                  hostname, port);
1273         WLog_ERR(TAG, "does not match %s given in the certificate:",
1274                  alt_names_count < 1 ? "the name" : "any of the names");
1275         WLog_ERR(TAG, "Common Name (CN):");
1276         WLog_ERR(TAG, "\t%s", common_name ? common_name : "no CN found in certificate");
1277         if (alt_names_count > 0)
1278         {
1279                 assert(NULL != alt_names);
1280                 WLog_ERR(TAG, "Alternative names:");
1281                 for (index = 0; index < alt_names_count; index++)
1282                 {
1283                         assert(alt_names[index]);
1284                         WLog_ERR(TAG, "\t %s", alt_names[index]);
1285                 }
1286         }
1287         WLog_ERR(TAG, "A valid certificate for the wrong name should NOT be trusted!");
1288 }
1289
1290 rdpTls* tls_new(rdpSettings* settings)
1291 {
1292         rdpTls* tls;
1293
1294         tls = (rdpTls*) calloc(1, sizeof(rdpTls));
1295
1296         if (!tls)
1297                 return NULL;
1298
1299         winpr_InitializeSSL(WINPR_SSL_INIT_DEFAULT);
1300
1301         tls->settings = settings;
1302
1303         if (!settings->ServerMode)
1304         {
1305                 tls->certificate_store = certificate_store_new(settings);
1306
1307                 if (!tls->certificate_store)
1308                         goto out_free;
1309         }
1310
1311         tls->alertLevel = TLS_ALERT_LEVEL_WARNING;
1312         tls->alertDescription = TLS_ALERT_DESCRIPTION_CLOSE_NOTIFY;
1313
1314         return tls;
1315
1316 out_free:
1317         free(tls);
1318         return NULL;
1319 }
1320
1321 void tls_free(rdpTls* tls)
1322 {
1323         if (!tls)
1324                 return;
1325
1326         if (tls->ctx)
1327         {
1328                 SSL_CTX_free(tls->ctx);
1329                 tls->ctx = NULL;
1330         }
1331
1332         if (tls->bio)
1333         {
1334                 BIO_free(tls->bio);
1335                 tls->bio = NULL;
1336         }
1337
1338         if (tls->underlying)
1339         {
1340                 BIO_free(tls->underlying);
1341                 tls->underlying = NULL;
1342         }
1343
1344         if (tls->PublicKey)
1345         {
1346                 free(tls->PublicKey);
1347                 tls->PublicKey = NULL;
1348         }
1349
1350         if (tls->Bindings)
1351         {
1352                 free(tls->Bindings->Bindings);
1353                 free(tls->Bindings);
1354                 tls->Bindings = NULL;
1355         }
1356
1357         if (tls->certificate_store)
1358         {
1359                 certificate_store_free(tls->certificate_store);
1360                 tls->certificate_store = NULL;
1361         }
1362
1363         free(tls);
1364 }