265845eea1cee5c02df8ae5ce9ac25fca0884eeb
[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"), err_prefix);
254     }
255   else if (error && !*error)
256     *error = g_error_new (G_TLS_ERROR, G_TLS_ERROR_MISC, "%s: %s", 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, _("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   /* XXX: remove the cast once public enum supports exporter */
800   switch ((int)type)
801     {
802     case G_TLS_CHANNEL_BINDING_TLS_UNIQUE:
803       return openssl_get_binding_tls_unique (openssl, data, error);
804       /* fall through */
805     case G_TLS_CHANNEL_BINDING_TLS_SERVER_END_POINT:
806       return openssl_get_binding_tls_server_end_point (openssl, data, error);
807       /* fall through */
808     case 100500:
809       return openssl_get_binding_tls_exporter (openssl, data, error);
810       /* fall through */
811     default:
812       /* Anyone to implement tls-unique-for-telnet? */
813       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_IMPLEMENTED,
814                    _("Requested channel binding type is not implemented"));
815     }
816   return FALSE;
817 }
818
819 static GTlsConnectionBaseStatus
820 g_tls_connection_openssl_handshake_thread_handshake (GTlsConnectionBase  *tls,
821                                                      gint64               timeout,
822                                                      GCancellable        *cancellable,
823                                                      GError             **error)
824 {
825   GTlsConnectionBaseStatus status;
826   int ret;
827
828   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls),
829                                G_IO_IN | G_IO_OUT,
830                                (GTlsOpensslIOFunc) SSL_do_handshake,
831                                NULL, timeout, cancellable, &ret, error,
832                                _("Error reading data from TLS socket"));
833
834   if (ret > 0)
835     {
836       if (!g_tls_connection_base_handshake_thread_verify_certificate (tls))
837         {
838           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
839                                _("Unacceptable TLS certificate"));
840           return G_TLS_CONNECTION_BASE_ERROR;
841         }
842     }
843
844   return status;
845 }
846
847 static void
848 g_tls_connection_openssl_push_io (GTlsConnectionBase *tls,
849                                   GIOCondition        direction,
850                                   gint64              timeout,
851                                   GCancellable       *cancellable)
852 {
853   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
854   GTlsConnectionOpensslPrivate *priv;
855   GError **error;
856
857   priv = g_tls_connection_openssl_get_instance_private (openssl);
858
859   G_TLS_CONNECTION_BASE_CLASS (g_tls_connection_openssl_parent_class)->push_io (tls, direction,
860                                                                                 timeout, cancellable);
861
862   if (direction & G_IO_IN)
863     {
864       error = g_tls_connection_base_get_read_error (tls);
865       g_tls_bio_set_read_cancellable (priv->bio, cancellable);
866       g_clear_error (error);
867       g_tls_bio_set_read_error (priv->bio, error);
868     }
869
870   if (direction & G_IO_OUT)
871     {
872       error = g_tls_connection_base_get_write_error (tls);
873       g_tls_bio_set_write_cancellable (priv->bio, cancellable);
874       g_clear_error (error);
875       g_tls_bio_set_write_error (priv->bio, error);
876     }
877
878   g_mutex_lock (&priv->ssl_mutex);
879 }
880
881 static GTlsConnectionBaseStatus
882 g_tls_connection_openssl_pop_io (GTlsConnectionBase  *tls,
883                                  GIOCondition         direction,
884                                  gboolean             success,
885                                  GError             **error)
886 {
887   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
888   GTlsConnectionOpensslPrivate *priv;
889
890   priv = g_tls_connection_openssl_get_instance_private (openssl);
891
892   g_mutex_unlock (&priv->ssl_mutex);
893
894   if (direction & G_IO_IN)
895     g_tls_bio_set_read_cancellable (priv->bio, NULL);
896
897   if (direction & G_IO_OUT)
898     g_tls_bio_set_write_cancellable (priv->bio, NULL);
899
900   return G_TLS_CONNECTION_BASE_CLASS (g_tls_connection_openssl_parent_class)->pop_io (tls, direction,
901                                                                                       success, error);
902 }
903
904 static int
905 perform_read (SSL      *ssl,
906               gpointer  user_data)
907 {
908   ReadRequest *req = user_data;
909
910   return SSL_read (ssl, req->buffer, req->count);
911 }
912
913 static GTlsConnectionBaseStatus
914 g_tls_connection_openssl_read (GTlsConnectionBase    *tls,
915                                void                  *buffer,
916                                gsize                  count,
917                                gint64                 timeout,
918                                gssize                *nread,
919                                GCancellable          *cancellable,
920                                GError               **error)
921 {
922   GTlsConnectionBaseStatus status;
923   ReadRequest req = { buffer, count };
924   int ret;
925
926   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls), G_IO_IN,
927                                perform_read, &req, timeout, cancellable, &ret,
928                                error, _("Error reading data from TLS socket"));
929
930   *nread = MAX (ret, 0);
931   return status;
932 }
933
934 static GTlsConnectionBaseStatus
935 g_tls_connection_openssl_read_message (GTlsConnectionBase  *tls,
936                                        GInputVector        *vectors,
937                                        guint                num_vectors,
938                                        gint64               timeout,
939                                        gssize              *nread,
940                                        GCancellable        *cancellable,
941                                        GError             **error)
942 {
943   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
944   GTlsConnectionOpensslPrivate *priv;
945   GTlsConnectionBaseStatus status;
946   gssize bytes_read;
947   gsize bytes_copied, bytes_remaining;
948   guint i;
949
950   *nread = 0;
951
952   priv = g_tls_connection_openssl_get_instance_private (openssl);
953
954   if (!priv->dtls_rx)
955     priv->dtls_rx = g_malloc (DTLS_MESSAGE_MAX_SIZE);
956
957   status = g_tls_connection_openssl_read (tls, priv->dtls_rx,
958                                           DTLS_MESSAGE_MAX_SIZE, timeout,
959                                           &bytes_read, cancellable, error);
960   if (status != G_TLS_CONNECTION_BASE_OK)
961     return status;
962
963   bytes_copied = 0;
964   bytes_remaining = bytes_read;
965   for (i = 0; i < num_vectors && bytes_remaining > 0; i++)
966     {
967       GInputVector *vector = &vectors[i];
968       gsize n;
969
970       n = MIN (bytes_remaining, vector->size);
971
972       memcpy (vector->buffer, priv->dtls_rx + bytes_copied, n);
973
974       bytes_copied += n;
975       bytes_remaining -= n;
976     }
977
978   *nread = bytes_copied;
979
980   return status;
981 }
982
983 static int
984 perform_write (SSL      *ssl,
985                gpointer  user_data)
986 {
987   WriteRequest *req = user_data;
988
989   return SSL_write (ssl, req->buffer, req->count);
990 }
991
992 static GTlsConnectionBaseStatus
993 g_tls_connection_openssl_write (GTlsConnectionBase    *tls,
994                                 const void            *buffer,
995                                 gsize                  count,
996                                 gint64                 timeout,
997                                 gssize                *nwrote,
998                                 GCancellable          *cancellable,
999                                 GError               **error)
1000 {
1001   GTlsConnectionBaseStatus status;
1002   WriteRequest req = { buffer, count };
1003   int ret;
1004
1005   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls), G_IO_OUT,
1006                                perform_write, &req, timeout, cancellable, &ret,
1007                                error, _("Error writing data to TLS socket"));
1008
1009   *nwrote = MAX (ret, 0);
1010   return status;
1011 }
1012
1013 static GTlsConnectionBaseStatus
1014 g_tls_connection_openssl_write_message (GTlsConnectionBase  *tls,
1015                                         GOutputVector       *vectors,
1016                                         guint                num_vectors,
1017                                         gint64               timeout,
1018                                         gssize              *nwrote,
1019                                         GCancellable        *cancellable,
1020                                         GError             **error)
1021 {
1022   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
1023   GTlsConnectionOpensslPrivate *priv;
1024   gsize bytes_copied, bytes_available;
1025   guint i;
1026
1027   priv = g_tls_connection_openssl_get_instance_private (openssl);
1028
1029   if (!priv->dtls_tx)
1030     priv->dtls_tx = g_malloc (DTLS_MESSAGE_MAX_SIZE);
1031
1032   bytes_copied = 0;
1033   bytes_available = DTLS_MESSAGE_MAX_SIZE;
1034   for (i = 0; i < num_vectors && bytes_available > 0; i++)
1035     {
1036       GOutputVector *vector = &vectors[i];
1037       gsize n;
1038
1039       n = MIN (vector->size, bytes_available);
1040
1041       memcpy (priv->dtls_tx + bytes_copied, vector->buffer, n);
1042
1043       bytes_copied += n;
1044       bytes_available -= n;
1045     }
1046
1047   return g_tls_connection_openssl_write (tls, priv->dtls_tx, bytes_copied,
1048                                          timeout, nwrote, cancellable, error);
1049 }
1050
1051 static GTlsConnectionBaseStatus
1052 g_tls_connection_openssl_close (GTlsConnectionBase  *tls,
1053                                 gint64               timeout,
1054                                 GCancellable        *cancellable,
1055                                 GError             **error)
1056 {
1057   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
1058   GTlsConnectionOpensslPrivate *priv;
1059
1060   priv = g_tls_connection_openssl_get_instance_private (openssl);
1061
1062   priv->shutting_down = TRUE;
1063
1064   return perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls),
1065                              G_IO_IN | G_IO_OUT,
1066                              (GTlsOpensslIOFunc) SSL_shutdown,
1067                              NULL, timeout, cancellable, NULL, error,
1068                              _("Error performing TLS close"));
1069 }
1070
1071 static void
1072 g_tls_connection_openssl_class_init (GTlsConnectionOpensslClass *klass)
1073 {
1074   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1075   GTlsConnectionBaseClass *base_class = G_TLS_CONNECTION_BASE_CLASS (klass);
1076
1077   object_class->finalize                                 = g_tls_connection_openssl_finalize;
1078
1079   base_class->prepare_handshake                          = g_tls_connection_openssl_prepare_handshake;
1080   base_class->verify_chain                               = g_tls_connection_openssl_verify_chain;
1081   base_class->complete_handshake                         = g_tls_connection_openssl_complete_handshake;
1082   base_class->handshake_thread_safe_renegotiation_status = g_tls_connection_openssl_handshake_thread_safe_renegotiation_status;
1083   base_class->handshake_thread_request_rehandshake       = g_tls_connection_openssl_handshake_thread_request_rehandshake;
1084   base_class->handshake_thread_handshake                 = g_tls_connection_openssl_handshake_thread_handshake;
1085   base_class->retrieve_peer_certificate                  = g_tls_connection_openssl_retrieve_peer_certificate;
1086   base_class->get_channel_binding_data                   = g_tls_connection_openssl_get_channel_binding_data;
1087   base_class->push_io                                    = g_tls_connection_openssl_push_io;
1088   base_class->pop_io                                     = g_tls_connection_openssl_pop_io;
1089   base_class->read_fn                                    = g_tls_connection_openssl_read;
1090   base_class->read_message_fn                            = g_tls_connection_openssl_read_message;
1091   base_class->write_fn                                   = g_tls_connection_openssl_write;
1092   base_class->write_message_fn                           = g_tls_connection_openssl_write_message;
1093   base_class->close_fn                                   = g_tls_connection_openssl_close;
1094 }
1095
1096 static int data_index = -1;
1097
1098 static gboolean
1099 g_tls_connection_openssl_initable_init (GInitable     *initable,
1100                                         GCancellable  *cancellable,
1101                                         GError       **error)
1102 {
1103   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (initable);
1104   GTlsConnectionOpensslPrivate *priv;
1105   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (initable);
1106   GIOStream *base_io_stream;
1107   GDatagramBased *base_socket;
1108   SSL *ssl;
1109
1110   g_object_get (tls,
1111                 "base-io-stream", &base_io_stream,
1112                 "base-socket", &base_socket,
1113                 NULL);
1114
1115   /* Ensure we are in TLS mode or DTLS mode. */
1116   g_return_val_if_fail (!!base_io_stream != !!base_socket, FALSE);
1117
1118   priv = g_tls_connection_openssl_get_instance_private (openssl);
1119
1120   ssl = g_tls_connection_openssl_get_ssl (openssl);
1121   g_assert (ssl);
1122
1123   if (data_index == -1) {
1124       data_index = SSL_get_ex_new_index (0, (void *)"gtlsconnection", NULL, NULL, NULL);
1125   }
1126   SSL_set_ex_data (ssl, data_index, openssl);
1127
1128   if (base_io_stream)
1129     priv->bio = g_tls_bio_new_from_iostream (base_io_stream);
1130   else
1131     priv->bio = g_tls_bio_new_from_datagram_based (base_socket);
1132
1133   SSL_set_bio (ssl, priv->bio, priv->bio);
1134
1135   g_clear_object (&base_io_stream);
1136   g_clear_object (&base_socket);
1137
1138   return TRUE;
1139 }
1140
1141 static void
1142 g_tls_connection_openssl_initable_iface_init (GInitableIface *iface)
1143 {
1144   iface->init = g_tls_connection_openssl_initable_init;
1145 }
1146
1147 static void
1148 g_tls_connection_openssl_init (GTlsConnectionOpenssl *openssl)
1149 {
1150   GTlsConnectionOpensslPrivate *priv;
1151
1152   priv = g_tls_connection_openssl_get_instance_private (openssl);
1153
1154   g_mutex_init (&priv->ssl_mutex);
1155 }
1156
1157 SSL *
1158 g_tls_connection_openssl_get_ssl (GTlsConnectionOpenssl *openssl)
1159 {
1160   g_return_val_if_fail (G_IS_TLS_CONNECTION_OPENSSL (openssl), NULL);
1161
1162   return G_TLS_CONNECTION_OPENSSL_GET_CLASS (openssl)->get_ssl (openssl);
1163 }
1164
1165 GTlsConnectionOpenssl *
1166 g_tls_connection_openssl_get_connection_from_ssl (SSL *ssl)
1167 {
1168   g_return_val_if_fail (ssl, NULL);
1169
1170   return SSL_get_ex_data (ssl, data_index);
1171 }