Imported Upstream version 2.74.0
[platform/upstream/glib-networking.git] / tls / openssl / gtlsconnection-openssl.c
1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /*
3  * gtlsconnection-openssl.c
4  *
5  * Copyright (C) 2015 NICE s.r.l.
6  *
7  * This file is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This file is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  *
20  * In addition, when the library is used with OpenSSL, a special
21  * exception applies. Refer to the LICENSE_EXCEPTION file for details.
22  *
23  * Authors: Ignacio Casal Quinteiro
24  */
25
26 #include "config.h"
27 #include "glib.h"
28
29 #include <errno.h>
30 #include <stdarg.h>
31 #include "openssl-include.h"
32
33 #include "gtlsconnection-openssl.h"
34 #include "gtlsbackend-openssl.h"
35 #include "gtlscertificate-openssl.h"
36 #include "gtlsdatabase-openssl.h"
37 #include "gtlsbio.h"
38 #include "gtlslog.h"
39
40 #include <glib/gi18n-lib.h>
41
42 #define DTLS_MESSAGE_MAX_SIZE 65536
43
44 typedef struct _GTlsConnectionOpensslPrivate
45 {
46   BIO *bio;
47   guint8 *dtls_rx;
48   guint8 *dtls_tx;
49   GMutex ssl_mutex;
50
51   gboolean shutting_down;
52 } GTlsConnectionOpensslPrivate;
53
54 typedef int (*GTlsOpensslIOFunc) (SSL *ssl, gpointer user_data);
55
56 typedef struct _ReadRequest
57 {
58   void *buffer;
59   gsize count;
60 } ReadRequest;
61
62 typedef struct _WriteRequest
63 {
64   const void *buffer;
65   gsize count;
66 } WriteRequest;
67
68 static void g_tls_connection_openssl_initable_iface_init (GInitableIface *iface);
69
70 G_DEFINE_ABSTRACT_TYPE_WITH_CODE (GTlsConnectionOpenssl, g_tls_connection_openssl, G_TYPE_TLS_CONNECTION_BASE,
71                                   G_ADD_PRIVATE (GTlsConnectionOpenssl)
72                                   G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE,
73                                                          g_tls_connection_openssl_initable_iface_init))
74
75 static void
76 g_tls_connection_openssl_finalize (GObject *object)
77 {
78   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (object);
79   GTlsConnectionOpensslPrivate *priv;
80
81   priv = g_tls_connection_openssl_get_instance_private (openssl);
82
83   g_free (priv->dtls_rx);
84   g_free (priv->dtls_tx);
85   g_mutex_clear (&priv->ssl_mutex);
86
87   G_OBJECT_CLASS (g_tls_connection_openssl_parent_class)->finalize (object);
88 }
89
90 static GTlsSafeRenegotiationStatus
91 g_tls_connection_openssl_handshake_thread_safe_renegotiation_status (GTlsConnectionBase *tls)
92 {
93   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
94   SSL *ssl;
95
96   ssl = g_tls_connection_openssl_get_ssl (openssl);
97
98   return SSL_get_secure_renegotiation_support (ssl) ? G_TLS_SAFE_RENEGOTIATION_SUPPORTED_BY_PEER
99                                                     : G_TLS_SAFE_RENEGOTIATION_UNSUPPORTED;
100 }
101
102 static GTlsConnectionBaseStatus
103 end_openssl_io (GTlsConnectionOpenssl  *openssl,
104                 GIOCondition            direction,
105                 int                     ret,
106                 gboolean                blocking,
107                 GError                **error,
108                 const char             *err_prefix,
109                 const char             *err_str)
110 {
111   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (openssl);
112   GTlsConnectionOpensslPrivate *priv;
113   int err_code, err, err_lib, reason;
114   GError *my_error = NULL;
115   GTlsConnectionBaseStatus status;
116   SSL *ssl;
117
118   priv = g_tls_connection_openssl_get_instance_private (openssl);
119
120   ssl = g_tls_connection_openssl_get_ssl (openssl);
121
122   err_code = SSL_get_error (ssl, ret);
123
124   status = g_tls_connection_base_pop_io (tls, direction, ret > 0, &my_error);
125
126   if ((err_code == SSL_ERROR_WANT_READ ||
127        err_code == SSL_ERROR_WANT_WRITE) &&
128       blocking)
129     {
130       if (my_error)
131         g_error_free (my_error);
132       return G_TLS_CONNECTION_BASE_TRY_AGAIN;
133     }
134
135   if (err_code == SSL_ERROR_ZERO_RETURN)
136     return G_TLS_CONNECTION_BASE_OK;
137
138   if (status == G_TLS_CONNECTION_BASE_OK ||
139       status == G_TLS_CONNECTION_BASE_WOULD_BLOCK ||
140       status == G_TLS_CONNECTION_BASE_TIMED_OUT)
141     {
142       if (my_error)
143         g_propagate_error (error, my_error);
144       return status;
145     }
146
147   /* This case is documented that it may happen and that is perfectly fine */
148   if (err_code == SSL_ERROR_SYSCALL &&
149       (priv->shutting_down && (!my_error || g_error_matches (my_error, G_IO_ERROR, G_IO_ERROR_BROKEN_PIPE))))
150     {
151       g_clear_error (&my_error);
152       return G_TLS_CONNECTION_BASE_OK;
153     }
154
155   err = ERR_get_error ();
156   err_lib = ERR_GET_LIB (err);
157   reason = ERR_GET_REASON (err);
158
159   if (g_tls_connection_base_is_handshaking (tls) && !g_tls_connection_base_ever_handshaked (tls))
160     {
161       if (reason == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE && my_error)
162         {
163           g_propagate_error (error, my_error);
164           return G_TLS_CONNECTION_BASE_ERROR;
165         }
166       else if (reason == SSL_R_BAD_PACKET_LENGTH ||
167                reason == SSL_R_UNKNOWN_ALERT_TYPE ||
168                reason == SSL_R_DECRYPTION_FAILED ||
169                reason == SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC ||
170                reason == SSL_R_BAD_PROTOCOL_VERSION_NUMBER ||
171                reason == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE ||
172                reason == SSL_R_UNKNOWN_PROTOCOL)
173         {
174           g_clear_error (&my_error);
175           g_set_error (error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS,
176                        _("Peer failed to perform TLS handshake: %s"), ERR_reason_error_string (err));
177           return G_TLS_CONNECTION_BASE_ERROR;
178         }
179     }
180
181 #ifdef SSL_R_SHUTDOWN_WHILE_IN_INIT
182   /* XXX: this error happens on ubuntu when shutting down the connection, it
183    * seems to be a bug in a specific version of openssl, so let's handle it
184    * gracefully
185    */
186   if (reason == SSL_R_SHUTDOWN_WHILE_IN_INIT)
187     {
188       g_clear_error (&my_error);
189       return G_TLS_CONNECTION_BASE_OK;
190     }
191 #endif
192
193   if (reason == SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE
194 #ifdef SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED
195       || reason == SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED
196 #endif
197      )
198     {
199       g_clear_error (&my_error);
200       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED,
201                            _("TLS connection peer did not send a certificate"));
202       return status;
203     }
204
205   if (reason == SSL_R_CERTIFICATE_VERIFY_FAILED)
206     {
207       g_clear_error (&my_error);
208       g_set_error (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
209                    _("Unacceptable TLS certificate"));
210       return G_TLS_CONNECTION_BASE_ERROR;
211     }
212
213   if (reason == SSL_R_TLSV1_ALERT_UNKNOWN_CA)
214     {
215       g_clear_error (&my_error);
216       g_set_error (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
217                    _("Unacceptable TLS certificate authority"));
218       return G_TLS_CONNECTION_BASE_ERROR;
219     }
220
221   if (err_lib == ERR_LIB_RSA && reason == RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY)
222     {
223       g_clear_error (&my_error);
224       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
225                            _("Digest too big for RSA key"));
226       return G_TLS_CONNECTION_BASE_ERROR;
227     }
228
229 #ifdef SSL_R_NO_RENEGOTIATION
230   if (reason == SSL_R_NO_RENEGOTIATION)
231     {
232       g_clear_error (&my_error);
233       g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_MISC,
234                            _("Secure renegotiation is disabled"));
235       return G_TLS_CONNECTION_BASE_REHANDSHAKE;
236     }
237 #endif
238
239   if (my_error)
240     g_propagate_error (error, my_error);
241
242   if (ret == 0 && err == 0 && err_lib == 0 && err_code == SSL_ERROR_SYSCALL
243       && (direction == G_IO_IN || direction == G_IO_OUT))
244     {
245       /* SSL_ERROR_SYSCALL usually means we have no bloody idea what has happened
246        * but when ret for read or write is 0 and all others error codes as well
247        * - this is normally Early EOF condition
248        */
249       if (!g_tls_connection_get_require_close_notify (G_TLS_CONNECTION (openssl)))
250         return G_TLS_CONNECTION_BASE_OK;
251
252       if (error && !*error)
253         *error = g_error_new (G_TLS_ERROR, G_TLS_ERROR_EOF, _("%s: The connection is broken"), gettext (err_prefix));
254     }
255   else if (error && !*error)
256     *error = g_error_new (G_TLS_ERROR, G_TLS_ERROR_MISC, "%s: %s", gettext (err_prefix), err_str);
257
258   return G_TLS_CONNECTION_BASE_ERROR;
259 }
260
261 static GTlsConnectionBaseStatus
262 perform_openssl_io (GTlsConnectionOpenssl  *openssl,
263                     GIOCondition            direction,
264                     GTlsOpensslIOFunc       perform_func,
265                     gpointer                perform_data,
266                     gint64                  timeout,
267                     GCancellable           *cancellable,
268                     int                    *out_ret,
269                     GError                **error,
270                     const char             *err_prefix)
271 {
272   GTlsConnectionBaseStatus status;
273   GTlsConnectionBase *tls;
274   GTlsConnectionOpensslPrivate *priv;
275   SSL *ssl;
276   gint64 deadline;
277   int ret;
278
279   tls = G_TLS_CONNECTION_BASE (openssl);
280   priv = g_tls_connection_openssl_get_instance_private (openssl);
281   ssl = g_tls_connection_openssl_get_ssl (openssl);
282
283   if (timeout >= 0)
284     deadline = g_get_monotonic_time () + timeout;
285   else
286     deadline = -1;
287
288   while (TRUE)
289     {
290       GIOCondition io_needed;
291       char error_str[256];
292       struct timeval tv;
293       gint64 io_timeout;
294
295       g_tls_connection_base_push_io (tls, direction, 0, cancellable);
296
297       if (g_tls_connection_base_is_dtls (tls))
298         DTLSv1_handle_timeout (ssl);
299
300       ret = perform_func (ssl, perform_data);
301
302       switch (SSL_get_error (ssl, ret))
303         {
304           case SSL_ERROR_WANT_READ:
305             io_needed = G_IO_IN;
306             break;
307           case SSL_ERROR_WANT_WRITE:
308             io_needed = G_IO_OUT;
309             break;
310           default:
311             io_needed = 0;
312             break;
313         }
314
315       ERR_error_string_n (SSL_get_error (ssl, ret), error_str,
316                           sizeof (error_str));
317       status = end_openssl_io (openssl, direction, ret, TRUE, error, err_prefix,
318                                error_str);
319
320       if (status != G_TLS_CONNECTION_BASE_TRY_AGAIN)
321         break;
322
323       if (g_tls_connection_base_is_dtls (tls) && DTLSv1_get_timeout (ssl, &tv))
324         io_timeout = (tv.tv_sec * G_USEC_PER_SEC) + tv.tv_usec;
325       else
326         io_timeout = -1;
327
328       if (deadline != -1)
329         {
330           gint64 remaining = MAX (deadline - g_get_monotonic_time (), 0);
331
332           if (io_timeout != -1)
333             io_timeout = MIN (io_timeout, remaining);
334           else
335             io_timeout = remaining;
336         }
337
338       if (io_timeout == 0)
339         break;
340
341       g_tls_bio_wait_available (priv->bio, io_needed, io_timeout, cancellable);
342     }
343
344   if (status == G_TLS_CONNECTION_BASE_TRY_AGAIN)
345     {
346       if (timeout == 0)
347         {
348           status = G_TLS_CONNECTION_BASE_WOULD_BLOCK;
349           g_clear_error (error);
350           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK,
351                                "Operation would block");
352         }
353       else if (timeout > 0)
354         {
355           status = G_TLS_CONNECTION_BASE_TIMED_OUT;
356           g_clear_error (error);
357           g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
358                                _("Socket I/O timed out"));
359         }
360     }
361
362   if (out_ret)
363     *out_ret = ret;
364
365   return status;
366 }
367
368 static int
369 _openssl_alpn_select_cb (SSL                  *ssl,
370                          const unsigned char **out,
371                          unsigned char        *outlen,
372                          const unsigned char  *in,
373                          unsigned int          inlen,
374                          void                 *arg)
375 {
376   GTlsConnectionBase *tls = arg;
377   int ret = SSL_TLSEXT_ERR_NOACK;
378   gchar **advertised_protocols = NULL;
379   gchar *logbuf;
380
381   logbuf = g_strndup ((const gchar *)in, inlen);
382   g_tls_log_debug (tls, "ALPN their protocols: %s", logbuf);
383   g_free (logbuf);
384
385   g_object_get (G_OBJECT (tls),
386                 "advertised-protocols", &advertised_protocols,
387                 NULL);
388
389   if (!advertised_protocols)
390     return ret;
391
392   if (g_strv_length (advertised_protocols) > 0)
393     {
394       GByteArray *protocols = g_byte_array_new ();
395       int i;
396       guint8 slen = 0;
397       guint8 *spd = NULL;
398
399       for (i = 0; advertised_protocols[i]; i++)
400         {
401           guint8 len = strlen (advertised_protocols[i]);
402           g_byte_array_append (protocols, &len, 1);
403           g_byte_array_append (protocols,
404                                (guint8 *)advertised_protocols[i],
405                                len);
406         }
407       logbuf = g_strndup ((const gchar *)protocols->data, protocols->len);
408       g_tls_log_debug (tls, "ALPN our protocols: %s", logbuf);
409       g_free (logbuf);
410
411       /* pointer to memory inside in[0..inlen] is returned on success
412        * pointer to protocols->data is returned on failure */
413       ret = SSL_select_next_proto (&spd, &slen,
414                                    in, inlen,
415                                    protocols->data, protocols->len);
416       if (ret == OPENSSL_NPN_NEGOTIATED)
417         {
418           logbuf = g_strndup ((const gchar *)spd, slen);
419           g_tls_log_debug (tls, "ALPN selected protocol %s", logbuf);
420           g_free (logbuf);
421
422           ret = SSL_TLSEXT_ERR_OK;
423           *out = spd;
424           *outlen = slen;
425         }
426       else
427         {
428           g_tls_log_debug (tls, "ALPN no matching protocol");
429           ret = SSL_TLSEXT_ERR_NOACK;
430         }
431
432       g_byte_array_unref (protocols);
433     }
434
435   g_strfreev (advertised_protocols);
436   return ret;
437 }
438
439 static void
440 g_tls_connection_openssl_prepare_handshake (GTlsConnectionBase  *tls,
441                                             gchar              **advertised_protocols)
442 {
443   SSL *ssl;
444
445   if (!advertised_protocols)
446     return;
447
448   ssl = g_tls_connection_openssl_get_ssl (G_TLS_CONNECTION_OPENSSL (tls));
449
450   if (G_IS_TLS_SERVER_CONNECTION (tls))
451     {
452       SSL_CTX *ctx = SSL_get_SSL_CTX(ssl);
453
454       g_tls_log_debug (tls, "Setting ALPN Callback on %p", ctx);
455       SSL_CTX_set_alpn_select_cb (ctx, _openssl_alpn_select_cb, tls);
456
457       return;
458     }
459
460   if (g_strv_length (advertised_protocols) > 0)
461     {
462       GByteArray *protocols = g_byte_array_new ();
463       int ret, i;
464
465       for (i = 0; advertised_protocols[i]; i++)
466         {
467           guint8 len = strlen (advertised_protocols[i]);
468           g_byte_array_append (protocols, &len, 1);
469           g_byte_array_append (protocols, (guint8 *)advertised_protocols[i], len);
470         }
471       ret = SSL_set_alpn_protos (ssl, protocols->data, protocols->len);
472       if (ret)
473         g_tls_log_debug (tls, "Error setting ALPN protocols: %d", ret);
474       else
475         {
476           gchar *logbuf = g_strndup ((const gchar *)protocols->data, protocols->len);
477
478           g_tls_log_debug (tls, "Setting ALPN protocols to %s", logbuf);
479           g_free (logbuf);
480         }
481       g_byte_array_unref (protocols);
482     }
483 }
484
485 static GTlsCertificateFlags
486 g_tls_connection_openssl_verify_chain (GTlsConnectionBase       *tls,
487                                        GTlsCertificate          *chain,
488                                        const gchar              *purpose,
489                                        GSocketConnectable       *identity,
490                                        GTlsInteraction          *interaction,
491                                        GTlsDatabaseVerifyFlags   flags,
492                                        GCancellable             *cancellable,
493                                        GError                  **error)
494 {
495   GTlsDatabase *database;
496   GTlsCertificateFlags errors = 0;
497   gboolean is_client = G_IS_TLS_CLIENT_CONNECTION (tls);
498
499   database = g_tls_connection_get_database (G_TLS_CONNECTION (tls));
500   if (database)
501     {
502       errors |= g_tls_database_verify_chain (database,
503                                              chain,
504                                              is_client ? G_TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER : G_TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT,
505                                              identity,
506                                              g_tls_connection_get_interaction (G_TLS_CONNECTION (tls)),
507                                              G_TLS_DATABASE_VERIFY_NONE,
508                                              NULL,
509                                              error);
510     }
511   else
512     {
513       errors |= G_TLS_CERTIFICATE_UNKNOWN_CA;
514       errors |= g_tls_certificate_verify (chain, identity, NULL);
515     }
516
517   return errors;
518 }
519
520 static GTlsProtocolVersion
521 glib_protocol_version_from_openssl (int protocol_version)
522 {
523   switch (protocol_version)
524     {
525     case SSL3_VERSION:
526       return G_TLS_PROTOCOL_VERSION_SSL_3_0;
527     case TLS1_VERSION:
528       return G_TLS_PROTOCOL_VERSION_TLS_1_0;
529     case TLS1_1_VERSION:
530       return G_TLS_PROTOCOL_VERSION_TLS_1_1;
531     case TLS1_2_VERSION:
532       return G_TLS_PROTOCOL_VERSION_TLS_1_2;
533     case TLS1_3_VERSION:
534       return G_TLS_PROTOCOL_VERSION_TLS_1_3;
535     case DTLS1_VERSION:
536       return G_TLS_PROTOCOL_VERSION_DTLS_1_0;
537     case DTLS1_2_VERSION:
538       return G_TLS_PROTOCOL_VERSION_DTLS_1_2;
539     default:
540       return G_TLS_PROTOCOL_VERSION_UNKNOWN;
541     }
542 }
543
544 static void
545 g_tls_connection_openssl_complete_handshake (GTlsConnectionBase   *tls,
546                                              gboolean              handshake_succeeded,
547                                              gchar               **negotiated_protocol,
548                                              GTlsProtocolVersion  *protocol_version,
549                                              gchar               **ciphersuite_name,
550                                              GError              **error)
551 {
552   SSL *ssl;
553   SSL_SESSION *session;
554   unsigned int len = 0;
555   const unsigned char *data = NULL;
556
557   if (!handshake_succeeded)
558     return;
559
560   ssl = g_tls_connection_openssl_get_ssl (G_TLS_CONNECTION_OPENSSL (tls));
561   session = SSL_get_session (ssl);
562
563   SSL_get0_alpn_selected (ssl, &data, &len);
564
565   g_tls_log_debug (tls, "negotiated ALPN protocols: [%d]%p", len, data);
566
567   if (data && len > 0)
568     {
569       g_assert (!*negotiated_protocol);
570       *negotiated_protocol = g_strndup ((gchar *)data, len);
571     }
572
573   *protocol_version = glib_protocol_version_from_openssl (SSL_SESSION_get_protocol_version (session));
574   *ciphersuite_name = g_strdup (SSL_get_cipher_name (ssl));
575 }
576
577 static int
578 perform_rehandshake (SSL      *ssl,
579                      gpointer  user_data)
580 {
581   GTlsConnectionBase *tls = user_data;
582   int ret = 1; /* always look on the bright side of life */
583
584 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
585   if (SSL_version(ssl) >= TLS1_3_VERSION)
586     ret = SSL_key_update (ssl, SSL_KEY_UPDATE_REQUESTED);
587   else if (SSL_get_secure_renegotiation_support (ssl) && !(SSL_get_options(ssl) & SSL_OP_NO_RENEGOTIATION))
588     /* remote and local peers both can rehandshake */
589     ret = SSL_renegotiate (ssl);
590   else
591     g_tls_log_debug (tls, "Secure renegotiation is not supported");
592 #else
593   ret = SSL_renegotiate (ssl);
594 #endif
595
596   return ret;
597 }
598
599 static GTlsConnectionBaseStatus
600 g_tls_connection_openssl_handshake_thread_request_rehandshake (GTlsConnectionBase  *tls,
601                                                                gint64               timeout,
602                                                                GCancellable        *cancellable,
603                                                                GError             **error)
604 {
605   /* On a client-side connection, SSL_renegotiate() itself will start
606    * a rehandshake, so we only need to do something special here for
607    * server-side connections.
608    */
609   if (!G_IS_TLS_SERVER_CONNECTION (tls))
610     return G_TLS_CONNECTION_BASE_OK;
611
612   return perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls), G_IO_IN | G_IO_OUT,
613                              perform_rehandshake, tls, timeout, cancellable,
614                              NULL, error, N_("Error performing TLS handshake"));
615 }
616
617 static GTlsCertificate *
618 g_tls_connection_openssl_retrieve_peer_certificate (GTlsConnectionBase *tls)
619 {
620   X509 *peer;
621   STACK_OF (X509) *certs;
622   GTlsCertificateOpenssl *chain;
623   SSL *ssl;
624
625   ssl = g_tls_connection_openssl_get_ssl (G_TLS_CONNECTION_OPENSSL (tls));
626
627   peer = SSL_get_peer_certificate (ssl);
628   if (!peer)
629     return NULL;
630
631   certs = SSL_get_peer_cert_chain (ssl);
632   if (!certs)
633     {
634       X509_free (peer);
635       return NULL;
636     }
637
638   chain = g_tls_certificate_openssl_build_chain (peer, certs);
639   X509_free (peer);
640   if (!chain)
641     return NULL;
642
643   return G_TLS_CERTIFICATE (chain);
644 }
645
646 static gboolean
647 openssl_get_binding_tls_unique (GTlsConnectionOpenssl  *tls,
648                                 GByteArray             *data,
649                                 GError                **error)
650 {
651   SSL *ssl = g_tls_connection_openssl_get_ssl (tls);
652   gboolean is_client = G_IS_TLS_CLIENT_CONNECTION (tls);
653   gboolean resumed = SSL_session_reused (ssl);
654   size_t len = 64;
655
656 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
657   if (SSL_version (ssl) >= TLS1_3_VERSION)
658     {
659       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_GENERAL_ERROR,
660                    _("The request is invalid."));
661       return FALSE;
662     }
663 #endif
664
665   /* This is a drill */
666   if (!data)
667     return TRUE;
668
669   do {
670     g_byte_array_set_size (data, len);
671     if ((resumed && is_client) || (!resumed && !is_client))
672       len = SSL_get_peer_finished (ssl, data->data, data->len);
673     else
674       len = SSL_get_finished (ssl, data->data, data->len);
675   } while (len > data->len);
676
677   if (len > 0)
678     {
679       g_byte_array_set_size (data, len);
680       return TRUE;
681     }
682   g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_AVAILABLE,
683                _("Channel binding data tls-unique is not available"));
684   return FALSE;
685 }
686
687 static gboolean
688 openssl_get_binding_tls_server_end_point (GTlsConnectionOpenssl  *tls,
689                                           GByteArray             *data,
690                                           GError                **error)
691 {
692   SSL *ssl = g_tls_connection_openssl_get_ssl (tls);
693   gboolean is_client = G_IS_TLS_CLIENT_CONNECTION (tls);
694   int algo_nid;
695   const EVP_MD *algo = NULL;
696   X509 *crt;
697
698   if (is_client)
699     crt = SSL_get_peer_certificate (ssl);
700   else
701     crt = SSL_get_certificate (ssl);
702
703   if (!crt)
704     {
705       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_AVAILABLE,
706                    _("X.509 Certificate is not available on the connection"));
707       return FALSE;
708     }
709
710   if (!OBJ_find_sigid_algs (X509_get_signature_nid (crt), &algo_nid, NULL))
711     {
712       X509_free (crt);
713       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_GENERAL_ERROR,
714                    _("Unable to obtain certificate signature algorithm"));
715       return FALSE;
716     }
717
718   /* This is a drill */
719   if (!data)
720     {
721       if (is_client)
722         X509_free (crt);
723       return TRUE;
724     }
725
726   switch (algo_nid)
727     {
728     case NID_md5:
729     case NID_sha1:
730       algo_nid = NID_sha256;
731       break;
732     case NID_md5_sha1:
733       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_SUPPORTED,
734                    _("Current X.509 certificate uses unknown or unsupported signature algorithm"));
735       if (is_client)
736         X509_free (crt);
737       return FALSE;
738     }
739
740   g_byte_array_set_size (data, EVP_MAX_MD_SIZE);
741   algo = EVP_get_digestbynid (algo_nid);
742   if (X509_digest (crt, algo, data->data, &(data->len)))
743     {
744       if (is_client)
745         X509_free (crt);
746       return TRUE;
747     }
748
749   if (is_client)
750     X509_free (crt);
751   g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_GENERAL_ERROR,
752                _("Failed to generate X.509 certificate digest"));
753   return FALSE;
754 }
755
756 #define RFC5705_LABEL_DATA "EXPORTER-Channel-Binding"
757 #define RFC5705_LABEL_LEN 24
758 static gboolean
759 openssl_get_binding_tls_exporter (GTlsConnectionOpenssl  *tls,
760                                   GByteArray             *data,
761                                   GError                **error)
762 {
763   SSL *ssl = g_tls_connection_openssl_get_ssl (tls);
764   size_t  ctx_len = 0;
765   guint8 *context = (guint8 *)"";
766   int ret;
767
768   if (!data)
769     return TRUE;
770
771   g_byte_array_set_size (data, 32);
772   ret = SSL_export_keying_material (ssl,
773                                     data->data, data->len,
774                                     RFC5705_LABEL_DATA, RFC5705_LABEL_LEN,
775                                     context, ctx_len,
776                                     1 /* use context */);
777
778   if (ret > 0)
779     return TRUE;
780
781   if (ret < 0)
782     g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_SUPPORTED,
783                  _("TLS Connection does not support TLS-Exporter feature"));
784   else
785     g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_GENERAL_ERROR,
786                  _("Unexpected error while exporting keying data"));
787
788   return FALSE;
789 }
790
791 static gboolean
792 g_tls_connection_openssl_get_channel_binding_data (GTlsConnectionBase      *tls,
793                                                    GTlsChannelBindingType   type,
794                                                    GByteArray              *data,
795                                                    GError                 **error)
796 {
797   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
798
799   switch (type)
800     {
801     case G_TLS_CHANNEL_BINDING_TLS_UNIQUE:
802       return openssl_get_binding_tls_unique (openssl, data, error);
803     case G_TLS_CHANNEL_BINDING_TLS_SERVER_END_POINT:
804       return openssl_get_binding_tls_server_end_point (openssl, data, error);
805     case G_TLS_CHANNEL_BINDING_TLS_EXPORTER:
806       return openssl_get_binding_tls_exporter (openssl, data, error);
807     default:
808       /* Anyone to implement tls-unique-for-telnet? */
809       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_IMPLEMENTED,
810                    _("Requested channel binding type is not implemented"));
811     }
812   return FALSE;
813 }
814
815 static GTlsConnectionBaseStatus
816 g_tls_connection_openssl_handshake_thread_handshake (GTlsConnectionBase  *tls,
817                                                      gint64               timeout,
818                                                      GCancellable        *cancellable,
819                                                      GError             **error)
820 {
821   GTlsConnectionBaseStatus status;
822   int ret;
823
824   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls),
825                                G_IO_IN | G_IO_OUT,
826                                (GTlsOpensslIOFunc) SSL_do_handshake,
827                                NULL, timeout, cancellable, &ret, error,
828                                N_("Error reading data from TLS socket"));
829
830   if (ret > 0)
831     {
832       if (!g_tls_connection_base_handshake_thread_verify_certificate (tls))
833         {
834           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
835                                _("Unacceptable TLS certificate"));
836           return G_TLS_CONNECTION_BASE_ERROR;
837         }
838     }
839
840   return status;
841 }
842
843 static void
844 g_tls_connection_openssl_push_io (GTlsConnectionBase *tls,
845                                   GIOCondition        direction,
846                                   gint64              timeout,
847                                   GCancellable       *cancellable)
848 {
849   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
850   GTlsConnectionOpensslPrivate *priv;
851   GError **error;
852
853   priv = g_tls_connection_openssl_get_instance_private (openssl);
854
855   G_TLS_CONNECTION_BASE_CLASS (g_tls_connection_openssl_parent_class)->push_io (tls, direction,
856                                                                                 timeout, cancellable);
857
858   if (direction & G_IO_IN)
859     {
860       error = g_tls_connection_base_get_read_error (tls);
861       g_tls_bio_set_read_cancellable (priv->bio, cancellable);
862       g_clear_error (error);
863       g_tls_bio_set_read_error (priv->bio, error);
864     }
865
866   if (direction & G_IO_OUT)
867     {
868       error = g_tls_connection_base_get_write_error (tls);
869       g_tls_bio_set_write_cancellable (priv->bio, cancellable);
870       g_clear_error (error);
871       g_tls_bio_set_write_error (priv->bio, error);
872     }
873
874   g_mutex_lock (&priv->ssl_mutex);
875 }
876
877 static GTlsConnectionBaseStatus
878 g_tls_connection_openssl_pop_io (GTlsConnectionBase  *tls,
879                                  GIOCondition         direction,
880                                  gboolean             success,
881                                  GError             **error)
882 {
883   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
884   GTlsConnectionOpensslPrivate *priv;
885
886   priv = g_tls_connection_openssl_get_instance_private (openssl);
887
888   g_mutex_unlock (&priv->ssl_mutex);
889
890   if (direction & G_IO_IN)
891     g_tls_bio_set_read_cancellable (priv->bio, NULL);
892
893   if (direction & G_IO_OUT)
894     g_tls_bio_set_write_cancellable (priv->bio, NULL);
895
896   return G_TLS_CONNECTION_BASE_CLASS (g_tls_connection_openssl_parent_class)->pop_io (tls, direction,
897                                                                                       success, error);
898 }
899
900 static int
901 perform_read (SSL      *ssl,
902               gpointer  user_data)
903 {
904   ReadRequest *req = user_data;
905
906   return SSL_read (ssl, req->buffer, req->count);
907 }
908
909 static GTlsConnectionBaseStatus
910 g_tls_connection_openssl_read (GTlsConnectionBase    *tls,
911                                void                  *buffer,
912                                gsize                  count,
913                                gint64                 timeout,
914                                gssize                *nread,
915                                GCancellable          *cancellable,
916                                GError               **error)
917 {
918   GTlsConnectionBaseStatus status;
919   ReadRequest req = { buffer, count };
920   int ret;
921
922   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls), G_IO_IN,
923                                perform_read, &req, timeout, cancellable, &ret,
924                                error, N_("Error reading data from TLS socket"));
925
926   *nread = MAX (ret, 0);
927   return status;
928 }
929
930 static GTlsConnectionBaseStatus
931 g_tls_connection_openssl_read_message (GTlsConnectionBase  *tls,
932                                        GInputVector        *vectors,
933                                        guint                num_vectors,
934                                        gint64               timeout,
935                                        gssize              *nread,
936                                        GCancellable        *cancellable,
937                                        GError             **error)
938 {
939   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
940   GTlsConnectionOpensslPrivate *priv;
941   GTlsConnectionBaseStatus status;
942   gssize bytes_read;
943   gsize bytes_copied, bytes_remaining;
944   guint i;
945
946   *nread = 0;
947
948   priv = g_tls_connection_openssl_get_instance_private (openssl);
949
950   if (!priv->dtls_rx)
951     priv->dtls_rx = g_malloc (DTLS_MESSAGE_MAX_SIZE);
952
953   status = g_tls_connection_openssl_read (tls, priv->dtls_rx,
954                                           DTLS_MESSAGE_MAX_SIZE, timeout,
955                                           &bytes_read, cancellable, error);
956   if (status != G_TLS_CONNECTION_BASE_OK)
957     return status;
958
959   bytes_copied = 0;
960   bytes_remaining = bytes_read;
961   for (i = 0; i < num_vectors && bytes_remaining > 0; i++)
962     {
963       GInputVector *vector = &vectors[i];
964       gsize n;
965
966       n = MIN (bytes_remaining, vector->size);
967
968       memcpy (vector->buffer, priv->dtls_rx + bytes_copied, n);
969
970       bytes_copied += n;
971       bytes_remaining -= n;
972     }
973
974   *nread = bytes_copied;
975
976   return status;
977 }
978
979 static int
980 perform_write (SSL      *ssl,
981                gpointer  user_data)
982 {
983   WriteRequest *req = user_data;
984
985   return SSL_write (ssl, req->buffer, req->count);
986 }
987
988 static GTlsConnectionBaseStatus
989 g_tls_connection_openssl_write (GTlsConnectionBase    *tls,
990                                 const void            *buffer,
991                                 gsize                  count,
992                                 gint64                 timeout,
993                                 gssize                *nwrote,
994                                 GCancellable          *cancellable,
995                                 GError               **error)
996 {
997   GTlsConnectionBaseStatus status;
998   WriteRequest req = { buffer, count };
999   int ret;
1000
1001   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls), G_IO_OUT,
1002                                perform_write, &req, timeout, cancellable, &ret,
1003                                error, N_("Error writing data to TLS socket"));
1004
1005   *nwrote = MAX (ret, 0);
1006   return status;
1007 }
1008
1009 static GTlsConnectionBaseStatus
1010 g_tls_connection_openssl_write_message (GTlsConnectionBase  *tls,
1011                                         GOutputVector       *vectors,
1012                                         guint                num_vectors,
1013                                         gint64               timeout,
1014                                         gssize              *nwrote,
1015                                         GCancellable        *cancellable,
1016                                         GError             **error)
1017 {
1018   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
1019   GTlsConnectionOpensslPrivate *priv;
1020   gsize bytes_copied, bytes_available;
1021   guint i;
1022
1023   priv = g_tls_connection_openssl_get_instance_private (openssl);
1024
1025   if (!priv->dtls_tx)
1026     priv->dtls_tx = g_malloc (DTLS_MESSAGE_MAX_SIZE);
1027
1028   bytes_copied = 0;
1029   bytes_available = DTLS_MESSAGE_MAX_SIZE;
1030   for (i = 0; i < num_vectors && bytes_available > 0; i++)
1031     {
1032       GOutputVector *vector = &vectors[i];
1033       gsize n;
1034
1035       n = MIN (vector->size, bytes_available);
1036
1037       memcpy (priv->dtls_tx + bytes_copied, vector->buffer, n);
1038
1039       bytes_copied += n;
1040       bytes_available -= n;
1041     }
1042
1043   return g_tls_connection_openssl_write (tls, priv->dtls_tx, bytes_copied,
1044                                          timeout, nwrote, cancellable, error);
1045 }
1046
1047 static GTlsConnectionBaseStatus
1048 g_tls_connection_openssl_close (GTlsConnectionBase  *tls,
1049                                 gint64               timeout,
1050                                 GCancellable        *cancellable,
1051                                 GError             **error)
1052 {
1053   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
1054   GTlsConnectionOpensslPrivate *priv;
1055
1056   priv = g_tls_connection_openssl_get_instance_private (openssl);
1057
1058   priv->shutting_down = TRUE;
1059
1060   return perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls),
1061                              G_IO_IN | G_IO_OUT,
1062                              (GTlsOpensslIOFunc) SSL_shutdown,
1063                              NULL, timeout, cancellable, NULL, error,
1064                              N_("Error performing TLS close"));
1065 }
1066
1067 static void
1068 g_tls_connection_openssl_class_init (GTlsConnectionOpensslClass *klass)
1069 {
1070   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1071   GTlsConnectionBaseClass *base_class = G_TLS_CONNECTION_BASE_CLASS (klass);
1072
1073   object_class->finalize                                 = g_tls_connection_openssl_finalize;
1074
1075   base_class->prepare_handshake                          = g_tls_connection_openssl_prepare_handshake;
1076   base_class->verify_chain                               = g_tls_connection_openssl_verify_chain;
1077   base_class->complete_handshake                         = g_tls_connection_openssl_complete_handshake;
1078   base_class->handshake_thread_safe_renegotiation_status = g_tls_connection_openssl_handshake_thread_safe_renegotiation_status;
1079   base_class->handshake_thread_request_rehandshake       = g_tls_connection_openssl_handshake_thread_request_rehandshake;
1080   base_class->handshake_thread_handshake                 = g_tls_connection_openssl_handshake_thread_handshake;
1081   base_class->retrieve_peer_certificate                  = g_tls_connection_openssl_retrieve_peer_certificate;
1082   base_class->get_channel_binding_data                   = g_tls_connection_openssl_get_channel_binding_data;
1083   base_class->push_io                                    = g_tls_connection_openssl_push_io;
1084   base_class->pop_io                                     = g_tls_connection_openssl_pop_io;
1085   base_class->read_fn                                    = g_tls_connection_openssl_read;
1086   base_class->read_message_fn                            = g_tls_connection_openssl_read_message;
1087   base_class->write_fn                                   = g_tls_connection_openssl_write;
1088   base_class->write_message_fn                           = g_tls_connection_openssl_write_message;
1089   base_class->close_fn                                   = g_tls_connection_openssl_close;
1090 }
1091
1092 static int data_index = -1;
1093
1094 static gboolean
1095 g_tls_connection_openssl_initable_init (GInitable     *initable,
1096                                         GCancellable  *cancellable,
1097                                         GError       **error)
1098 {
1099   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (initable);
1100   GTlsConnectionOpensslPrivate *priv;
1101   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (initable);
1102   GIOStream *base_io_stream;
1103   GDatagramBased *base_socket;
1104   SSL *ssl;
1105
1106   g_object_get (tls,
1107                 "base-io-stream", &base_io_stream,
1108                 "base-socket", &base_socket,
1109                 NULL);
1110
1111   /* Ensure we are in TLS mode or DTLS mode. */
1112   g_return_val_if_fail (!!base_io_stream != !!base_socket, FALSE);
1113
1114   priv = g_tls_connection_openssl_get_instance_private (openssl);
1115
1116   ssl = g_tls_connection_openssl_get_ssl (openssl);
1117   g_assert (ssl);
1118
1119   if (data_index == -1) {
1120       data_index = SSL_get_ex_new_index (0, (void *)"gtlsconnection", NULL, NULL, NULL);
1121   }
1122   SSL_set_ex_data (ssl, data_index, openssl);
1123
1124   if (base_io_stream)
1125     priv->bio = g_tls_bio_new_from_iostream (base_io_stream);
1126   else
1127     priv->bio = g_tls_bio_new_from_datagram_based (base_socket);
1128
1129   SSL_set_bio (ssl, priv->bio, priv->bio);
1130
1131   g_clear_object (&base_io_stream);
1132   g_clear_object (&base_socket);
1133
1134   return TRUE;
1135 }
1136
1137 static void
1138 g_tls_connection_openssl_initable_iface_init (GInitableIface *iface)
1139 {
1140   iface->init = g_tls_connection_openssl_initable_init;
1141 }
1142
1143 static void
1144 g_tls_connection_openssl_init (GTlsConnectionOpenssl *openssl)
1145 {
1146   GTlsConnectionOpensslPrivate *priv;
1147
1148   priv = g_tls_connection_openssl_get_instance_private (openssl);
1149
1150   g_mutex_init (&priv->ssl_mutex);
1151 }
1152
1153 SSL *
1154 g_tls_connection_openssl_get_ssl (GTlsConnectionOpenssl *openssl)
1155 {
1156   g_return_val_if_fail (G_IS_TLS_CONNECTION_OPENSSL (openssl), NULL);
1157
1158   return G_TLS_CONNECTION_OPENSSL_GET_CLASS (openssl)->get_ssl (openssl);
1159 }
1160
1161 GTlsConnectionOpenssl *
1162 g_tls_connection_openssl_get_connection_from_ssl (SSL *ssl)
1163 {
1164   g_return_val_if_fail (ssl, NULL);
1165
1166   return SSL_get_ex_data (ssl, data_index);
1167 }