c6cfb031e78a1993b23ad140732ccd0ca4a90112
[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   TIZEN_LOGI("tls[%p]", tls);
446   if (!advertised_protocols)
447     return;
448
449   ssl = g_tls_connection_openssl_get_ssl (G_TLS_CONNECTION_OPENSSL (tls));
450
451   if (G_IS_TLS_SERVER_CONNECTION (tls))
452     {
453       SSL_CTX *ctx = SSL_get_SSL_CTX(ssl);
454
455       g_tls_log_debug (tls, "Setting ALPN Callback on %p", ctx);
456       SSL_CTX_set_alpn_select_cb (ctx, _openssl_alpn_select_cb, tls);
457
458       return;
459     }
460
461   if (g_strv_length (advertised_protocols) > 0)
462     {
463       GByteArray *protocols = g_byte_array_new ();
464       int ret, i;
465
466       for (i = 0; advertised_protocols[i]; i++)
467         {
468           guint8 len = strlen (advertised_protocols[i]);
469           g_byte_array_append (protocols, &len, 1);
470           g_byte_array_append (protocols, (guint8 *)advertised_protocols[i], len);
471         }
472       ret = SSL_set_alpn_protos (ssl, protocols->data, protocols->len);
473       if (ret)
474         g_tls_log_debug (tls, "Error setting ALPN protocols: %d", ret);
475       else
476         {
477           gchar *logbuf = g_strndup ((const gchar *)protocols->data, protocols->len);
478
479           g_tls_log_debug (tls, "Setting ALPN protocols to %s", logbuf);
480           g_free (logbuf);
481         }
482       g_byte_array_unref (protocols);
483     }
484 }
485
486 static GTlsCertificateFlags
487 g_tls_connection_openssl_verify_chain (GTlsConnectionBase       *tls,
488                                        GTlsCertificate          *chain,
489                                        const gchar              *purpose,
490                                        GSocketConnectable       *identity,
491                                        GTlsInteraction          *interaction,
492                                        GTlsDatabaseVerifyFlags   flags,
493                                        GCancellable             *cancellable,
494                                        GError                  **error)
495 {
496   GTlsDatabase *database;
497   GTlsCertificateFlags errors = 0;
498   gboolean is_client = G_IS_TLS_CLIENT_CONNECTION (tls);
499
500   database = g_tls_connection_get_database (G_TLS_CONNECTION (tls));
501   if (database)
502     {
503       errors |= g_tls_database_verify_chain (database,
504                                              chain,
505                                              is_client ? G_TLS_DATABASE_PURPOSE_AUTHENTICATE_SERVER : G_TLS_DATABASE_PURPOSE_AUTHENTICATE_CLIENT,
506                                              identity,
507                                              g_tls_connection_get_interaction (G_TLS_CONNECTION (tls)),
508                                              G_TLS_DATABASE_VERIFY_NONE,
509                                              NULL,
510                                              error);
511     }
512   else
513     {
514       TIZEN_LOGE("SSL Handshake - Unknown CA");
515       errors |= G_TLS_CERTIFICATE_UNKNOWN_CA;
516       errors |= g_tls_certificate_verify (chain, identity, NULL);
517     }
518
519   return errors;
520 }
521
522 static GTlsProtocolVersion
523 glib_protocol_version_from_openssl (int protocol_version)
524 {
525   switch (protocol_version)
526     {
527     case SSL3_VERSION:
528       return G_TLS_PROTOCOL_VERSION_SSL_3_0;
529     case TLS1_VERSION:
530       return G_TLS_PROTOCOL_VERSION_TLS_1_0;
531     case TLS1_1_VERSION:
532       return G_TLS_PROTOCOL_VERSION_TLS_1_1;
533     case TLS1_2_VERSION:
534       return G_TLS_PROTOCOL_VERSION_TLS_1_2;
535     case TLS1_3_VERSION:
536       return G_TLS_PROTOCOL_VERSION_TLS_1_3;
537     case DTLS1_VERSION:
538       return G_TLS_PROTOCOL_VERSION_DTLS_1_0;
539     case DTLS1_2_VERSION:
540       return G_TLS_PROTOCOL_VERSION_DTLS_1_2;
541     default:
542       return G_TLS_PROTOCOL_VERSION_UNKNOWN;
543     }
544 }
545
546 static void
547 g_tls_connection_openssl_complete_handshake (GTlsConnectionBase   *tls,
548                                              gboolean              handshake_succeeded,
549                                              gchar               **negotiated_protocol,
550                                              GTlsProtocolVersion  *protocol_version,
551                                              gchar               **ciphersuite_name,
552                                              GError              **error)
553 {
554   SSL *ssl;
555   SSL_SESSION *session;
556   unsigned int len = 0;
557   const unsigned char *data = NULL;
558
559   if (!handshake_succeeded)
560     return;
561
562   TIZEN_LOGI("tls[%p]", tls);
563
564   ssl = g_tls_connection_openssl_get_ssl (G_TLS_CONNECTION_OPENSSL (tls));
565   session = SSL_get_session (ssl);
566
567   SSL_get0_alpn_selected (ssl, &data, &len);
568
569   g_tls_log_debug (tls, "negotiated ALPN protocols: [%d]%p", len, data);
570
571   if (data && len > 0)
572     {
573       g_assert (!*negotiated_protocol);
574       *negotiated_protocol = g_strndup ((gchar *)data, len);
575     }
576
577   *protocol_version = glib_protocol_version_from_openssl (SSL_SESSION_get_protocol_version (session));
578   *ciphersuite_name = g_strdup (SSL_get_cipher_name (ssl));
579 }
580
581 static int
582 perform_rehandshake (SSL      *ssl,
583                      gpointer  user_data)
584 {
585   GTlsConnectionBase *tls = user_data;
586   int ret = 1; /* always look on the bright side of life */
587
588 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
589   if (SSL_version(ssl) >= TLS1_3_VERSION)
590     ret = SSL_key_update (ssl, SSL_KEY_UPDATE_REQUESTED);
591   else if (SSL_get_secure_renegotiation_support (ssl) && !(SSL_get_options(ssl) & SSL_OP_NO_RENEGOTIATION))
592     /* remote and local peers both can rehandshake */
593     ret = SSL_renegotiate (ssl);
594   else
595     g_tls_log_debug (tls, "Secure renegotiation is not supported");
596 #else
597   ret = SSL_renegotiate (ssl);
598 #endif
599
600   return ret;
601 }
602
603 static GTlsConnectionBaseStatus
604 g_tls_connection_openssl_handshake_thread_request_rehandshake (GTlsConnectionBase  *tls,
605                                                                gint64               timeout,
606                                                                GCancellable        *cancellable,
607                                                                GError             **error)
608 {
609   /* On a client-side connection, SSL_renegotiate() itself will start
610    * a rehandshake, so we only need to do something special here for
611    * server-side connections.
612    */
613   if (!G_IS_TLS_SERVER_CONNECTION (tls))
614     return G_TLS_CONNECTION_BASE_OK;
615
616   return perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls), G_IO_IN | G_IO_OUT,
617                              perform_rehandshake, tls, timeout, cancellable,
618                              NULL, error, _("Error performing TLS handshake"));
619 }
620
621 static GTlsCertificate *
622 g_tls_connection_openssl_retrieve_peer_certificate (GTlsConnectionBase *tls)
623 {
624   X509 *peer;
625   STACK_OF (X509) *certs;
626   GTlsCertificateOpenssl *chain;
627   SSL *ssl;
628
629   ssl = g_tls_connection_openssl_get_ssl (G_TLS_CONNECTION_OPENSSL (tls));
630
631   peer = SSL_get_peer_certificate (ssl);
632   if (!peer)
633     return NULL;
634
635   certs = SSL_get_peer_cert_chain (ssl);
636   if (!certs)
637     {
638       X509_free (peer);
639       return NULL;
640     }
641
642   chain = g_tls_certificate_openssl_build_chain (peer, certs);
643   X509_free (peer);
644   if (!chain)
645     return NULL;
646
647   return G_TLS_CERTIFICATE (chain);
648 }
649
650 static gboolean
651 openssl_get_binding_tls_unique (GTlsConnectionOpenssl  *tls,
652                                 GByteArray             *data,
653                                 GError                **error)
654 {
655   SSL *ssl = g_tls_connection_openssl_get_ssl (tls);
656   gboolean is_client = G_IS_TLS_CLIENT_CONNECTION (tls);
657   gboolean resumed = SSL_session_reused (ssl);
658   size_t len = 64;
659
660 #if OPENSSL_VERSION_NUMBER >= 0x10101000L
661   if (SSL_version (ssl) >= TLS1_3_VERSION)
662     {
663       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_GENERAL_ERROR,
664                    _("The request is invalid."));
665       return FALSE;
666     }
667 #endif
668
669   /* This is a drill */
670   if (!data)
671     return TRUE;
672
673   do {
674     g_byte_array_set_size (data, len);
675     if ((resumed && is_client) || (!resumed && !is_client))
676       len = SSL_get_peer_finished (ssl, data->data, data->len);
677     else
678       len = SSL_get_finished (ssl, data->data, data->len);
679   } while (len > data->len);
680
681   if (len > 0)
682     {
683       g_byte_array_set_size (data, len);
684       return TRUE;
685     }
686   g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_AVAILABLE,
687                _("Channel binding data tls-unique is not available"));
688   return FALSE;
689 }
690
691 static gboolean
692 openssl_get_binding_tls_server_end_point (GTlsConnectionOpenssl  *tls,
693                                           GByteArray             *data,
694                                           GError                **error)
695 {
696   SSL *ssl = g_tls_connection_openssl_get_ssl (tls);
697   gboolean is_client = G_IS_TLS_CLIENT_CONNECTION (tls);
698   int algo_nid;
699   const EVP_MD *algo = NULL;
700   X509 *crt;
701
702   if (is_client)
703     crt = SSL_get_peer_certificate (ssl);
704   else
705     crt = SSL_get_certificate (ssl);
706
707   if (!crt)
708     {
709       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_AVAILABLE,
710                    _("X.509 Certificate is not available on the connection"));
711       return FALSE;
712     }
713
714   if (!OBJ_find_sigid_algs (X509_get_signature_nid (crt), &algo_nid, NULL))
715     {
716       X509_free (crt);
717       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_GENERAL_ERROR,
718                    _("Unable to obtain certificate signature algorithm"));
719       return FALSE;
720     }
721
722   /* This is a drill */
723   if (!data)
724     {
725       if (is_client)
726         X509_free (crt);
727       return TRUE;
728     }
729
730   switch (algo_nid)
731     {
732     case NID_md5:
733     case NID_sha1:
734       algo_nid = NID_sha256;
735       break;
736     case NID_md5_sha1:
737       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_SUPPORTED,
738                    _("Current X.509 certificate uses unknown or unsupported signature algorithm"));
739       if (is_client)
740         X509_free (crt);
741       return FALSE;
742     }
743
744   g_byte_array_set_size (data, EVP_MAX_MD_SIZE);
745   algo = EVP_get_digestbynid (algo_nid);
746   if (X509_digest (crt, algo, data->data, &(data->len)))
747     {
748       if (is_client)
749         X509_free (crt);
750       return TRUE;
751     }
752
753   if (is_client)
754     X509_free (crt);
755   g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_GENERAL_ERROR,
756                _("Failed to generate X.509 certificate digest"));
757   return FALSE;
758 }
759
760 #define RFC5705_LABEL_DATA "EXPORTER-Channel-Binding"
761 #define RFC5705_LABEL_LEN 24
762 static gboolean
763 openssl_get_binding_tls_exporter (GTlsConnectionOpenssl  *tls,
764                                   GByteArray             *data,
765                                   GError                **error)
766 {
767   SSL *ssl = g_tls_connection_openssl_get_ssl (tls);
768   size_t  ctx_len = 0;
769   guint8 *context = (guint8 *)"";
770   int ret;
771
772   if (!data)
773     return TRUE;
774
775   g_byte_array_set_size (data, 32);
776   ret = SSL_export_keying_material (ssl,
777                                     data->data, data->len,
778                                     RFC5705_LABEL_DATA, RFC5705_LABEL_LEN,
779                                     context, ctx_len,
780                                     1 /* use context */);
781
782   if (ret > 0)
783     return TRUE;
784
785   if (ret < 0)
786     g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_SUPPORTED,
787                  _("TLS Connection does not support TLS-Exporter feature"));
788   else
789     g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_GENERAL_ERROR,
790                  _("Unexpected error while exporting keying data"));
791
792   return FALSE;
793 }
794
795 static gboolean
796 g_tls_connection_openssl_get_channel_binding_data (GTlsConnectionBase      *tls,
797                                                    GTlsChannelBindingType   type,
798                                                    GByteArray              *data,
799                                                    GError                 **error)
800 {
801   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
802
803   /* XXX: remove the cast once public enum supports exporter */
804   switch ((int)type)
805     {
806     case G_TLS_CHANNEL_BINDING_TLS_UNIQUE:
807       return openssl_get_binding_tls_unique (openssl, data, error);
808       /* fall through */
809     case G_TLS_CHANNEL_BINDING_TLS_SERVER_END_POINT:
810       return openssl_get_binding_tls_server_end_point (openssl, data, error);
811       /* fall through */
812     case 100500:
813       return openssl_get_binding_tls_exporter (openssl, data, error);
814       /* fall through */
815     default:
816       /* Anyone to implement tls-unique-for-telnet? */
817       g_set_error (error, G_TLS_CHANNEL_BINDING_ERROR, G_TLS_CHANNEL_BINDING_ERROR_NOT_IMPLEMENTED,
818                    _("Requested channel binding type is not implemented"));
819     }
820   return FALSE;
821 }
822
823 static GTlsConnectionBaseStatus
824 g_tls_connection_openssl_handshake_thread_handshake (GTlsConnectionBase  *tls,
825                                                      gint64               timeout,
826                                                      GCancellable        *cancellable,
827                                                      GError             **error)
828 {
829   GTlsConnectionBaseStatus status;
830   int ret;
831
832   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls),
833                                G_IO_IN | G_IO_OUT,
834                                (GTlsOpensslIOFunc) SSL_do_handshake,
835                                NULL, timeout, cancellable, &ret, error,
836                                _("Error reading data from TLS socket"));
837
838   if (ret > 0)
839     {
840       if (!g_tls_connection_base_handshake_thread_verify_certificate (tls))
841         {
842           g_set_error_literal (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE,
843                                _("Unacceptable TLS certificate"));
844           return G_TLS_CONNECTION_BASE_ERROR;
845         }
846     }
847
848   return status;
849 }
850
851 static void
852 g_tls_connection_openssl_push_io (GTlsConnectionBase *tls,
853                                   GIOCondition        direction,
854                                   gint64              timeout,
855                                   GCancellable       *cancellable)
856 {
857   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
858   GTlsConnectionOpensslPrivate *priv;
859   GError **error;
860
861   priv = g_tls_connection_openssl_get_instance_private (openssl);
862
863   G_TLS_CONNECTION_BASE_CLASS (g_tls_connection_openssl_parent_class)->push_io (tls, direction,
864                                                                                 timeout, cancellable);
865
866   if (direction & G_IO_IN)
867     {
868       error = g_tls_connection_base_get_read_error (tls);
869       g_tls_bio_set_read_cancellable (priv->bio, cancellable);
870       g_clear_error (error);
871       g_tls_bio_set_read_error (priv->bio, error);
872     }
873
874   if (direction & G_IO_OUT)
875     {
876       error = g_tls_connection_base_get_write_error (tls);
877       g_tls_bio_set_write_cancellable (priv->bio, cancellable);
878       g_clear_error (error);
879       g_tls_bio_set_write_error (priv->bio, error);
880     }
881
882   g_mutex_lock (&priv->ssl_mutex);
883 }
884
885 static GTlsConnectionBaseStatus
886 g_tls_connection_openssl_pop_io (GTlsConnectionBase  *tls,
887                                  GIOCondition         direction,
888                                  gboolean             success,
889                                  GError             **error)
890 {
891   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
892   GTlsConnectionOpensslPrivate *priv;
893
894   priv = g_tls_connection_openssl_get_instance_private (openssl);
895
896   g_mutex_unlock (&priv->ssl_mutex);
897
898   if (direction & G_IO_IN)
899     g_tls_bio_set_read_cancellable (priv->bio, NULL);
900
901   if (direction & G_IO_OUT)
902     g_tls_bio_set_write_cancellable (priv->bio, NULL);
903
904   return G_TLS_CONNECTION_BASE_CLASS (g_tls_connection_openssl_parent_class)->pop_io (tls, direction,
905                                                                                       success, error);
906 }
907
908 static int
909 perform_read (SSL      *ssl,
910               gpointer  user_data)
911 {
912   ReadRequest *req = user_data;
913
914   return SSL_read (ssl, req->buffer, req->count);
915 }
916
917 static GTlsConnectionBaseStatus
918 g_tls_connection_openssl_read (GTlsConnectionBase    *tls,
919                                void                  *buffer,
920                                gsize                  count,
921                                gint64                 timeout,
922                                gssize                *nread,
923                                GCancellable          *cancellable,
924                                GError               **error)
925 {
926   GTlsConnectionBaseStatus status;
927   ReadRequest req = { buffer, count };
928   int ret;
929
930   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls), G_IO_IN,
931                                perform_read, &req, timeout, cancellable, &ret,
932                                error, _("Error reading data from TLS socket"));
933
934   *nread = MAX (ret, 0);
935   return status;
936 }
937
938 static GTlsConnectionBaseStatus
939 g_tls_connection_openssl_read_message (GTlsConnectionBase  *tls,
940                                        GInputVector        *vectors,
941                                        guint                num_vectors,
942                                        gint64               timeout,
943                                        gssize              *nread,
944                                        GCancellable        *cancellable,
945                                        GError             **error)
946 {
947   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
948   GTlsConnectionOpensslPrivate *priv;
949   GTlsConnectionBaseStatus status;
950   gssize bytes_read;
951   gsize bytes_copied, bytes_remaining;
952   guint i;
953
954   *nread = 0;
955
956   priv = g_tls_connection_openssl_get_instance_private (openssl);
957
958   if (!priv->dtls_rx)
959     priv->dtls_rx = g_malloc (DTLS_MESSAGE_MAX_SIZE);
960
961   status = g_tls_connection_openssl_read (tls, priv->dtls_rx,
962                                           DTLS_MESSAGE_MAX_SIZE, timeout,
963                                           &bytes_read, cancellable, error);
964   if (status != G_TLS_CONNECTION_BASE_OK)
965     return status;
966
967   bytes_copied = 0;
968   bytes_remaining = bytes_read;
969   for (i = 0; i < num_vectors && bytes_remaining > 0; i++)
970     {
971       GInputVector *vector = &vectors[i];
972       gsize n;
973
974       n = MIN (bytes_remaining, vector->size);
975
976       memcpy (vector->buffer, priv->dtls_rx + bytes_copied, n);
977
978       bytes_copied += n;
979       bytes_remaining -= n;
980     }
981
982   *nread = bytes_copied;
983
984   return status;
985 }
986
987 static int
988 perform_write (SSL      *ssl,
989                gpointer  user_data)
990 {
991   WriteRequest *req = user_data;
992
993   return SSL_write (ssl, req->buffer, req->count);
994 }
995
996 static GTlsConnectionBaseStatus
997 g_tls_connection_openssl_write (GTlsConnectionBase    *tls,
998                                 const void            *buffer,
999                                 gsize                  count,
1000                                 gint64                 timeout,
1001                                 gssize                *nwrote,
1002                                 GCancellable          *cancellable,
1003                                 GError               **error)
1004 {
1005   GTlsConnectionBaseStatus status;
1006   WriteRequest req = { buffer, count };
1007   int ret;
1008
1009   status = perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls), G_IO_OUT,
1010                                perform_write, &req, timeout, cancellable, &ret,
1011                                error, _("Error writing data to TLS socket"));
1012
1013   *nwrote = MAX (ret, 0);
1014   return status;
1015 }
1016
1017 static GTlsConnectionBaseStatus
1018 g_tls_connection_openssl_write_message (GTlsConnectionBase  *tls,
1019                                         GOutputVector       *vectors,
1020                                         guint                num_vectors,
1021                                         gint64               timeout,
1022                                         gssize              *nwrote,
1023                                         GCancellable        *cancellable,
1024                                         GError             **error)
1025 {
1026   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
1027   GTlsConnectionOpensslPrivate *priv;
1028   gsize bytes_copied, bytes_available;
1029   guint i;
1030
1031   priv = g_tls_connection_openssl_get_instance_private (openssl);
1032
1033   if (!priv->dtls_tx)
1034     priv->dtls_tx = g_malloc (DTLS_MESSAGE_MAX_SIZE);
1035
1036   bytes_copied = 0;
1037   bytes_available = DTLS_MESSAGE_MAX_SIZE;
1038   for (i = 0; i < num_vectors && bytes_available > 0; i++)
1039     {
1040       GOutputVector *vector = &vectors[i];
1041       gsize n;
1042
1043       n = MIN (vector->size, bytes_available);
1044
1045       memcpy (priv->dtls_tx + bytes_copied, vector->buffer, n);
1046
1047       bytes_copied += n;
1048       bytes_available -= n;
1049     }
1050
1051   return g_tls_connection_openssl_write (tls, priv->dtls_tx, bytes_copied,
1052                                          timeout, nwrote, cancellable, error);
1053 }
1054
1055 static GTlsConnectionBaseStatus
1056 g_tls_connection_openssl_close (GTlsConnectionBase  *tls,
1057                                 gint64               timeout,
1058                                 GCancellable        *cancellable,
1059                                 GError             **error)
1060 {
1061   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (tls);
1062   GTlsConnectionOpensslPrivate *priv;
1063
1064   priv = g_tls_connection_openssl_get_instance_private (openssl);
1065
1066   priv->shutting_down = TRUE;
1067
1068  TIZEN_LOGI("tls[%p]", tls);
1069
1070   return perform_openssl_io (G_TLS_CONNECTION_OPENSSL (tls),
1071                              G_IO_IN | G_IO_OUT,
1072                              (GTlsOpensslIOFunc) SSL_shutdown,
1073                              NULL, timeout, cancellable, NULL, error,
1074                              _("Error performing TLS close"));
1075 }
1076
1077 static void
1078 g_tls_connection_openssl_class_init (GTlsConnectionOpensslClass *klass)
1079 {
1080   GObjectClass *object_class = G_OBJECT_CLASS (klass);
1081   GTlsConnectionBaseClass *base_class = G_TLS_CONNECTION_BASE_CLASS (klass);
1082
1083   object_class->finalize                                 = g_tls_connection_openssl_finalize;
1084
1085   base_class->prepare_handshake                          = g_tls_connection_openssl_prepare_handshake;
1086   base_class->verify_chain                               = g_tls_connection_openssl_verify_chain;
1087   base_class->complete_handshake                         = g_tls_connection_openssl_complete_handshake;
1088   base_class->handshake_thread_safe_renegotiation_status = g_tls_connection_openssl_handshake_thread_safe_renegotiation_status;
1089   base_class->handshake_thread_request_rehandshake       = g_tls_connection_openssl_handshake_thread_request_rehandshake;
1090   base_class->handshake_thread_handshake                 = g_tls_connection_openssl_handshake_thread_handshake;
1091   base_class->retrieve_peer_certificate                  = g_tls_connection_openssl_retrieve_peer_certificate;
1092   base_class->get_channel_binding_data                   = g_tls_connection_openssl_get_channel_binding_data;
1093   base_class->push_io                                    = g_tls_connection_openssl_push_io;
1094   base_class->pop_io                                     = g_tls_connection_openssl_pop_io;
1095   base_class->read_fn                                    = g_tls_connection_openssl_read;
1096   base_class->read_message_fn                            = g_tls_connection_openssl_read_message;
1097   base_class->write_fn                                   = g_tls_connection_openssl_write;
1098   base_class->write_message_fn                           = g_tls_connection_openssl_write_message;
1099   base_class->close_fn                                   = g_tls_connection_openssl_close;
1100 }
1101
1102 static int data_index = -1;
1103
1104 static gboolean
1105 g_tls_connection_openssl_initable_init (GInitable     *initable,
1106                                         GCancellable  *cancellable,
1107                                         GError       **error)
1108 {
1109   GTlsConnectionOpenssl *openssl = G_TLS_CONNECTION_OPENSSL (initable);
1110   GTlsConnectionOpensslPrivate *priv;
1111   GTlsConnectionBase *tls = G_TLS_CONNECTION_BASE (initable);
1112   GIOStream *base_io_stream;
1113   GDatagramBased *base_socket;
1114   SSL *ssl;
1115
1116   g_object_get (tls,
1117                 "base-io-stream", &base_io_stream,
1118                 "base-socket", &base_socket,
1119                 NULL);
1120
1121   /* Ensure we are in TLS mode or DTLS mode. */
1122   g_return_val_if_fail (!!base_io_stream != !!base_socket, FALSE);
1123
1124   priv = g_tls_connection_openssl_get_instance_private (openssl);
1125
1126   ssl = g_tls_connection_openssl_get_ssl (openssl);
1127   g_assert (ssl);
1128
1129   if (data_index == -1) {
1130       data_index = SSL_get_ex_new_index (0, (void *)"gtlsconnection", NULL, NULL, NULL);
1131   }
1132   SSL_set_ex_data (ssl, data_index, openssl);
1133
1134   if (base_io_stream)
1135     priv->bio = g_tls_bio_new_from_iostream (base_io_stream);
1136   else
1137     priv->bio = g_tls_bio_new_from_datagram_based (base_socket);
1138
1139   SSL_set_bio (ssl, priv->bio, priv->bio);
1140
1141   g_clear_object (&base_io_stream);
1142   g_clear_object (&base_socket);
1143
1144   return TRUE;
1145 }
1146
1147 static void
1148 g_tls_connection_openssl_initable_iface_init (GInitableIface *iface)
1149 {
1150   iface->init = g_tls_connection_openssl_initable_init;
1151 }
1152
1153 static void
1154 g_tls_connection_openssl_init (GTlsConnectionOpenssl *openssl)
1155 {
1156   GTlsConnectionOpensslPrivate *priv;
1157
1158   priv = g_tls_connection_openssl_get_instance_private (openssl);
1159
1160   g_mutex_init (&priv->ssl_mutex);
1161 }
1162
1163 SSL *
1164 g_tls_connection_openssl_get_ssl (GTlsConnectionOpenssl *openssl)
1165 {
1166   g_return_val_if_fail (G_IS_TLS_CONNECTION_OPENSSL (openssl), NULL);
1167
1168   return G_TLS_CONNECTION_OPENSSL_GET_CLASS (openssl)->get_ssl (openssl);
1169 }
1170
1171 GTlsConnectionOpenssl *
1172 g_tls_connection_openssl_get_connection_from_ssl (SSL *ssl)
1173 {
1174   g_return_val_if_fail (ssl, NULL);
1175
1176   return SSL_get_ex_data (ssl, data_index);
1177 }