Imported Upstream version 2.72.alpha
[platform/upstream/glib-networking.git] / tls / tests / connection.c
1 /* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /*
3  * GIO TLS tests
4  *
5  * Copyright 2011 Collabora, Ltd.
6  *
7  * This library 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 library 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
18  * Public License along with this library; if not, see
19  * <http://www.gnu.org/licenses/>.
20  *
21  * In addition, when the library is used with OpenSSL, a special
22  * exception applies. Refer to the LICENSE_EXCEPTION file for details.
23  *
24  * Author: Stef Walter <stefw@collabora.co.uk>
25  */
26
27 #include "config.h"
28
29 #include "mock-interaction.h"
30
31 #include <gio/gio.h>
32
33 #include <sys/types.h>
34 #include <string.h>
35
36 #ifdef BACKEND_IS_GNUTLS
37 #include <gnutls/gnutls.h>
38 #include <gnutls/pkcs11.h>
39 #else
40 #include "openssl-include.h"
41 #endif
42
43 static const gchar *
44 tls_test_file_path (const char *name)
45 {
46   const gchar *const_path;
47   gchar *path;
48
49   path = g_test_build_filename (G_TEST_DIST, "files", name, NULL);
50   if (!g_path_is_absolute (path))
51     {
52       gchar *cwd, *abs;
53
54       cwd = g_get_current_dir ();
55       abs = g_build_filename (cwd, path, NULL);
56       g_free (cwd);
57       g_free (path);
58       path = abs;
59     }
60
61   const_path = g_intern_string (path);
62   g_free (path);
63   return const_path;
64 }
65
66 #define TEST_DATA "You win again, gravity!\n"
67 #define TEST_DATA_LENGTH 24
68
69 typedef enum {
70   WRITE_THEN_CLOSE,
71   WRITE_THEN_WAIT,
72   HANDSHAKE_ONLY
73 } ServerConnectionReceivedStrategy;
74
75 typedef struct {
76   GMainContext *context;
77   GMainLoop *loop;
78   GSocketService *service;
79   GTlsDatabase *database;
80   GIOStream *server_connection;
81   GIOStream *client_connection;
82   GSocketConnectable *identity;
83   GSocketAddress *address;
84   GTlsAuthenticationMode auth_mode;
85   gboolean rehandshake;
86   GTlsCertificateFlags accept_flags;
87   GError *read_error;
88   GError *server_error;
89   gboolean ignore_client_close_error;
90   ServerConnectionReceivedStrategy connection_received_strategy;
91   gboolean server_running;
92   gboolean server_ever_handshaked;
93   GTlsCertificate *server_certificate;
94   const gchar * const *server_protocols;
95   gulong incoming_connection_delay;
96
97   char buf[128];
98   gssize nread, nwrote;
99 } TestConnection;
100
101 static void
102 setup_connection (TestConnection *test, gconstpointer data)
103 {
104   test->context = g_main_context_default ();
105   test->loop = g_main_loop_new (test->context, FALSE);
106   test->auth_mode = G_TLS_AUTHENTICATION_NONE;
107 }
108
109 /* Waits about 10 seconds for @var to be NULL/FALSE */
110 #define WAIT_UNTIL_UNSET(var)                                \
111   if (var)                                                   \
112     {                                                        \
113       int i;                                                 \
114                                                              \
115       for (i = 0; i < 13 && (var); i++)                      \
116         {                                                    \
117           g_usleep (1000 * (1 << i));                        \
118           g_main_context_iteration (test->context, FALSE);   \
119         }                                                    \
120                                                              \
121       g_assert_true (!(var));                                \
122     }
123
124 /* Waits about 10 seconds for @var's ref_count to drop to 1 */
125 #define WAIT_UNTIL_UNREFFED(var)                                \
126   if (var)                                                      \
127     {                                                           \
128       int i;                                                    \
129                                                                 \
130       for (i = 0; i < 13 && G_OBJECT (var)->ref_count > 1; i++) \
131         {                                                       \
132           g_usleep (1000 * (1 << i));                           \
133           g_main_context_iteration (NULL, FALSE);               \
134         }                                                       \
135                                                                 \
136       g_assert_cmpuint (G_OBJECT (var)->ref_count, ==, 1);      \
137     }
138
139 static void
140 wait_until_server_finished (TestConnection *test)
141 {
142     WAIT_UNTIL_UNSET (test->server_running);
143 }
144
145 static void
146 teardown_connection (TestConnection *test, gconstpointer data)
147 {
148   if (test->service)
149     {
150       g_socket_service_stop (test->service);
151       /* The outstanding accept_async will hold a ref on test->service,
152        * which we want to wait for it to release if we're valgrinding.
153        */
154       g_socket_listener_close (G_SOCKET_LISTENER (test->service));
155       WAIT_UNTIL_UNREFFED (test->service);
156       g_object_unref (test->service);
157       test->service = NULL;
158     }
159
160   if (test->server_connection)
161     {
162       WAIT_UNTIL_UNSET (test->server_running);
163
164       WAIT_UNTIL_UNREFFED (test->server_connection);
165       g_object_unref (test->server_connection);
166       test->server_connection = NULL;
167     }
168
169   if (test->client_connection)
170     {
171       WAIT_UNTIL_UNREFFED (test->client_connection);
172       g_object_unref (test->client_connection);
173       test->client_connection = NULL;
174     }
175
176   if (test->database)
177     {
178       WAIT_UNTIL_UNREFFED (test->database);
179       g_object_unref (test->database);
180       test->database = NULL;
181     }
182
183   g_clear_object (&test->address);
184   g_clear_object (&test->identity);
185   g_clear_object (&test->server_certificate);
186
187   g_main_loop_unref (test->loop);
188
189   g_clear_error (&test->read_error);
190   g_clear_error (&test->server_error);
191 }
192
193 static void
194 start_server (TestConnection *test)
195 {
196   GInetAddress *inet;
197   GSocketAddress *addr;
198   GInetSocketAddress *iaddr;
199   GError *error = NULL;
200
201   inet = g_inet_address_new_from_string ("127.0.0.1");
202   addr = g_inet_socket_address_new (inet, 0);
203   g_object_unref (inet);
204
205   g_socket_listener_add_address (G_SOCKET_LISTENER (test->service), addr,
206                                  G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_TCP,
207                                  NULL, &test->address, &error);
208   g_assert_no_error (error);
209
210   g_object_unref (addr);
211
212   /* The hostname in test->identity matches the server certificate. */
213   iaddr = G_INET_SOCKET_ADDRESS (test->address);
214   test->identity = g_network_address_new ("server.example.com",
215                                           g_inet_socket_address_get_port (iaddr));
216
217   test->server_running = TRUE;
218 }
219
220 static gboolean
221 on_accept_certificate (GTlsConnection       *conn,
222                        GTlsCertificate      *cert,
223                        GTlsCertificateFlags  errors,
224                        gpointer              user_data)
225 {
226   TestConnection *test = user_data;
227
228   g_assert_true (G_IS_TLS_CERTIFICATE (cert));
229
230   return errors == test->accept_flags;
231 }
232
233 static void on_output_write_finish (GObject        *object,
234                                     GAsyncResult   *res,
235                                     gpointer        user_data);
236
237 static void
238 on_rehandshake_finish (GObject        *object,
239                        GAsyncResult   *res,
240                        gpointer        user_data)
241 {
242   TestConnection *test = user_data;
243   GError *error = NULL;
244   GOutputStream *stream;
245
246   g_tls_connection_handshake_finish (G_TLS_CONNECTION (object), res, &error);
247   g_assert_no_error (error);
248
249   stream = g_io_stream_get_output_stream (test->server_connection);
250   g_output_stream_write_async (stream, TEST_DATA + TEST_DATA_LENGTH / 2,
251                                TEST_DATA_LENGTH / 2,
252                                G_PRIORITY_DEFAULT, NULL,
253                                on_output_write_finish, test);
254 }
255
256 static void
257 on_server_close_finish (GObject        *object,
258                         GAsyncResult   *res,
259                         gpointer        user_data)
260 {
261   TestConnection *test = user_data;
262   GError *error = NULL;
263
264   g_io_stream_close_finish (G_IO_STREAM (object), res, &error);
265   // FIXME: https://gitlab.gnome.org/GNOME/glib-networking/issues/105
266   // g_assert_no_error (error);
267
268   test->server_running = FALSE;
269 }
270
271 static void
272 close_server_connection (TestConnection *test)
273 {
274   g_io_stream_close_async (test->server_connection, G_PRIORITY_DEFAULT, NULL,
275                            on_server_close_finish, test);
276 }
277
278 static void
279 on_output_write_finish (GObject        *object,
280                         GAsyncResult   *res,
281                         gpointer        user_data)
282 {
283   TestConnection *test = user_data;
284
285   g_assert_no_error (test->server_error);
286   g_output_stream_write_finish (G_OUTPUT_STREAM (object), res, &test->server_error);
287
288   if (!test->server_error && test->rehandshake)
289     {
290       test->rehandshake = FALSE;
291       g_tls_connection_handshake_async (G_TLS_CONNECTION (test->server_connection),
292                                         G_PRIORITY_DEFAULT, NULL,
293                                         on_rehandshake_finish, test);
294       return;
295     }
296
297   if (test->connection_received_strategy == WRITE_THEN_CLOSE)
298     close_server_connection (test);
299 }
300
301 static void
302 on_server_handshake_finish (GObject      *object,
303                             GAsyncResult *res,
304                             gpointer      user_data)
305 {
306   TestConnection *test = user_data;
307   g_tls_connection_handshake_finish (G_TLS_CONNECTION (object), res, &test->server_error);
308   g_assert_no_error (test->server_error);
309   test->server_ever_handshaked = TRUE;
310 }
311
312 static gboolean
313 on_incoming_connection (GSocketService     *service,
314                         GSocketConnection  *connection,
315                         GObject            *source_object,
316                         gpointer            user_data)
317 {
318   TestConnection *test = user_data;
319   GOutputStream *stream;
320   GTlsCertificate *cert;
321   GError *error = NULL;
322
323   if (test->incoming_connection_delay != 0)
324     g_usleep (test->incoming_connection_delay);
325
326   g_assert_null (test->server_connection);
327   test->server_connection = g_tls_server_connection_new (G_IO_STREAM (connection),
328                                                          test->server_certificate, &error);
329   g_assert_no_error (error);
330
331   if (!test->server_certificate)
332     {
333       cert = g_tls_certificate_new_from_file (tls_test_file_path ("server-and-key.pem"), &error);
334       g_assert_no_error (error);
335       g_tls_connection_set_certificate (G_TLS_CONNECTION (test->server_connection), cert);
336       g_object_unref (cert);
337     }
338
339   g_object_set (test->server_connection, "authentication-mode", test->auth_mode, NULL);
340   g_signal_connect (test->server_connection, "accept-certificate",
341                     G_CALLBACK (on_accept_certificate), test);
342
343   if (test->database)
344     g_tls_connection_set_database (G_TLS_CONNECTION (test->server_connection), test->database);
345
346   if (test->server_protocols)
347     {
348       g_tls_connection_set_advertised_protocols (G_TLS_CONNECTION (test->server_connection),
349                                                  test->server_protocols);
350     }
351
352   stream = g_io_stream_get_output_stream (test->server_connection);
353
354   if (test->connection_received_strategy == WRITE_THEN_CLOSE ||
355       test->connection_received_strategy == WRITE_THEN_WAIT)
356     {
357       g_output_stream_write_async (stream, TEST_DATA,
358                                    test->rehandshake ? TEST_DATA_LENGTH / 2 : TEST_DATA_LENGTH,
359                                    G_PRIORITY_DEFAULT, NULL,
360                                    on_output_write_finish, test);
361     }
362   else
363     {
364       g_tls_connection_handshake_async (G_TLS_CONNECTION (test->server_connection),
365                                         G_PRIORITY_DEFAULT, NULL,
366                                         on_server_handshake_finish, test);
367     }
368
369   return FALSE;
370 }
371
372 static void
373 start_async_server_service (TestConnection                   *test,
374                             GTlsAuthenticationMode            auth_mode,
375                             ServerConnectionReceivedStrategy  connection_received_strategy)
376 {
377   test->service = g_socket_service_new ();
378   start_server (test);
379
380   test->auth_mode = auth_mode;
381   g_signal_connect (test->service, "incoming", G_CALLBACK (on_incoming_connection), test);
382
383   test->connection_received_strategy = connection_received_strategy;
384 }
385
386 static GIOStream *
387 start_async_server_and_connect_to_it (TestConnection         *test,
388                                       GTlsAuthenticationMode  auth_mode)
389 {
390   GSocketClient *client;
391   GError *error = NULL;
392   GSocketConnection *connection;
393
394   start_async_server_service (test, auth_mode, WRITE_THEN_CLOSE);
395
396   client = g_socket_client_new ();
397   connection = g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
398                                         NULL, &error);
399   g_assert_no_error (error);
400   g_object_unref (client);
401
402   return G_IO_STREAM (connection);
403 }
404
405 static void
406 run_echo_server (GThreadedSocketService *service,
407                  GSocketConnection      *connection,
408                  GObject                *source_object,
409                  gpointer                user_data)
410 {
411   TestConnection *test = user_data;
412   GTlsConnection *tlsconn;
413   GTlsCertificate *cert;
414   GError *error = NULL;
415   GInputStream *istream;
416   GOutputStream *ostream;
417   gssize nread, nwrote, total;
418   gchar buf[128];
419
420   if (test->server_certificate)
421     {
422       cert = g_object_ref (test->server_certificate);
423     }
424   else
425     {
426       cert = g_tls_certificate_new_from_file (tls_test_file_path ("server-and-key.pem"), &error);
427       g_assert_no_error (error);
428     }
429
430   test->server_connection = g_tls_server_connection_new (G_IO_STREAM (connection),
431                                                          cert, &error);
432   g_assert_no_error (error);
433   g_object_unref (cert);
434
435   tlsconn = G_TLS_CONNECTION (test->server_connection);
436   g_tls_connection_handshake (tlsconn, NULL, &error);
437   g_assert_no_error (error);
438
439   istream = g_io_stream_get_input_stream (test->server_connection);
440   ostream = g_io_stream_get_output_stream (test->server_connection);
441
442   while (TRUE)
443     {
444       nread = g_input_stream_read (istream, buf, sizeof (buf), NULL, &error);
445       g_assert_no_error (error);
446       g_assert_cmpint (nread, >=, 0);
447
448       if (nread == 0)
449         break;
450
451       for (total = 0; total < nread; total += nwrote)
452         {
453           nwrote = g_output_stream_write (ostream, buf + total, nread - total, NULL, &error);
454           g_assert_no_error (error);
455         }
456
457       if (test->rehandshake)
458         {
459           test->rehandshake = FALSE;
460           g_tls_connection_handshake (tlsconn, NULL, &error);
461           g_assert_no_error (error);
462         }
463     }
464
465   g_io_stream_close (test->server_connection, NULL, &error);
466   g_assert_no_error (error);
467   test->server_running = FALSE;
468 }
469
470 static void
471 start_echo_server_service (TestConnection *test)
472 {
473   test->service = g_threaded_socket_service_new (5);
474   start_server (test);
475
476   g_signal_connect (test->service, "run", G_CALLBACK (run_echo_server), test);
477 }
478
479 static GIOStream *
480 start_echo_server_and_connect_to_it (TestConnection *test)
481 {
482   GSocketClient *client;
483   GError *error = NULL;
484   GSocketConnection *connection;
485
486   start_echo_server_service (test);
487
488   client = g_socket_client_new ();
489   connection = g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
490                                         NULL, &error);
491   g_assert_no_error (error);
492   g_object_unref (client);
493
494   return G_IO_STREAM (connection);
495 }
496
497 static void
498 on_client_connection_close_finish (GObject        *object,
499                                    GAsyncResult   *res,
500                                    gpointer        user_data)
501 {
502   TestConnection *test = user_data;
503   GError *error = NULL;
504
505   g_io_stream_close_finish (G_IO_STREAM (object), res, &error);
506
507   /* FIXME: When running test_client_auth_failure(), GnuTLS throws a
508    * G_TLS_CERTIFICATE_REQUIRED error here for TLS 1.3, but no error for TLS
509    * 1.2. What's up with this difference? Can we have consistent errors?
510    */
511   if (!test->ignore_client_close_error)
512     g_assert_no_error (error);
513
514   g_main_loop_quit (test->loop);
515 }
516
517 static void
518 on_input_read_finish (GObject        *object,
519                       GAsyncResult   *res,
520                       gpointer        user_data)
521 {
522   TestConnection *test = user_data;
523   gchar *line, *check;
524
525   line = g_data_input_stream_read_line_finish (G_DATA_INPUT_STREAM (object), res,
526                                                NULL, &test->read_error);
527   if (!test->read_error)
528     {
529       g_assert_nonnull (line);
530
531       check = g_strdup (TEST_DATA);
532       g_strstrip (check);
533       g_assert_cmpstr (line, ==, check);
534       g_free (check);
535       g_free (line);
536     }
537
538   g_io_stream_close_async (test->client_connection, G_PRIORITY_DEFAULT,
539                            NULL, on_client_connection_close_finish, test);
540 }
541
542 static void
543 read_test_data_async (TestConnection *test)
544 {
545   GDataInputStream *stream;
546
547   stream = g_data_input_stream_new (g_io_stream_get_input_stream (test->client_connection));
548   g_assert_nonnull (stream);
549
550   g_data_input_stream_read_line_async (stream, G_PRIORITY_DEFAULT, NULL,
551                                        on_input_read_finish, test);
552   g_object_unref (stream);
553 }
554
555 static void
556 test_basic_connection (TestConnection *test,
557                        gconstpointer   data)
558 {
559   GIOStream *connection;
560   GError *error = NULL;
561
562   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
563   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
564   g_assert_no_error (error);
565   g_object_unref (connection);
566
567   /* No validation at all in this test */
568   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
569                                                 0);
570
571   read_test_data_async (test);
572   g_main_loop_run (test->loop);
573   wait_until_server_finished (test);
574
575   g_assert_no_error (test->read_error);
576   g_assert_no_error (test->server_error);
577 }
578
579 static void
580 test_verified_connection (TestConnection *test,
581                           gconstpointer   data)
582 {
583   GIOStream *connection;
584   GError *error = NULL;
585
586   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
587   g_assert_no_error (error);
588   g_assert_nonnull (test->database);
589
590   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
591   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
592   g_assert_no_error (error);
593   g_assert_nonnull (test->client_connection);
594   g_object_unref (connection);
595
596   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
597
598   /* All validation in this test */
599   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
600                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
601
602   read_test_data_async (test);
603   g_main_loop_run (test->loop);
604   wait_until_server_finished (test);
605
606   g_assert_no_error (test->read_error);
607   g_assert_no_error (test->server_error);
608 }
609
610 static void
611 test_verified_chain (TestConnection *test,
612                      gconstpointer   data)
613 {
614   GTlsBackend *backend;
615   GTlsCertificate *server_cert;
616   GTlsCertificate *intermediate_cert;
617   char *cert_data = NULL;
618   char *key_data = NULL;
619   GError *error = NULL;
620
621   backend = g_tls_backend_get_default ();
622
623   /* Prepare the intermediate cert. */
624   intermediate_cert = g_tls_certificate_new_from_file (tls_test_file_path ("intermediate-ca.pem"), &error);
625   g_assert_no_error (error);
626   g_assert_nonnull (intermediate_cert);
627
628   /* Prepare the server cert. */
629   g_clear_pointer (&cert_data, g_free);
630   g_file_get_contents (tls_test_file_path ("server-intermediate.pem"),
631                        &cert_data, NULL, &error);
632   g_assert_no_error (error);
633   g_assert_nonnull (cert_data);
634
635   g_file_get_contents (tls_test_file_path ("server-intermediate-key.pem"),
636                        &key_data, NULL, &error);
637   g_assert_no_error (error);
638   g_assert_nonnull (key_data);
639
640   server_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
641                                 NULL, &error,
642                                 "issuer", intermediate_cert,
643                                 "certificate-pem", cert_data,
644                                 "private-key-pem", key_data,
645                                 NULL);
646   g_assert_no_error (error);
647   g_assert_nonnull (server_cert);
648
649   g_object_unref (intermediate_cert);
650   g_free (cert_data);
651   g_free (key_data);
652
653   test->server_certificate = server_cert;
654   test_verified_connection (test, data);
655 }
656
657 static void
658 test_verified_chain_with_redundant_root_cert (TestConnection *test,
659                                               gconstpointer   data)
660 {
661   GTlsBackend *backend;
662   GTlsCertificate *server_cert;
663   GTlsCertificate *intermediate_cert;
664   GTlsCertificate *root_cert;
665   char *cert_data = NULL;
666   char *key_data = NULL;
667   GError *error = NULL;
668
669   backend = g_tls_backend_get_default ();
670
671   /* The root is redundant. It should not hurt anything. */
672   root_cert = g_tls_certificate_new_from_file (tls_test_file_path ("ca.pem"), &error);
673   g_assert_no_error (error);
674   g_assert_nonnull (root_cert);
675
676   /* Prepare the intermediate cert. */
677   g_file_get_contents (tls_test_file_path ("intermediate-ca.pem"),
678                        &cert_data, NULL, &error);
679   g_assert_no_error (error);
680   g_assert_nonnull (cert_data);
681
682   intermediate_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
683                                       NULL, &error,
684                                       "issuer", root_cert,
685                                       "certificate-pem", cert_data,
686                                       NULL);
687   g_assert_no_error (error);
688   g_assert_nonnull (intermediate_cert);
689
690   /* Prepare the server cert. */
691   g_clear_pointer (&cert_data, g_free);
692   g_file_get_contents (tls_test_file_path ("server-intermediate.pem"),
693                        &cert_data, NULL, &error);
694   g_assert_no_error (error);
695   g_assert_nonnull (cert_data);
696
697   g_file_get_contents (tls_test_file_path ("server-intermediate-key.pem"),
698                        &key_data, NULL, &error);
699   g_assert_no_error (error);
700   g_assert_nonnull (key_data);
701
702   server_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
703                                 NULL, &error,
704                                 "issuer", intermediate_cert,
705                                 "certificate-pem", cert_data,
706                                 "private-key-pem", key_data,
707                                 NULL);
708   g_assert_no_error (error);
709   g_assert_nonnull (server_cert);
710
711   g_object_unref (intermediate_cert);
712   g_object_unref (root_cert);
713   g_free (cert_data);
714   g_free (key_data);
715
716   test->server_certificate = server_cert;
717   test_verified_connection (test, data);
718 }
719
720 static void
721 test_verified_chain_with_duplicate_server_cert (TestConnection *test,
722                                                 gconstpointer   data)
723 {
724   /* This is another common server misconfiguration. Apache reads certificates
725    * from two configuration files: one for the server cert, and one for the rest
726    * of the chain. If the server cert is pasted into both files, it will be sent
727    * twice. We should be tolerant of this. */
728
729   GTlsBackend *backend;
730   GTlsCertificate *server_cert;
731   GTlsCertificate *extra_server_cert;
732   GTlsCertificate *intermediate_cert;
733   char *cert_data = NULL;
734   char *key_data = NULL;
735   GError *error = NULL;
736
737   backend = g_tls_backend_get_default ();
738
739   /* Prepare the intermediate cert. */
740   intermediate_cert = g_tls_certificate_new_from_file (tls_test_file_path ("intermediate-ca.pem"), &error);
741   g_assert_no_error (error);
742   g_assert_nonnull (intermediate_cert);
743
744   /* Prepare the server cert. */
745   g_clear_pointer (&cert_data, g_free);
746   g_file_get_contents (tls_test_file_path ("server-intermediate.pem"),
747                        &cert_data, NULL, &error);
748   g_assert_no_error (error);
749   g_assert_nonnull (cert_data);
750
751   g_file_get_contents (tls_test_file_path ("server-intermediate-key.pem"),
752                        &key_data, NULL, &error);
753   g_assert_no_error (error);
754   g_assert_nonnull (key_data);
755
756   server_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
757                                 NULL, &error,
758                                 "issuer", intermediate_cert,
759                                 "certificate-pem", cert_data,
760                                 NULL);
761   g_assert_no_error (error);
762   g_assert_nonnull (server_cert);
763
764   /* Prepare the server cert... again. Private key must go on this one. */
765   extra_server_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
766                                       NULL, &error,
767                                       "issuer", server_cert,
768                                       "certificate-pem", cert_data,
769                                       "private-key-pem", key_data,
770                                       NULL);
771   g_assert_no_error (error);
772   g_assert_nonnull (extra_server_cert);
773
774   g_object_unref (intermediate_cert);
775   g_object_unref (server_cert);
776   g_free (cert_data);
777   g_free (key_data);
778
779   test->server_certificate = extra_server_cert;
780   test_verified_connection (test, data);
781 }
782
783 static void
784 test_verified_unordered_chain (TestConnection *test,
785                                gconstpointer   data)
786 {
787   GTlsBackend *backend;
788   GTlsCertificate *server_cert;
789   GTlsCertificate *intermediate_cert;
790   GTlsCertificate *root_cert;
791   char *cert_data = NULL;
792   char *key_data = NULL;
793   GError *error = NULL;
794
795   backend = g_tls_backend_get_default ();
796
797   /* Prepare the intermediate cert (to be sent last, out of order)! */
798   intermediate_cert = g_tls_certificate_new_from_file (tls_test_file_path ("intermediate-ca.pem"),
799                                                        &error);
800   g_assert_no_error (error);
801   g_assert_nonnull (intermediate_cert);
802
803   g_file_get_contents (tls_test_file_path ("ca.pem"), &cert_data, NULL, &error);
804   g_assert_no_error (error);
805   g_assert_nonnull (cert_data);
806
807   /* Prepare the root cert (to be sent in the middle of the chain). */
808   root_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
809                               NULL, &error,
810                               "issuer", intermediate_cert,
811                               "certificate-pem", cert_data,
812                               NULL);
813   g_assert_no_error (error);
814   g_assert_nonnull (root_cert);
815
816   g_clear_pointer (&cert_data, g_free);
817   g_file_get_contents (tls_test_file_path ("server-intermediate.pem"),
818                        &cert_data, NULL, &error);
819   g_assert_no_error (error);
820   g_assert_nonnull (cert_data);
821
822   g_file_get_contents (tls_test_file_path ("server-intermediate-key.pem"),
823                        &key_data, NULL, &error);
824   g_assert_no_error (error);
825   g_assert_nonnull (key_data);
826
827   /* Prepare the server cert. */
828   server_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
829                                 NULL, &error,
830                                 "issuer", root_cert,
831                                 "certificate-pem", cert_data,
832                                 "private-key-pem", key_data,
833                                 NULL);
834   g_assert_no_error (error);
835   g_assert_nonnull (server_cert);
836
837   g_object_unref (intermediate_cert);
838   g_object_unref (root_cert);
839   g_free (cert_data);
840   g_free (key_data);
841
842   test->server_certificate = server_cert;
843   test_verified_connection (test, data);
844 }
845
846 static void
847 test_verified_chain_with_alternative_ca_cert (TestConnection *test,
848                                               gconstpointer   data)
849 {
850   GTlsBackend *backend;
851   GTlsCertificate *server_cert;
852   GTlsCertificate *intermediate_cert;
853   GTlsCertificate *root_cert;
854   char *cert_data = NULL;
855   char *key_data = NULL;
856   GError *error = NULL;
857
858   backend = g_tls_backend_get_default ();
859
860   /* This "root" cert is issued by a CA that is not in the trust store. So it's
861    * not really a root, but it has the same public key as a cert in the trust
862    * store. If the client insists on a traditional chain of trust, this will
863    * fail, since the issuer is untrusted. */
864   root_cert = g_tls_certificate_new_from_file (tls_test_file_path ("ca-alternative.pem"), &error);
865   g_assert_no_error (error);
866   g_assert_nonnull (root_cert);
867
868   /* Prepare the intermediate cert. Modern TLS libraries are expected to notice
869    * that it is signed by the same public key as a certificate in the root
870    * store, and accept the certificate, ignoring the untrusted "root" sent next
871    * in the chain, which servers send for compatibility with clients that don't
872    * have the new CA cert in the trust store yet. (In this scenario, the old
873    * client still trusts the old CA cert.) */
874   g_file_get_contents (tls_test_file_path ("intermediate-ca.pem"),
875                        &cert_data, NULL, &error);
876   g_assert_no_error (error);
877   g_assert_nonnull (cert_data);
878
879   intermediate_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
880                                       NULL, &error,
881                                       "issuer", root_cert,
882                                       "certificate-pem", cert_data,
883                                       NULL);
884   g_assert_no_error (error);
885   g_assert_nonnull (intermediate_cert);
886
887   /* Prepare the server cert. */
888   g_clear_pointer (&cert_data, g_free);
889   g_file_get_contents (tls_test_file_path ("server-intermediate.pem"),
890                        &cert_data, NULL, &error);
891   g_assert_no_error (error);
892   g_assert_nonnull (cert_data);
893
894   g_file_get_contents (tls_test_file_path ("server-intermediate-key.pem"),
895                        &key_data, NULL, &error);
896   g_assert_no_error (error);
897   g_assert_nonnull (key_data);
898
899   server_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
900                                 NULL, &error,
901                                 "issuer", intermediate_cert,
902                                 "certificate-pem", cert_data,
903                                 "private-key-pem", key_data,
904                                 NULL);
905   g_assert_no_error (error);
906   g_assert_nonnull (server_cert);
907
908   g_object_unref (intermediate_cert);
909   g_object_unref (root_cert);
910   g_free (cert_data);
911   g_free (key_data);
912
913   test->server_certificate = server_cert;
914   test_verified_connection (test, data);
915 }
916
917 static void
918 test_invalid_chain_with_alternative_ca_cert (TestConnection *test,
919                                              gconstpointer   data)
920 {
921   GTlsBackend *backend;
922   GTlsCertificate *server_cert;
923   GTlsCertificate *root_cert;
924   GIOStream *connection;
925   char *cert_data = NULL;
926   char *key_data = NULL;
927   GError *error = NULL;
928
929   backend = g_tls_backend_get_default ();
930
931   /* This certificate has the same public key as a certificate in the root store. */
932   root_cert = g_tls_certificate_new_from_file (tls_test_file_path ("ca-alternative.pem"), &error);
933   g_assert_no_error (error);
934   g_assert_nonnull (root_cert);
935
936   /* The intermediate cert is not sent. The chain should be rejected, since without intermediate.pem
937    * there is no proof that ca-alternative.pem signed server-intermediate.pem. */
938   g_file_get_contents (tls_test_file_path ("server-intermediate.pem"),
939                        &cert_data, NULL, &error);
940   g_assert_no_error (error);
941   g_assert_nonnull (cert_data);
942
943   g_file_get_contents (tls_test_file_path ("server-intermediate-key.pem"),
944                        &key_data, NULL, &error);
945   g_assert_no_error (error);
946   g_assert_nonnull (key_data);
947
948   server_cert = g_initable_new (g_tls_backend_get_certificate_type (backend),
949                                 NULL, &error,
950                                 "issuer", root_cert,
951                                 "certificate-pem", cert_data,
952                                 "private-key-pem", key_data,
953                                 NULL);
954   g_assert_no_error (error);
955   g_assert_nonnull (server_cert);
956
957   g_object_unref (root_cert);
958   g_free (cert_data);
959   g_free (key_data);
960
961   test->server_certificate = server_cert;
962   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
963   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
964   g_assert_no_error (error);
965   g_assert_nonnull (test->client_connection);
966   g_object_unref (connection);
967
968   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
969
970   /* Make sure this test doesn't expire. */
971   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
972                                                 G_TLS_CERTIFICATE_VALIDATE_ALL & ~G_TLS_CERTIFICATE_EXPIRED);
973
974   read_test_data_async (test);
975   g_main_loop_run (test->loop);
976   wait_until_server_finished (test);
977
978   g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
979
980 #ifdef BACKEND_IS_GNUTLS
981   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS);
982 #elif defined(BACKEND_IS_OPENSSL)
983   /* FIXME: This is not OK. There should be a NOT_TLS errors. But some times
984    * we either get no error or BROKEN_PIPE
985    */
986 #endif
987 }
988
989 static void
990 on_notify_accepted_cas (GObject *obj,
991                         GParamSpec *spec,
992                         gpointer user_data)
993 {
994   gboolean *changed = user_data;
995   *changed = TRUE;
996 }
997
998 static void
999 test_client_auth_connection (TestConnection *test,
1000                              gconstpointer   data)
1001 {
1002   GIOStream *connection;
1003   GError *error = NULL;
1004   GTlsCertificate *cert;
1005   GTlsCertificate *peer;
1006   gboolean cas_changed;
1007   GSocketClient *client;
1008
1009   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
1010   g_assert_no_error (error);
1011   g_assert_nonnull (test->database);
1012
1013   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_REQUIRED);
1014   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1015   g_assert_no_error (error);
1016   g_assert_nonnull (test->client_connection);
1017   g_object_unref (connection);
1018
1019   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1020
1021   cert = g_tls_certificate_new_from_file (tls_test_file_path ("client-and-key.pem"), &error);
1022   g_assert_no_error (error);
1023
1024   g_tls_connection_set_certificate (G_TLS_CONNECTION (test->client_connection), cert);
1025
1026   /* All validation in this test */
1027   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1028                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1029
1030   cas_changed = FALSE;
1031   g_signal_connect (test->client_connection, "notify::accepted-cas",
1032                     G_CALLBACK (on_notify_accepted_cas), &cas_changed);
1033
1034   read_test_data_async (test);
1035   g_main_loop_run (test->loop);
1036   wait_until_server_finished (test);
1037
1038   g_assert_no_error (test->read_error);
1039   g_assert_no_error (test->server_error);
1040
1041   peer = g_tls_connection_get_peer_certificate (G_TLS_CONNECTION (test->server_connection));
1042   g_assert_nonnull (peer);
1043   g_assert_true (g_tls_certificate_is_same (peer, cert));
1044   g_assert_true (cas_changed);
1045
1046   g_object_unref (cert);
1047   g_object_unref (test->client_connection);
1048   g_clear_object (&test->server_connection);
1049
1050   /* Now start a new connection to the same server with a different client cert */
1051   client = g_socket_client_new ();
1052   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
1053                                                      NULL, &error));
1054   g_assert_no_error (error);
1055   g_object_unref (client);
1056   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1057   g_assert_no_error (error);
1058   g_assert_nonnull (test->client_connection);
1059   g_object_unref (connection);
1060
1061   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1062                                                 0);
1063   cert = g_tls_certificate_new_from_file (tls_test_file_path ("client2-and-key.pem"), &error);
1064   g_assert_no_error (error);
1065   g_tls_connection_set_certificate (G_TLS_CONNECTION (test->client_connection), cert);
1066   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1067
1068   read_test_data_async (test);
1069   g_main_loop_run (test->loop);
1070   wait_until_server_finished (test);
1071
1072   g_assert_no_error (test->read_error);
1073   g_assert_no_error (test->server_error);
1074
1075   /* peer should see the second client cert */
1076   peer = g_tls_connection_get_peer_certificate (G_TLS_CONNECTION (test->server_connection));
1077   g_assert_nonnull (peer);
1078   g_assert_true (g_tls_certificate_is_same (peer, cert));
1079   g_object_unref (cert);
1080 }
1081
1082 #ifdef BACKEND_IS_GNUTLS
1083 static void
1084 run_until_object_is_destroyed (GMainContext *context,
1085                                GWeakRef     *weak_ref)
1086 {
1087   GObject *object;
1088
1089   while ((object = g_weak_ref_get (weak_ref)))
1090     {
1091       g_object_unref (object);
1092       g_main_context_iteration (context, FALSE);
1093     }
1094 }
1095 #endif
1096
1097 static void
1098 test_client_auth_pkcs11_connection (TestConnection *test,
1099                                     gconstpointer   data)
1100 {
1101 #ifndef BACKEND_IS_GNUTLS
1102   g_test_skip ("This backend does not support PKCS #11");
1103 #else
1104   GIOStream *connection;
1105   GError *error = NULL;
1106   GTlsCertificate *cert;
1107   GTlsCertificate *peer;
1108   gboolean cas_changed;
1109   GSocketClient *client;
1110   GTlsInteraction *interaction;
1111   GWeakRef weak_ref;
1112
1113   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
1114   g_assert_no_error (error);
1115   g_assert_nonnull (test->database);
1116
1117   interaction = mock_interaction_new_static_password ("ABC123");
1118
1119   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_REQUIRED);
1120   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1121   g_assert_no_error (error);
1122   g_assert_nonnull (test->client_connection);
1123   g_object_unref (connection);
1124
1125   g_weak_ref_init (&weak_ref, test->client_connection);
1126
1127   g_tls_connection_set_interaction (G_TLS_CONNECTION (test->client_connection), interaction);
1128   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1129
1130   cert = g_tls_certificate_new_from_pkcs11_uris ("pkcs11:model=mock;manufacturer=GLib-Networking;serial=1;token=Mock%20Certificate;id=%4D%6F%63%6B%20%43%65%72%74%69%66%69%63%61%74%65;object=Mock%20Certificate;type=cert",
1131                                                  "pkcs11:model=mock;manufacturer=GLib-Networking;serial=1;token=Mock%20Certificate;id=%4D%6F%63%6B%20%50%72%69%76%61%74%65%20%4B%65%79;object=Mock%20Private%20Key;type=private",
1132                                                  &error);
1133   g_assert_no_error (error);
1134
1135   g_tls_connection_set_certificate (G_TLS_CONNECTION (test->client_connection), cert);
1136
1137   /* All validation in this test */
1138   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1139                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1140
1141   cas_changed = FALSE;
1142   g_signal_connect (test->client_connection, "notify::accepted-cas",
1143                     G_CALLBACK (on_notify_accepted_cas), &cas_changed);
1144
1145   read_test_data_async (test);
1146   g_main_loop_run (test->loop);
1147   wait_until_server_finished (test);
1148
1149   g_assert_no_error (test->read_error);
1150   g_assert_no_error (test->server_error);
1151
1152   peer = g_tls_connection_get_peer_certificate (G_TLS_CONNECTION (test->server_connection));
1153   g_assert_nonnull (peer);
1154   g_assert_true (g_tls_certificate_is_same (peer, cert));
1155   g_assert_true (cas_changed);
1156
1157   g_object_unref (cert);
1158   g_object_unref (test->client_connection);
1159   g_clear_object (&test->server_connection);
1160
1161   /* The mock PKCS#11 module allows only a single PKCS#11 connection at a time.
1162    * This means we have to ensure the original GTlsClientConnection is finalized
1163    * before creating the next one.
1164    */
1165   run_until_object_is_destroyed (test->context, &weak_ref);
1166   g_weak_ref_clear (&weak_ref);
1167
1168   /* Now start a new connection to the same server with a different client cert.
1169    * Also test using a single URI matching both the cert and private key.
1170    */
1171   client = g_socket_client_new ();
1172   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
1173                                                      NULL, &error));
1174   g_assert_no_error (error);
1175   g_object_unref (client);
1176   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1177   g_assert_no_error (error);
1178   g_assert_nonnull (test->client_connection);
1179   g_object_unref (connection);
1180
1181   g_tls_connection_set_interaction (G_TLS_CONNECTION (test->client_connection), interaction);
1182   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1183                                                 0);
1184   cert = g_tls_certificate_new_from_pkcs11_uris ("pkcs11:model=mock;manufacturer=GLib-Networking;serial=1;token=Mock%20Certificate;id=%4D%6F%63%6B%20%50%72%69%76%61%74%65%20%4B%65%79%20%32",
1185                                                  NULL,
1186                                                  &error);
1187   g_assert_no_error (error);
1188   g_tls_connection_set_certificate (G_TLS_CONNECTION (test->client_connection), cert);
1189   g_object_unref (cert);
1190   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1191
1192   read_test_data_async (test);
1193   g_main_loop_run (test->loop);
1194   wait_until_server_finished (test);
1195
1196   g_assert_no_error (test->read_error);
1197   g_assert_no_error (test->server_error);
1198
1199   /* peer should see the second client cert */
1200   peer = g_tls_connection_get_peer_certificate (G_TLS_CONNECTION (test->server_connection));
1201   g_assert_nonnull (peer);
1202   g_assert_true (g_tls_certificate_is_same (peer, cert));
1203
1204   g_object_unref (interaction);
1205 #endif
1206 }
1207
1208 static void
1209 test_client_auth_rehandshake (TestConnection *test,
1210                               gconstpointer   data)
1211 {
1212   test->rehandshake = TRUE;
1213   test_client_auth_connection (test, data);
1214 }
1215
1216 static void
1217 test_client_auth_failure (TestConnection *test,
1218                           gconstpointer   data)
1219 {
1220   GIOStream *connection;
1221   GError *error = NULL;
1222   gboolean accepted_changed;
1223   GSocketClient *client;
1224   GTlsCertificate *cert;
1225   GTlsCertificate *peer;
1226   GTlsInteraction *interaction;
1227
1228   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
1229   g_assert_no_error (error);
1230   g_assert_nonnull (test->database);
1231
1232   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_REQUIRED);
1233   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1234   g_assert_no_error (error);
1235   g_assert_nonnull (test->client_connection);
1236   g_object_unref (connection);
1237
1238   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1239
1240   /* No Certificate set */
1241
1242   /* All validation in this test */
1243   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1244                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1245
1246   accepted_changed = FALSE;
1247   g_signal_connect (test->client_connection, "notify::accepted-cas",
1248                     G_CALLBACK (on_notify_accepted_cas), &accepted_changed);
1249
1250   test->ignore_client_close_error = TRUE;
1251
1252   read_test_data_async (test);
1253   g_main_loop_run (test->loop);
1254   wait_until_server_finished (test);
1255
1256   /* FIXME: We should always receive G_TLS_ERROR_CERTIFICATE_REQUIRED here. But
1257    * on our TLS 1.2 CI, sometimes we receive GNUTLS_E_PREMATURE_TERMINATION,
1258    * which we translate to G_TLS_ERROR_NOT_TLS because we have never handshaked
1259    * successfully. If the timing is different and it occurs after the handshake,
1260    * then we get G_TLS_ERROR_EOF. Sadly, I can't reproduce the issue locally, so
1261    * my odds of fixing it are slim to none. The connection is at least failing
1262    * as we expect, just not with the desired error.
1263    */
1264   if (!g_error_matches (test->read_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS) &&
1265       !g_error_matches (test->read_error, G_TLS_ERROR, G_TLS_ERROR_EOF))
1266     {
1267       g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED);
1268     }
1269   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED);
1270
1271   g_assert_true (accepted_changed);
1272
1273   g_object_unref (test->client_connection);
1274   g_clear_object (&test->server_connection);
1275   g_clear_error (&test->read_error);
1276   g_clear_error (&test->server_error);
1277
1278   test->ignore_client_close_error = FALSE;
1279
1280   /* Now start a new connection to the same server with a valid client cert;
1281    * this should succeed, and not use the cached failed session from above */
1282   client = g_socket_client_new ();
1283   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
1284                                                      NULL, &error));
1285   g_assert_no_error (error);
1286   g_object_unref (client);
1287   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1288   g_assert_no_error (error);
1289   g_assert_nonnull (test->client_connection);
1290   g_object_unref (connection);
1291
1292   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1293
1294   /* Have the interaction return a certificate */
1295   cert = g_tls_certificate_new_from_file (tls_test_file_path ("client-and-key.pem"), &error);
1296   g_assert_no_error (error);
1297   interaction = mock_interaction_new_static_certificate (cert);
1298   g_tls_connection_set_interaction (G_TLS_CONNECTION (test->client_connection), interaction);
1299   g_object_unref (interaction);
1300
1301   /* All validation in this test */
1302   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1303                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1304
1305   accepted_changed = FALSE;
1306   g_signal_connect (test->client_connection, "notify::accepted-cas",
1307                     G_CALLBACK (on_notify_accepted_cas), &accepted_changed);
1308
1309   read_test_data_async (test);
1310   g_main_loop_run (test->loop);
1311   wait_until_server_finished (test);
1312
1313   g_assert_no_error (test->read_error);
1314   g_assert_no_error (test->server_error);
1315
1316   peer = g_tls_connection_get_peer_certificate (G_TLS_CONNECTION (test->server_connection));
1317   g_assert_nonnull (peer);
1318   g_assert_true (g_tls_certificate_is_same (peer, cert));
1319   g_assert_true (accepted_changed);
1320
1321   g_object_unref (cert);
1322 }
1323
1324 static void
1325 test_client_auth_fail_missing_client_private_key (TestConnection *test,
1326                                                   gconstpointer   data)
1327 {
1328   GTlsCertificate *cert;
1329   GIOStream *connection;
1330   GError *error = NULL;
1331
1332   g_test_bug ("793712");
1333
1334   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
1335   g_assert_no_error (error);
1336   g_assert_nonnull (test->database);
1337
1338   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_REQUIRED);
1339   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1340   g_assert_no_error (error);
1341   g_assert_nonnull (test->client_connection);
1342   g_object_unref (connection);
1343
1344   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1345
1346   /* Oops: we "accidentally" set client.pem rather than client-and-key.pem. The
1347    * connection will fail, but we should not crash.
1348    */
1349   cert = g_tls_certificate_new_from_file (tls_test_file_path ("client.pem"), &error);
1350   g_assert_no_error (error);
1351
1352   g_tls_connection_set_certificate (G_TLS_CONNECTION (test->client_connection), cert);
1353
1354   /* All validation in this test */
1355   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1356                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1357 #if BACKEND_IS_OPENSSL && defined(G_OS_WIN32)
1358   test->ignore_client_close_error = TRUE;
1359 #endif
1360
1361   read_test_data_async (test);
1362   g_main_loop_run (test->loop);
1363   wait_until_server_finished (test);
1364
1365 #if BACKEND_IS_OPENSSL && defined(G_OS_WIN32)
1366   test->ignore_client_close_error = FALSE;
1367 #endif
1368
1369   g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED);
1370 #if BACKEND_IS_OPENSSL
1371   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED);
1372 #else
1373   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS);
1374 #endif
1375 }
1376
1377 static void
1378 test_client_auth_request_cert (TestConnection *test,
1379                                gconstpointer   data)
1380 {
1381   GIOStream *connection;
1382   GError *error = NULL;
1383   GTlsCertificate *cert;
1384   GTlsCertificate *peer;
1385   GTlsInteraction *interaction;
1386   gboolean cas_changed;
1387
1388   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
1389   g_assert_no_error (error);
1390   g_assert_nonnull (test->database);
1391
1392   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_REQUIRED);
1393   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1394   g_assert_no_error (error);
1395   g_assert_nonnull (test->client_connection);
1396   g_object_unref (connection);
1397
1398   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1399
1400   /* Have the interaction return a certificate */
1401   cert = g_tls_certificate_new_from_file (tls_test_file_path ("client-and-key.pem"), &error);
1402   g_assert_no_error (error);
1403   interaction = mock_interaction_new_static_certificate (cert);
1404   g_tls_connection_set_interaction (G_TLS_CONNECTION (test->client_connection), interaction);
1405   g_object_unref (interaction);
1406
1407   /* All validation in this test */
1408   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1409                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1410
1411   cas_changed = FALSE;
1412   g_signal_connect (test->client_connection, "notify::accepted-cas",
1413                     G_CALLBACK (on_notify_accepted_cas), &cas_changed);
1414
1415   read_test_data_async (test);
1416   g_main_loop_run (test->loop);
1417   wait_until_server_finished (test);
1418
1419   g_assert_no_error (test->read_error);
1420   g_assert_no_error (test->server_error);
1421
1422   peer = g_tls_connection_get_peer_certificate (G_TLS_CONNECTION (test->server_connection));
1423   g_assert_nonnull (peer);
1424   g_assert_true (g_tls_certificate_is_same (peer, cert));
1425   g_assert_true (cas_changed);
1426
1427   g_object_unref (cert);
1428 }
1429
1430 static void
1431 test_client_auth_request_fail (TestConnection *test,
1432                                gconstpointer   data)
1433 {
1434   GIOStream *connection;
1435   GError *error = NULL;
1436   GTlsInteraction *interaction;
1437
1438   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
1439   g_assert_no_error (error);
1440   g_assert_nonnull (test->database);
1441
1442   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_REQUIRED);
1443   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1444   g_assert_no_error (error);
1445   g_assert_nonnull (test->client_connection);
1446   g_object_unref (connection);
1447
1448   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1449
1450   /* Have the interaction return an error */
1451   interaction = mock_interaction_new_static_error (G_FILE_ERROR, G_FILE_ERROR_ACCES, "Request message");
1452   g_tls_connection_set_interaction (G_TLS_CONNECTION (test->client_connection), interaction);
1453   g_object_unref (interaction);
1454
1455   /* All validation in this test */
1456   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1457                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1458
1459   test->ignore_client_close_error = TRUE;
1460
1461   read_test_data_async (test);
1462   g_main_loop_run (test->loop);
1463   wait_until_server_finished (test);
1464
1465   /* FIXME: We should always receive G_TLS_ERROR_CERTIFICATE_REQUIRED here. But
1466    * on our TLS 1.2 CI, sometimes we receive GNUTLS_E_PREMATURE_TERMINATION,
1467    * which we translate to G_TLS_ERROR_NOT_TLS because we have never handshaked
1468    * successfully. If the timing is different and it occurs after the handshake,
1469    * then we get G_TLS_ERROR_EOF. Sadly, I can't reproduce the issue locally, so
1470    * my odds of fixing it are slim to none. The connection is at least failing
1471    * as we expect, just not with the desired error.
1472    */
1473   if (!g_error_matches (test->read_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS) &&
1474       !g_error_matches (test->read_error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED) &&
1475       !g_error_matches (test->read_error, G_TLS_ERROR, G_TLS_ERROR_EOF))
1476     {
1477       /* G_FILE_ERROR_ACCES is the error returned by our mock interaction object
1478        * when the GTlsInteraction's certificate request fails.
1479        */
1480       g_assert_error (test->read_error, G_FILE_ERROR, G_FILE_ERROR_ACCES);
1481     }
1482   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_CERTIFICATE_REQUIRED);
1483
1484   g_io_stream_close (test->server_connection, NULL, NULL);
1485   g_io_stream_close (test->client_connection, NULL, NULL);
1486 }
1487
1488 static void
1489 test_client_auth_request_none (TestConnection *test,
1490                                gconstpointer   data)
1491 {
1492   GIOStream *connection;
1493   GError *error = NULL;
1494
1495   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
1496   g_assert_no_error (error);
1497   g_assert_nonnull (test->database);
1498
1499   /* Request, but don't provide, a client certificate */
1500   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_REQUESTED);
1501   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1502   g_assert_no_error (error);
1503   g_assert_nonnull (test->client_connection);
1504   g_object_unref (connection);
1505
1506   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
1507
1508   /* All validation in this test */
1509   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1510                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1511
1512   read_test_data_async (test);
1513   g_main_loop_run (test->loop);
1514   wait_until_server_finished (test);
1515
1516   /* The connection should succeed and everything should work. We only REQUESTED
1517    * authentication, in contrast to G_TLS_AUTHENTICATION_REQUIRED where this
1518    * should fail.
1519    */
1520   g_assert_no_error (test->read_error);
1521   g_assert_no_error (test->server_error);
1522 }
1523
1524
1525 static void
1526 test_connection_no_database (TestConnection *test,
1527                              gconstpointer   data)
1528 {
1529   GIOStream *connection;
1530   GError *error = NULL;
1531
1532   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
1533   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1534   g_assert_no_error (error);
1535   g_assert_nonnull (test->client_connection);
1536   g_object_unref (connection);
1537
1538   /* Overrides loading of the default database */
1539   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), NULL);
1540
1541   /* All validation in this test */
1542   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1543                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1544
1545   test->accept_flags = G_TLS_CERTIFICATE_UNKNOWN_CA;
1546   g_signal_connect (test->client_connection, "accept-certificate",
1547                     G_CALLBACK (on_accept_certificate), test);
1548
1549   read_test_data_async (test);
1550   g_main_loop_run (test->loop);
1551   wait_until_server_finished (test);
1552
1553   g_assert_no_error (test->read_error);
1554   g_assert_no_error (test->server_error);
1555 }
1556
1557 static void
1558 handshake_failed_cb (GObject      *source,
1559                      GAsyncResult *result,
1560                      gpointer      user_data)
1561 {
1562   TestConnection *test = user_data;
1563   GError *error = NULL;
1564
1565   g_tls_connection_handshake_finish (G_TLS_CONNECTION (test->client_connection),
1566                                      result, &error);
1567   g_assert_error (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
1568   g_clear_error (&error);
1569
1570   g_main_loop_quit (test->loop);
1571 }
1572
1573 static void
1574 test_failed_connection (TestConnection *test,
1575                         gconstpointer   data)
1576 {
1577   GIOStream *connection;
1578   GError *error = NULL;
1579   GSocketConnectable *bad_addr;
1580
1581   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
1582
1583   bad_addr = g_network_address_new ("wrong.example.com", 80);
1584   test->client_connection = g_tls_client_connection_new (connection, bad_addr, &error);
1585   g_object_unref (bad_addr);
1586   g_assert_no_error (error);
1587   g_object_unref (connection);
1588
1589   g_tls_connection_handshake_async (G_TLS_CONNECTION (test->client_connection),
1590                                     G_PRIORITY_DEFAULT, NULL,
1591                                     handshake_failed_cb, test);
1592   g_main_loop_run (test->loop);
1593
1594   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1595                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
1596
1597   read_test_data_async (test);
1598   g_main_loop_run (test->loop);
1599   wait_until_server_finished (test);
1600
1601   g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
1602
1603 #ifdef BACKEND_IS_GNUTLS
1604   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS);
1605 #elif defined(BACKEND_IS_OPENSSL)
1606   /* FIXME: This is not OK. There should be a NOT_TLS errors. But some times
1607    * we either get no error or BROKEN_PIPE
1608    */
1609 #endif
1610 }
1611
1612 static void
1613 socket_client_connected (GObject      *source,
1614                          GAsyncResult *result,
1615                          gpointer      user_data)
1616 {
1617   TestConnection *test = user_data;
1618   GSocketConnection *connection;
1619   GError *error = NULL;
1620
1621   connection = g_socket_client_connect_finish (G_SOCKET_CLIENT (source),
1622                                                result, &error);
1623   g_assert_no_error (error);
1624   test->client_connection = G_IO_STREAM (connection);
1625
1626   g_main_loop_quit (test->loop);
1627 }
1628
1629 static void
1630 test_connection_socket_client (TestConnection *test,
1631                                gconstpointer   data)
1632 {
1633   GSocketClient *client;
1634   GTlsCertificateFlags flags;
1635   GSocketConnection *connection;
1636   GIOStream *base;
1637   GError *error = NULL;
1638
1639   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_CLOSE);
1640   client = g_socket_client_new ();
1641   g_socket_client_set_tls (client, TRUE);
1642   flags = G_TLS_CERTIFICATE_VALIDATE_ALL & ~G_TLS_CERTIFICATE_UNKNOWN_CA;
1643   /* test->address doesn't match the server's cert */
1644   flags = flags & ~G_TLS_CERTIFICATE_BAD_IDENTITY;
1645   g_socket_client_set_tls_validation_flags (client, flags);
1646
1647   g_socket_client_connect_async (client, G_SOCKET_CONNECTABLE (test->address),
1648                                  NULL, socket_client_connected, test);
1649   g_main_loop_run (test->loop);
1650   wait_until_server_finished (test);
1651
1652   connection = (GSocketConnection *)test->client_connection;
1653   test->client_connection = NULL;
1654
1655   g_assert_true (G_IS_TCP_WRAPPER_CONNECTION (connection));
1656   base = g_tcp_wrapper_connection_get_base_io_stream (G_TCP_WRAPPER_CONNECTION (connection));
1657   g_assert_true (G_IS_TLS_CONNECTION (base));
1658
1659   g_io_stream_close (G_IO_STREAM (connection), NULL, &error);
1660   g_assert_no_error (error);
1661   g_object_unref (connection);
1662
1663   g_object_unref (client);
1664 }
1665
1666 static void
1667 socket_client_failed (GObject      *source,
1668                       GAsyncResult *result,
1669                       gpointer      user_data)
1670 {
1671   TestConnection *test = user_data;
1672   GError *error = NULL;
1673
1674   g_socket_client_connect_finish (G_SOCKET_CLIENT (source),
1675                                   result, &error);
1676   g_assert_error (error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
1677   g_clear_error (&error);
1678
1679   g_main_loop_quit (test->loop);
1680 }
1681
1682 static void
1683 test_connection_socket_client_failed (TestConnection *test,
1684                                       gconstpointer   data)
1685 {
1686   GSocketClient *client;
1687
1688   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_CLOSE);
1689   client = g_socket_client_new ();
1690   g_socket_client_set_tls (client, TRUE);
1691   /* this time we don't adjust the validation flags */
1692
1693   g_socket_client_connect_async (client, G_SOCKET_CONNECTABLE (test->address),
1694                                  NULL, socket_client_failed, test);
1695   g_main_loop_run (test->loop);
1696   wait_until_server_finished (test);
1697
1698 #ifdef BACKEND_IS_GNUTLS
1699   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS);
1700 #else
1701   /* FIXME: This is not OK. There should be a NOT_TLS errors. But some times
1702    * we either get no error or BROKEN_PIPE
1703    */
1704 #endif
1705
1706   g_object_unref (client);
1707 }
1708
1709 static gboolean
1710 socket_client_timed_out_write (gpointer user_data)
1711 {
1712   TestConnection *test = user_data;
1713   GInputStream *input_stream;
1714   GOutputStream *output_stream;
1715   GError *error = NULL;
1716   gchar buffer[TEST_DATA_LENGTH];
1717   gssize size;
1718
1719   input_stream = g_io_stream_get_input_stream (test->client_connection);
1720   output_stream = g_io_stream_get_output_stream (test->client_connection);
1721
1722   /* read TEST_DATA_LENGTH once */
1723   size = g_input_stream_read (input_stream, &buffer, TEST_DATA_LENGTH,
1724                               NULL, &error);
1725   if (error)
1726     {
1727       /* This should very rarely ever happen, but in practice it can take more
1728        * than one second to read under heavy load, or when running many tests
1729        * simultaneously, so don't fail if this happens.
1730        */
1731       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT);
1732       g_assert_cmpint (size, ==, -1);
1733       g_clear_error (&error);
1734     }
1735   else
1736     {
1737       g_assert_no_error (error);
1738       g_assert_cmpint (size, ==, TEST_DATA_LENGTH);
1739
1740       /* read TEST_DATA_LENGTH again to cause the time out */
1741       size = g_input_stream_read (input_stream, &buffer, TEST_DATA_LENGTH,
1742                                   NULL, &error);
1743       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT);
1744       g_assert_cmpint (size, ==, -1);
1745       g_clear_error (&error);
1746     }
1747
1748   /* write after a timeout, session should still be valid */
1749   size = g_output_stream_write (output_stream, TEST_DATA, TEST_DATA_LENGTH,
1750                                 NULL, &error);
1751   g_assert_no_error (error);
1752   g_assert_cmpint (size, ==, TEST_DATA_LENGTH);
1753
1754   g_main_loop_quit (test->loop);
1755
1756   return G_SOURCE_REMOVE;
1757 }
1758
1759 static void
1760 socket_client_timed_out_write_connected (GObject      *source,
1761                                          GAsyncResult *result,
1762                                          gpointer      user_data)
1763 {
1764   TestConnection *test = user_data;
1765   GSocketConnection *connection;
1766   GError *error = NULL;
1767
1768   connection = g_socket_client_connect_finish (G_SOCKET_CLIENT (source),
1769                                                result, &error);
1770   g_assert_no_error (error);
1771   test->client_connection = G_IO_STREAM (connection);
1772
1773   /* We need to use an idle callback here to guarantee that the upcoming call
1774    * to g_input_stream_read() executes on the next iteration of the main
1775    * context. Otherwise, we could deadlock ourselves: the read would not be able
1776    * to complete if GTask executes socket_client_timed_out_write_connected()
1777    * using g_task_return_now() instead of posting the invocation to the next
1778    * iteration of the main context, because the server will not progress until
1779    * the main context is iterated, but iteration would be blocked waiting for
1780    * client's read to complete.
1781    */
1782   g_idle_add (socket_client_timed_out_write, test);
1783 }
1784
1785 static void
1786 test_connection_read_time_out_write (TestConnection *test,
1787                                      gconstpointer   data)
1788 {
1789   GSocketClient *client;
1790   GTlsCertificateFlags flags;
1791   GSocketConnection *connection;
1792   GIOStream *base;
1793   GError *error = NULL;
1794
1795   /* Don't close the server connection after writing TEST_DATA. */
1796   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_WAIT);
1797   client = g_socket_client_new ();
1798   /* Set a 1 second time out on the socket */
1799   g_socket_client_set_timeout (client, 1);
1800   g_socket_client_set_tls (client, TRUE);
1801   flags = G_TLS_CERTIFICATE_VALIDATE_ALL & ~G_TLS_CERTIFICATE_UNKNOWN_CA;
1802   /* test->address doesn't match the server's cert */
1803   flags = flags & ~G_TLS_CERTIFICATE_BAD_IDENTITY;
1804   g_socket_client_set_tls_validation_flags (client, flags);
1805
1806   g_socket_client_connect_async (client, G_SOCKET_CONNECTABLE (test->address),
1807                                  NULL, socket_client_timed_out_write_connected, test);
1808
1809   g_main_loop_run (test->loop);
1810
1811   /* Close the server now */
1812   close_server_connection (test);
1813
1814   connection = (GSocketConnection *)test->client_connection;
1815   test->client_connection = NULL;
1816
1817   g_assert_true (G_IS_TCP_WRAPPER_CONNECTION (connection));
1818   base = g_tcp_wrapper_connection_get_base_io_stream (G_TCP_WRAPPER_CONNECTION (connection));
1819   g_assert_true (G_IS_TLS_CONNECTION (base));
1820
1821   g_io_stream_close (G_IO_STREAM (connection), NULL, &error);
1822   g_assert_no_error (error);
1823   g_object_unref (connection);
1824
1825   g_object_unref (client);
1826 }
1827
1828 static void
1829 simul_async_read_complete (GObject      *object,
1830                            GAsyncResult *result,
1831                            gpointer      user_data)
1832 {
1833   TestConnection *test = user_data;
1834   gssize nread;
1835   GError *error = NULL;
1836
1837   nread = g_input_stream_read_finish (G_INPUT_STREAM (object),
1838                                       result, &error);
1839   g_assert_no_error (error);
1840
1841   test->nread += nread;
1842   g_assert_cmpint (test->nread, <=, TEST_DATA_LENGTH);
1843
1844   if (test->nread == TEST_DATA_LENGTH)
1845     {
1846       g_io_stream_close (test->client_connection, NULL, &error);
1847       g_assert_no_error (error);
1848       g_main_loop_quit (test->loop);
1849     }
1850   else
1851     {
1852       g_input_stream_read_async (G_INPUT_STREAM (object),
1853                                  test->buf + test->nread,
1854                                  TEST_DATA_LENGTH / 2,
1855                                  G_PRIORITY_DEFAULT, NULL,
1856                                  simul_async_read_complete, test);
1857     }
1858 }
1859
1860 static void
1861 simul_async_write_complete (GObject      *object,
1862                             GAsyncResult *result,
1863                             gpointer      user_data)
1864 {
1865   TestConnection *test = user_data;
1866   gssize nwrote;
1867   GError *error = NULL;
1868
1869   nwrote = g_output_stream_write_finish (G_OUTPUT_STREAM (object),
1870                                          result, &error);
1871   g_assert_no_error (error);
1872
1873   test->nwrote += nwrote;
1874   if (test->nwrote < TEST_DATA_LENGTH)
1875     {
1876       g_output_stream_write_async (G_OUTPUT_STREAM (object),
1877                                    &TEST_DATA[test->nwrote],
1878                                    TEST_DATA_LENGTH - test->nwrote,
1879                                    G_PRIORITY_DEFAULT, NULL,
1880                                    simul_async_write_complete, test);
1881     }
1882 }
1883
1884 static void
1885 test_simultaneous_async (TestConnection *test,
1886                          gconstpointer   data)
1887 {
1888   GIOStream *connection;
1889   GTlsCertificateFlags flags;
1890   GError *error = NULL;
1891
1892   connection = start_echo_server_and_connect_to_it (test);
1893   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1894   g_assert_no_error (error);
1895   g_object_unref (connection);
1896
1897   flags = G_TLS_CERTIFICATE_VALIDATE_ALL &
1898     ~(G_TLS_CERTIFICATE_UNKNOWN_CA | G_TLS_CERTIFICATE_BAD_IDENTITY);
1899   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1900                                                 flags);
1901
1902   memset (test->buf, 0, sizeof (test->buf));
1903   test->nread = test->nwrote = 0;
1904
1905   g_input_stream_read_async (g_io_stream_get_input_stream (test->client_connection),
1906                              test->buf, TEST_DATA_LENGTH / 2,
1907                              G_PRIORITY_DEFAULT, NULL,
1908                              simul_async_read_complete, test);
1909   g_output_stream_write_async (g_io_stream_get_output_stream (test->client_connection),
1910                                TEST_DATA, TEST_DATA_LENGTH / 2,
1911                                G_PRIORITY_DEFAULT, NULL,
1912                                simul_async_write_complete, test);
1913
1914   g_main_loop_run (test->loop);
1915   wait_until_server_finished (test);
1916
1917   g_assert_cmpint (test->nread, ==, TEST_DATA_LENGTH);
1918   g_assert_cmpint (test->nwrote, ==, TEST_DATA_LENGTH);
1919   g_assert_cmpstr (test->buf, ==, TEST_DATA);
1920 }
1921
1922 static void
1923 test_simultaneous_async_rehandshake (TestConnection *test,
1924                                      gconstpointer   data)
1925 {
1926   test->rehandshake = TRUE;
1927   test_simultaneous_async (test, data);
1928 }
1929
1930 static gpointer
1931 simul_read_thread (gpointer user_data)
1932 {
1933   TestConnection *test = user_data;
1934   GInputStream *istream = g_io_stream_get_input_stream (test->client_connection);
1935   GError *error = NULL;
1936   gssize nread;
1937
1938   while (test->nread < TEST_DATA_LENGTH)
1939     {
1940       nread = g_input_stream_read (istream,
1941                                    test->buf + test->nread,
1942                                    MIN (TEST_DATA_LENGTH / 2, TEST_DATA_LENGTH - test->nread),
1943                                    NULL, &error);
1944       g_assert_no_error (error);
1945
1946       test->nread += nread;
1947     }
1948
1949   return NULL;
1950 }
1951
1952 static gpointer
1953 simul_write_thread (gpointer user_data)
1954 {
1955   TestConnection *test = user_data;
1956   GOutputStream *ostream = g_io_stream_get_output_stream (test->client_connection);
1957   GError *error = NULL;
1958   gssize nwrote;
1959
1960   while (test->nwrote < TEST_DATA_LENGTH)
1961     {
1962       nwrote = g_output_stream_write (ostream,
1963                                       &TEST_DATA[test->nwrote],
1964                                       MIN (TEST_DATA_LENGTH / 2, TEST_DATA_LENGTH - test->nwrote),
1965                                       NULL, &error);
1966       g_assert_no_error (error);
1967
1968       test->nwrote += nwrote;
1969     }
1970
1971   return NULL;
1972 }
1973
1974 static void
1975 test_simultaneous_sync (TestConnection *test,
1976                         gconstpointer   data)
1977 {
1978   GIOStream *connection;
1979   GTlsCertificateFlags flags;
1980   GError *error = NULL;
1981   GThread *read_thread, *write_thread;
1982
1983   connection = start_echo_server_and_connect_to_it (test);
1984   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
1985   g_assert_no_error (error);
1986   g_object_unref (connection);
1987
1988   flags = G_TLS_CERTIFICATE_VALIDATE_ALL &
1989     ~(G_TLS_CERTIFICATE_UNKNOWN_CA | G_TLS_CERTIFICATE_BAD_IDENTITY);
1990   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
1991                                                 flags);
1992
1993   memset (test->buf, 0, sizeof (test->buf));
1994   test->nread = test->nwrote = 0;
1995
1996   read_thread = g_thread_new ("reader", simul_read_thread, test);
1997   write_thread = g_thread_new ("writer", simul_write_thread, test);
1998
1999   /* We need to run the main loop to get the GThreadedSocketService to
2000    * receive the connection and spawn the server thread.
2001    */
2002   while (!test->server_connection)
2003     g_main_context_iteration (test->context, FALSE);
2004
2005   g_thread_join (write_thread);
2006   g_thread_join (read_thread);
2007
2008   g_assert_cmpint (test->nread, ==, TEST_DATA_LENGTH);
2009   g_assert_cmpint (test->nwrote, ==, TEST_DATA_LENGTH);
2010   g_assert_cmpstr (test->buf, ==, TEST_DATA);
2011
2012   g_io_stream_close (test->client_connection, NULL, &error);
2013   g_assert_no_error (error);
2014 }
2015
2016 static void
2017 test_simultaneous_sync_rehandshake (TestConnection *test,
2018                                     gconstpointer   data)
2019 {
2020   test->rehandshake = TRUE;
2021   test_simultaneous_sync (test, data);
2022 }
2023
2024 static void
2025 test_close_immediately (TestConnection *test,
2026                         gconstpointer   data)
2027 {
2028   GIOStream *connection;
2029   GError *error = NULL;
2030
2031   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2032   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2033   g_assert_no_error (error);
2034   g_object_unref (connection);
2035
2036   /*
2037    * At this point the server won't get a chance to run. But regardless
2038    * closing should not wait on the server, trying to handshake or something.
2039    */
2040   g_io_stream_close (test->client_connection, NULL, &error);
2041   g_assert_no_error (error);
2042 }
2043
2044 static void
2045 close_server_connection_uncleanly (TestConnection *test)
2046 {
2047   GIOStream *base_iostream;
2048   GError *error = NULL;
2049
2050   /* Instead of closing the GTlsConnection itself, we'll directly close its
2051    * underlying output stream in order to ensure the TLS close notify is never
2052    * sent.
2053    */
2054   g_object_get (test->server_connection,
2055                 "base-io-stream", &base_iostream,
2056                 NULL);
2057
2058   g_io_stream_close (base_iostream, NULL, &error);
2059   g_assert_no_error (error);
2060
2061   test->server_running = FALSE;
2062
2063   g_object_unref (base_iostream);
2064 }
2065
2066 static void
2067 test_unclean_close_by_server (TestConnection *test,
2068                               gconstpointer   data)
2069 {
2070   GSocketClient *client;
2071   GTlsCertificateFlags flags;
2072   GTlsConnection *client_connection;
2073   gssize nread;
2074
2075   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, HANDSHAKE_ONLY);
2076   client = g_socket_client_new ();
2077   g_socket_client_set_tls (client, TRUE);
2078   flags = G_TLS_CERTIFICATE_VALIDATE_ALL & ~G_TLS_CERTIFICATE_UNKNOWN_CA;
2079   /* test->address doesn't match the server's cert */
2080   flags = flags & ~G_TLS_CERTIFICATE_BAD_IDENTITY;
2081   g_socket_client_set_tls_validation_flags (client, flags);
2082
2083   g_socket_client_connect_async (client, G_SOCKET_CONNECTABLE (test->address),
2084                                  NULL, socket_client_connected, test);
2085   g_main_loop_run (test->loop);
2086
2087   /* The server might not have completed its handshake yet. We want to
2088    * wait until the handshake has completed successfully before closing
2089    * the connection.
2090    */
2091   while (!test->server_ever_handshaked)
2092     g_main_context_iteration (test->context, TRUE);
2093
2094   close_server_connection_uncleanly (test);
2095
2096   /* Because the server closed its connection uncleanly, we should receive
2097    * G_TLS_ERROR_EOF to warn that the close notify alert was not received,
2098    * indicating a truncation attack. The only other acceptable error here
2099    * is connection closed, which is an uncommon race.
2100    */
2101   nread = g_input_stream_read (g_io_stream_get_input_stream (test->client_connection),
2102                                test->buf, TEST_DATA_LENGTH,
2103                                NULL, &test->read_error);
2104   if (!g_error_matches (test->read_error, G_IO_ERROR, G_IO_ERROR_BROKEN_PIPE))
2105     g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_EOF);
2106   g_assert_cmpint (nread, ==, -1);
2107
2108   /* Now do it again, except this time, we ignore truncation attacks by
2109    * disabling require_close_notify.
2110    */
2111   g_clear_error (&test->read_error);
2112   g_clear_object (&test->address);
2113   g_clear_object (&test->identity);
2114   g_socket_service_stop (test->service);
2115   g_clear_object (&test->service);
2116   g_clear_object (&test->server_connection);
2117   g_clear_object (&test->client_connection);
2118   test->server_ever_handshaked = FALSE;
2119   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, HANDSHAKE_ONLY);
2120
2121   g_socket_client_set_tls (client, TRUE);
2122   g_socket_client_connect_async (client, G_SOCKET_CONNECTABLE (test->address),
2123                                  NULL, socket_client_connected, test);
2124   g_main_loop_run (test->loop);
2125
2126   while (!test->server_ever_handshaked)
2127     g_main_context_iteration (test->context, TRUE);
2128
2129   close_server_connection_uncleanly (test);
2130
2131   client_connection = G_TLS_CONNECTION (g_tcp_wrapper_connection_get_base_io_stream (G_TCP_WRAPPER_CONNECTION (test->client_connection)));
2132   g_tls_connection_set_require_close_notify (client_connection, FALSE);
2133
2134   nread = g_input_stream_read (g_io_stream_get_input_stream (test->client_connection),
2135                                test->buf, TEST_DATA_LENGTH,
2136                                NULL, &test->read_error);
2137   if (!g_error_matches (test->read_error, G_IO_ERROR, G_IO_ERROR_BROKEN_PIPE))
2138     g_assert_no_error (test->read_error);
2139   g_assert_cmpint (nread, ==, 0);
2140
2141   g_object_unref (client);
2142 }
2143
2144 static gboolean
2145 async_implicit_handshake_dispatch (GPollableInputStream *stream,
2146                                    gpointer user_data)
2147 {
2148   TestConnection *test = user_data;
2149   GError *error = NULL;
2150   gchar buffer[TEST_DATA_LENGTH];
2151   gssize size;
2152   gboolean keep_running;
2153
2154   size = g_pollable_input_stream_read_nonblocking (stream, buffer,
2155                                                    TEST_DATA_LENGTH,
2156                                                    NULL, &error);
2157
2158   keep_running = (-1 == size);
2159
2160   if (keep_running)
2161     {
2162       g_assert_error (error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK);
2163       g_error_free (error);
2164     }
2165   else
2166     {
2167       g_assert_no_error (error);
2168       g_assert_cmpint (size, ==, TEST_DATA_LENGTH);
2169       g_main_loop_quit (test->loop);
2170     }
2171
2172   return keep_running;
2173 }
2174
2175 static void
2176 test_async_implicit_handshake (TestConnection *test, gconstpointer   data)
2177 {
2178   GTlsCertificateFlags flags;
2179   GIOStream *stream;
2180   GInputStream *input_stream;
2181   GSource *input_source;
2182   GError *error = NULL;
2183
2184   g_test_bug ("710691");
2185
2186   stream = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2187   test->client_connection = g_tls_client_connection_new (stream, test->identity, &error);
2188   g_assert_no_error (error);
2189   g_object_unref (stream);
2190
2191   flags = G_TLS_CERTIFICATE_VALIDATE_ALL &
2192     ~(G_TLS_CERTIFICATE_UNKNOWN_CA | G_TLS_CERTIFICATE_BAD_IDENTITY);
2193   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2194                                                 flags);
2195
2196   /**
2197    * Create a source from the client's input stream. The dispatch
2198    * callback will be called a first time, which will perform a
2199    * non-blocking read triggering the asynchronous implicit
2200    * handshaking.
2201    */
2202   input_stream = g_io_stream_get_input_stream (test->client_connection);
2203   input_source =
2204     g_pollable_input_stream_create_source (G_POLLABLE_INPUT_STREAM (input_stream),
2205                                            NULL);
2206
2207   g_source_set_callback (input_source,
2208                          (GSourceFunc) async_implicit_handshake_dispatch,
2209                          test, NULL);
2210
2211   g_source_attach (input_source, NULL);
2212   g_source_unref (input_source);
2213
2214   g_main_loop_run (test->loop);
2215   wait_until_server_finished (test);
2216
2217   g_io_stream_close (G_IO_STREAM (test->client_connection), NULL, &error);
2218   g_assert_no_error (error);
2219   g_object_unref (test->client_connection);
2220   test->client_connection = NULL;
2221 }
2222
2223 static void
2224 handshake_completed (GObject      *object,
2225                      GAsyncResult *result,
2226                      gpointer      user_data)
2227 {
2228   gboolean *complete = user_data;
2229
2230   *complete = TRUE;
2231   return;
2232 }
2233
2234 static void
2235 test_output_stream_close (TestConnection *test,
2236                           gconstpointer   data)
2237 {
2238   GIOStream *connection;
2239   GError *error = NULL;
2240   gboolean ret;
2241   gboolean handshake_complete = FALSE;
2242   gssize size;
2243
2244 #ifdef BACKEND_IS_OPENSSL
2245 # if OPENSSL_VERSION_NUMBER >= 0x10101000L
2246   /* FIXME: This test fails most of the times with openssl 1.1.1, my guess is that
2247    * there is still some threading issue and we endup calling input_stream_read
2248    * from different threads and the same time.
2249    */
2250   g_test_skip ("this is not supported with openssl 1.1.1");
2251   return;
2252 # endif
2253 #endif
2254
2255   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2256   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2257   g_assert_no_error (error);
2258   g_object_unref (connection);
2259
2260   /* No validation at all in this test */
2261   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2262                                                 0);
2263
2264   g_tls_connection_handshake_async (G_TLS_CONNECTION (test->client_connection),
2265                                     G_PRIORITY_DEFAULT, NULL,
2266                                     handshake_completed, &handshake_complete);
2267
2268   while (!handshake_complete)
2269     g_main_context_iteration (test->context, TRUE);
2270
2271   ret = g_output_stream_close (g_io_stream_get_output_stream (test->client_connection),
2272                                NULL, &error);
2273   g_assert_no_error (error);
2274   g_assert_true (ret);
2275
2276   /* Verify that double close returns TRUE */
2277   ret = g_output_stream_close (g_io_stream_get_output_stream (test->client_connection),
2278                                NULL, &error);
2279   g_assert_no_error (error);
2280   g_assert_true (ret);
2281
2282   size = g_output_stream_write (g_io_stream_get_output_stream (test->client_connection),
2283                                 "data", 4, NULL, &error);
2284   g_assert_cmpint (size, ==, -1);
2285   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CLOSED);
2286   g_clear_error (&error);
2287
2288   /* We closed the output stream, but not the input stream, so receiving
2289    * data should still work.
2290    */
2291   read_test_data_async (test);
2292   g_main_loop_run (test->loop);
2293   wait_until_server_finished (test);
2294
2295   g_assert_no_error (test->read_error);
2296   g_assert_no_error (test->server_error);
2297
2298   ret = g_io_stream_close (test->client_connection, NULL, &error);
2299   g_assert_no_error (error);
2300   g_assert_true (ret);
2301 }
2302
2303 static void
2304 test_garbage_database (TestConnection *test,
2305                        gconstpointer   data)
2306 {
2307   GIOStream *connection;
2308   GError *error = NULL;
2309
2310   test->database = g_tls_file_database_new (tls_test_file_path ("garbage.pem"), &error);
2311   g_assert_error (error, G_TLS_ERROR, G_TLS_ERROR_MISC);
2312   g_assert_null (test->database);
2313   g_clear_error (&error);
2314
2315   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2316   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2317   g_assert_no_error (error);
2318   g_assert_nonnull (test->client_connection);
2319   g_object_unref (connection);
2320
2321   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
2322
2323   /* All validation in this test */
2324   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2325                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
2326
2327   read_test_data_async (test);
2328   g_main_loop_run (test->loop);
2329   wait_until_server_finished (test);
2330
2331   /* Should reject the server's certificate, because our TLS database contains
2332    * no valid certificates.
2333    */
2334   g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
2335 #ifdef BACKEND_IS_GNUTLS
2336   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS);
2337 #endif
2338 }
2339
2340 static void
2341 test_readwrite_after_connection_destroyed (TestConnection *test,
2342                                            gconstpointer   data)
2343 {
2344   GIOStream *connection;
2345   GOutputStream *ostream;
2346   GInputStream *istream;
2347   unsigned char buffer[1];
2348   GError *error = NULL;
2349
2350   g_test_bug ("792219");
2351
2352   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2353   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2354   g_assert_no_error (error);
2355   g_object_unref (connection);
2356
2357   istream = g_object_ref (g_io_stream_get_input_stream (test->client_connection));
2358   ostream = g_object_ref (g_io_stream_get_output_stream (test->client_connection));
2359   g_clear_object (&test->client_connection);
2360
2361   /* The GTlsConnection has been destroyed, but its underlying streams
2362    * live on, because we have reffed them. Verify that attempts to read
2363    * and write produce only nice GErrors.
2364    */
2365   g_input_stream_read (istream, buffer, sizeof (buffer), NULL, &error);
2366   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CLOSED);
2367   g_clear_error (&error);
2368
2369   g_output_stream_write (ostream, TEST_DATA, TEST_DATA_LENGTH,
2370                          G_PRIORITY_DEFAULT, &error);
2371   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_CLOSED);
2372   g_clear_error (&error);
2373
2374   g_input_stream_close (istream, NULL, &error);
2375   g_assert_no_error (error);
2376
2377   g_output_stream_close (ostream, NULL, &error);
2378   g_assert_no_error (error);
2379
2380   g_object_unref (istream);
2381   g_object_unref (ostream);
2382 }
2383
2384 static void
2385 test_alpn (TestConnection *test,
2386            const char * const *client_protocols,
2387            const char * const *server_protocols,
2388            const char *negotiated_protocol)
2389 {
2390   GIOStream *connection;
2391   GError *error = NULL;
2392
2393   test->server_protocols = server_protocols;
2394
2395   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
2396   g_assert_no_error (error);
2397   g_assert_nonnull (test->database);
2398
2399   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2400   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2401   g_assert_no_error (error);
2402   g_object_unref (connection);
2403
2404   if (client_protocols)
2405     {
2406       g_tls_connection_set_advertised_protocols (G_TLS_CONNECTION (test->client_connection),
2407                                                  client_protocols);
2408     }
2409
2410   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
2411
2412   read_test_data_async (test);
2413   g_main_loop_run (test->loop);
2414   wait_until_server_finished (test);
2415
2416   g_assert_no_error (test->read_error);
2417   g_assert_no_error (test->server_error);
2418
2419   g_assert_cmpstr (g_tls_connection_get_negotiated_protocol (G_TLS_CONNECTION (test->server_connection)), ==, negotiated_protocol);
2420   g_assert_cmpstr (g_tls_connection_get_negotiated_protocol (G_TLS_CONNECTION (test->client_connection)), ==, negotiated_protocol);
2421 }
2422
2423 static void
2424 test_alpn_match (TestConnection *test,
2425                  gconstpointer   data)
2426 {
2427   const char * const client_protocols[] = { "one", "two", "three", NULL };
2428   const char * const server_protocols[] = { "four", "seven", "nine", "two", NULL };
2429
2430   test_alpn (test, client_protocols, server_protocols, "two");
2431 }
2432
2433 static void
2434 test_alpn_no_match (TestConnection *test,
2435                     gconstpointer   data)
2436 {
2437   const char * const client_protocols[] = { "one", "two", "three", NULL };
2438   const char * const server_protocols[] = { "four", "seven", "nine", NULL };
2439
2440   test_alpn (test, client_protocols, server_protocols, NULL);
2441 }
2442
2443 static void
2444 test_alpn_client_only (TestConnection *test,
2445                        gconstpointer   data)
2446 {
2447   const char * const client_protocols[] = { "one", "two", "three", NULL };
2448
2449   test_alpn (test, client_protocols, NULL, NULL);
2450 }
2451
2452 static void
2453 test_alpn_server_only (TestConnection *test,
2454                        gconstpointer   data)
2455 {
2456   const char * const server_protocols[] = { "four", "seven", "nine", "two", NULL };
2457
2458   test_alpn (test, NULL, server_protocols, NULL);
2459 }
2460
2461 static gboolean
2462 on_accept_certificate_with_sync_close (GTlsClientConnection *conn,
2463                                        GTlsCertificate      *cert,
2464                                        GTlsCertificateFlags  errors,
2465                                        gpointer              user_data)
2466 {
2467   GError *error = NULL;
2468
2469   /* Attempting to perform a sync operation that would block the
2470    * handshake should fail, not deadlock.
2471    */
2472   g_io_stream_close (G_IO_STREAM (conn), NULL, &error);
2473   g_assert_error (error, G_IO_ERROR, G_IO_ERROR_FAILED);
2474   g_error_free (error);
2475
2476   /* FIXME: When writing this test, I initially wanted to return FALSE
2477    * here to reject the connection. However, this surfaces a bug that I
2478    * have not fixed yet. The problem is the server is not seeing the end
2479    * of its g_output_stream_write() when the client fails the handshake.
2480    * No good. The server's implicit handshake failure should trigger a
2481    * write failure as well, instead of stalling. This needs to be fixed.
2482    *
2483    * Fixing this would allow us to guarantee that this callback is
2484    * actually executed by checking test->read_error at the bottom of
2485    * test_sync_op_during_handshake(). Currently, this test would still
2486    * pass even if this callback were to be improperly skipped.
2487    */
2488   return TRUE;
2489 }
2490
2491 static void
2492 test_sync_op_during_handshake (TestConnection *test,
2493                                gconstpointer   data)
2494 {
2495   GIOStream *connection;
2496   GError *error = NULL;
2497
2498   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2499   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2500   g_assert_no_error (error);
2501   g_object_unref (connection);
2502
2503   /* For this test, we need validation to fail to ensure that the
2504    * accept-certificate signal gets emitted.
2505    */
2506   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2507                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
2508
2509   g_signal_connect (test->client_connection, "accept-certificate",
2510                     G_CALLBACK (on_accept_certificate_with_sync_close), test);
2511
2512   read_test_data_async (test);
2513   g_main_loop_run (test->loop);
2514   wait_until_server_finished (test);
2515
2516   g_assert_no_error (test->read_error);
2517   g_assert_no_error (test->server_error);
2518 }
2519
2520 static void
2521 test_socket_timeout (TestConnection *test,
2522                      gconstpointer   data)
2523 {
2524   GIOStream *connection;
2525   GSocketClient *client;
2526   GError *error = NULL;
2527
2528   test->incoming_connection_delay = (gulong)(1.5 * G_USEC_PER_SEC);
2529
2530   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_CLOSE);
2531
2532   client = g_socket_client_new ();
2533   g_socket_client_set_timeout (client, 1);
2534   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
2535                                                      NULL, &error));
2536   g_assert_no_error (error);
2537   g_object_unref (client);
2538
2539   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2540   g_assert_no_error (error);
2541   g_object_unref (connection);
2542
2543   /* No validation at all in this test */
2544   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2545                                                 0);
2546
2547   read_test_data_async (test);
2548   g_main_loop_run (test->loop);
2549   wait_until_server_finished (test);
2550
2551   g_assert_error (test->read_error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT);
2552 #ifndef BACKEND_IS_OPENSSL
2553   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS);
2554 #endif
2555 }
2556
2557 static void
2558 test_connection_binding_match_tls_unique (TestConnection *test,
2559                                           gconstpointer   data)
2560 {
2561   GSocketClient *client;
2562   GIOStream *connection;
2563   GByteArray *client_cb, *server_cb;
2564   gchar *client_b64, *server_b64;
2565   gboolean client_supports_tls_unique;
2566   gboolean server_supports_tls_unique;
2567   GError *error = NULL;
2568
2569   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
2570   g_assert_no_error (error);
2571   g_assert_nonnull (test->database);
2572
2573   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_WAIT);
2574
2575   client = g_socket_client_new ();
2576   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
2577                                                      NULL, &error));
2578   g_assert_no_error (error);
2579   g_object_unref (client);
2580
2581   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2582   g_assert_no_error (error);
2583   g_assert_nonnull (test->client_connection);
2584   g_object_unref (connection);
2585
2586   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
2587
2588   /* All validation in this test */
2589   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2590                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
2591
2592   read_test_data_async (test);
2593   g_main_loop_run (test->loop);
2594
2595   /* tls-unique is supported by the OpenSSL backend always. It's supported by
2596    * the GnuTLS backend only with TLS 1.2 or older. Since the test needs to be
2597    * independent of backend and TLS version, this is allowed to fail....
2598    */
2599   client_supports_tls_unique = g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->client_connection),
2600                                                                           G_TLS_CHANNEL_BINDING_TLS_UNIQUE, NULL, NULL);
2601   server_supports_tls_unique = g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->server_connection),
2602                                                                           G_TLS_CHANNEL_BINDING_TLS_UNIQUE, NULL, NULL);
2603   g_assert_cmpint (client_supports_tls_unique, ==, server_supports_tls_unique);
2604
2605   /* Real test: retrieve bindings and compare */
2606   if (client_supports_tls_unique)
2607     {
2608       g_assert_false (g_tls_connection_get_protocol_version (
2609             G_TLS_CONNECTION (test->client_connection)) == G_TLS_PROTOCOL_VERSION_TLS_1_3);
2610       client_cb = g_byte_array_new ();
2611       server_cb = g_byte_array_new ();
2612       g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->client_connection),
2613                                                                 G_TLS_CHANNEL_BINDING_TLS_UNIQUE, client_cb, NULL));
2614       g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->server_connection),
2615                                                                 G_TLS_CHANNEL_BINDING_TLS_UNIQUE, server_cb, NULL));
2616       g_assert_cmpint (client_cb->len, >, 0);
2617       g_assert_cmpint (server_cb->len, >, 0);
2618
2619       client_b64 = g_base64_encode (client_cb->data, client_cb->len);
2620       server_b64 = g_base64_encode (server_cb->data, server_cb->len);
2621       g_assert_cmpstr (client_b64, ==, server_b64);
2622
2623       g_free (client_b64);
2624       g_free (server_b64);
2625       g_byte_array_unref (client_cb);
2626       g_byte_array_unref (server_cb);
2627     }
2628   else
2629     {
2630       g_assert_true (g_tls_connection_get_protocol_version (
2631             G_TLS_CONNECTION (test->client_connection)) == G_TLS_PROTOCOL_VERSION_TLS_1_3);
2632       g_test_skip ("tls-unique is not supported");
2633     }
2634
2635   /* drop the mic */
2636   close_server_connection (test);
2637   wait_until_server_finished (test);
2638
2639   g_assert_no_error (test->read_error);
2640   g_assert_no_error (test->server_error);
2641 }
2642
2643 /* create_files.sh should update this digest but if anything goes wrong
2644  * please make sure the string below matches the output of
2645  * openssl x509 -outform der -in files/server.pem | openssl sha256 -binary | base64
2646  **/
2647 #define SERVER_CERT_DIGEST_B64 "sdRMUK4PwcHXUPAMwglrSy4Fi8Ybfim61hfucliJ19s="
2648 static void
2649 test_connection_binding_match_tls_server_end_point (TestConnection *test,
2650                                                     gconstpointer   data)
2651 {
2652   GSocketClient *client;
2653   GIOStream *connection;
2654   GByteArray *client_cb, *server_cb;
2655   gchar *client_b64, *server_b64;
2656   GError *error = NULL;
2657
2658   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
2659   g_assert_no_error (error);
2660   g_assert_nonnull (test->database);
2661
2662   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_WAIT);
2663
2664   client = g_socket_client_new ();
2665   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
2666                                                      NULL, &error));
2667   g_assert_no_error (error);
2668   g_object_unref (client);
2669
2670   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2671   g_assert_no_error (error);
2672   g_assert_nonnull (test->client_connection);
2673   g_object_unref (connection);
2674
2675   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
2676
2677   /* All validation in this test */
2678   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2679                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
2680
2681   read_test_data_async (test);
2682   g_main_loop_run (test->loop);
2683
2684   /* Smoke test: ensure both sides support tls-server-end-point */
2685   g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->client_connection),
2686                                         G_TLS_CHANNEL_BINDING_TLS_SERVER_END_POINT, NULL, NULL));
2687   g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->server_connection),
2688                                         G_TLS_CHANNEL_BINDING_TLS_SERVER_END_POINT, NULL, NULL));
2689
2690   /* Real test: retrieve bindings and compare */
2691   client_cb = g_byte_array_new ();
2692   server_cb = g_byte_array_new ();
2693   g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->client_connection),
2694                                         G_TLS_CHANNEL_BINDING_TLS_SERVER_END_POINT, client_cb, NULL));
2695   g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->server_connection),
2696                                         G_TLS_CHANNEL_BINDING_TLS_SERVER_END_POINT, server_cb, NULL));
2697
2698   client_b64 = g_base64_encode (client_cb->data, client_cb->len);
2699   server_b64 = g_base64_encode (server_cb->data, server_cb->len);
2700   g_assert_cmpstr (client_b64, ==, server_b64);
2701   g_assert_cmpstr (client_b64, ==, SERVER_CERT_DIGEST_B64);
2702   g_assert_cmpstr (server_b64, ==, SERVER_CERT_DIGEST_B64);
2703
2704   g_free (client_b64);
2705   g_free (server_b64);
2706   g_byte_array_unref (client_cb);
2707   g_byte_array_unref (server_cb);
2708
2709   /* drop the mic */
2710   close_server_connection (test);
2711   wait_until_server_finished (test);
2712
2713   g_assert_no_error (test->read_error);
2714   g_assert_no_error (test->server_error);
2715 }
2716
2717 static void
2718 test_connection_binding_match_tls_exporter (TestConnection *test,
2719                                             gconstpointer   data)
2720 {
2721   GSocketClient *client;
2722   GIOStream *connection;
2723   GByteArray *client_cb, *server_cb;
2724   gchar *client_b64, *server_b64;
2725   GError *error = NULL;
2726
2727   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
2728   g_assert_no_error (error);
2729   g_assert_nonnull (test->database);
2730
2731   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_WAIT);
2732
2733   client = g_socket_client_new ();
2734   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
2735                                                      NULL, &error));
2736   g_assert_no_error (error);
2737   g_object_unref (client);
2738
2739   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2740   g_assert_no_error (error);
2741   g_assert_nonnull (test->client_connection);
2742   g_object_unref (connection);
2743
2744   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
2745
2746   /* All validation in this test */
2747   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2748                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
2749
2750   read_test_data_async (test);
2751   g_main_loop_run (test->loop);
2752
2753   /* Smoke test: ensure both sides support tls-exporter */
2754   g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->client_connection),
2755                                                     (GTlsChannelBindingType)100500, NULL, NULL));
2756   g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->server_connection),
2757                                                     (GTlsChannelBindingType)100500, NULL, NULL));
2758
2759   /* Real test: retrieve bindings and compare */
2760   client_cb = g_byte_array_new ();
2761   server_cb = g_byte_array_new ();
2762   g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->client_connection),
2763                                                     (GTlsChannelBindingType)100500, client_cb, NULL));
2764   g_assert_true (g_tls_connection_get_channel_binding_data (G_TLS_CONNECTION (test->server_connection),
2765                                                     (GTlsChannelBindingType)100500, server_cb, NULL));
2766
2767   client_b64 = g_base64_encode (client_cb->data, client_cb->len);
2768   server_b64 = g_base64_encode (server_cb->data, server_cb->len);
2769   g_assert_cmpstr (client_b64, ==, server_b64);
2770
2771   g_free (client_b64);
2772   g_free (server_b64);
2773   g_byte_array_unref (client_cb);
2774   g_byte_array_unref (server_cb);
2775
2776   /* drop the mic */
2777   close_server_connection (test);
2778   wait_until_server_finished (test);
2779
2780   g_assert_no_error (test->read_error);
2781   g_assert_no_error (test->server_error);
2782 }
2783
2784 static void
2785 test_connection_missing_server_identity (TestConnection *test,
2786                                          gconstpointer   data)
2787 {
2788   GIOStream *connection;
2789   GError *error = NULL;
2790
2791   test->database = g_tls_file_database_new (tls_test_file_path ("ca-roots.pem"), &error);
2792   g_assert_no_error (error);
2793   g_assert_nonnull (test->database);
2794
2795   /* We pass NULL instead of test->identity when creating the client
2796    * connection. This means verification must fail with
2797    * G_TLS_CERTIFICATE_BAD_IDENTITY.
2798    */
2799   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2800   test->client_connection = g_tls_client_connection_new (connection, NULL, &error);
2801   g_assert_no_error (error);
2802   g_assert_nonnull (test->client_connection);
2803   g_object_unref (connection);
2804
2805   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
2806
2807   /* All validation in this test */
2808   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2809                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
2810
2811   read_test_data_async (test);
2812   g_main_loop_run (test->loop);
2813   wait_until_server_finished (test);
2814
2815   g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
2816
2817 #ifdef BACKEND_IS_GNUTLS
2818   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS);
2819 #elif defined(BACKEND_IS_OPENSSL)
2820   /* FIXME: This is not OK. There should be a NOT_TLS errors. But some times
2821    * we either get no error or BROKEN_PIPE
2822    */
2823 #endif
2824
2825   g_clear_error (&test->read_error);
2826   g_clear_error (&test->server_error);
2827
2828   g_clear_object (&test->address);
2829   g_clear_object (&test->identity);
2830
2831   g_clear_object (&test->client_connection);
2832   g_clear_object (&test->server_connection);
2833
2834   g_socket_service_stop (test->service);
2835   g_clear_object (&test->service);
2836
2837   /* Now do the same thing again, this time ignoring bad identity. */
2838
2839   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2840   test->client_connection = g_tls_client_connection_new (connection, NULL, &error);
2841   g_assert_no_error (error);
2842   g_assert_nonnull (test->client_connection);
2843   g_object_unref (connection);
2844
2845   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
2846
2847   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2848                                                 G_TLS_CERTIFICATE_VALIDATE_ALL & ~G_TLS_CERTIFICATE_BAD_IDENTITY);
2849
2850   read_test_data_async (test);
2851   g_main_loop_run (test->loop);
2852   wait_until_server_finished (test);
2853
2854   g_assert_no_error (test->read_error);
2855   g_assert_no_error (test->server_error);
2856 }
2857
2858 typedef struct {
2859   TestConnection *test;
2860   gboolean peer_certificate_notified;
2861   gboolean peer_certificate_errors_notified;
2862 } NotifyTestData;
2863
2864 static gboolean
2865 on_accept_certificate_peer_certificate_notify (GTlsConnection       *conn,
2866                                                GTlsCertificate      *cert,
2867                                                GTlsCertificateFlags  errors,
2868                                                NotifyTestData       *data)
2869 {
2870   TestConnection *test = data->test;
2871
2872   g_assert_true (G_IS_TLS_CERTIFICATE (cert));
2873
2874   /* We guarantee these props are not set until after the handshake. */
2875   g_assert_null (g_tls_connection_get_peer_certificate (conn));
2876   g_assert_cmpint (g_tls_connection_get_peer_certificate_errors (conn), ==, 0);
2877
2878   g_assert_false (data->peer_certificate_notified);
2879   g_assert_false (data->peer_certificate_errors_notified);
2880
2881   return errors == test->accept_flags;
2882 }
2883
2884 static void
2885 on_peer_certificate_notify (GTlsConnection *conn,
2886                             GParamSpec     *pspec,
2887                             gboolean       *notified)
2888 {
2889   *notified = TRUE;
2890 }
2891
2892 static void
2893 on_peer_certificate_errors_notify (GTlsConnection *conn,
2894                                    GParamSpec     *pspec,
2895                                    gboolean       *notified)
2896 {
2897   *notified = TRUE;
2898 }
2899
2900 static void
2901 test_peer_certificate_notify (TestConnection *test,
2902                               gconstpointer   data)
2903 {
2904   NotifyTestData notify_data = { test, FALSE, FALSE };
2905   GIOStream *connection;
2906   GError *error = NULL;
2907
2908   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2909   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2910   g_assert_no_error (error);
2911   g_object_unref (connection);
2912
2913   /* For this test, we need validation to fail to ensure that the
2914    * accept-certificate signal gets emitted.
2915    */
2916   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2917                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
2918
2919   g_signal_connect (test->client_connection, "accept-certificate",
2920                     G_CALLBACK (on_accept_certificate_peer_certificate_notify), &notify_data);
2921   g_signal_connect (test->client_connection, "notify::peer-certificate",
2922                     G_CALLBACK (on_peer_certificate_notify), &notify_data.peer_certificate_notified);
2923   g_signal_connect (test->client_connection, "notify::peer-certificate-errors",
2924                     G_CALLBACK (on_peer_certificate_errors_notify), &notify_data.peer_certificate_errors_notified);
2925
2926   read_test_data_async (test);
2927   g_main_loop_run (test->loop);
2928   wait_until_server_finished (test);
2929
2930   g_assert_true (notify_data.peer_certificate_notified);
2931   g_assert_true (notify_data.peer_certificate_errors_notified);
2932
2933   g_assert_true (G_IS_TLS_CERTIFICATE (g_tls_connection_get_peer_certificate (G_TLS_CONNECTION (test->client_connection))));
2934   g_assert_cmpint (g_tls_connection_get_peer_certificate_errors (G_TLS_CONNECTION (test->client_connection)), !=, 0);
2935
2936   g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
2937 #ifdef BACKEND_IS_GNUTLS
2938   g_assert_error (test->server_error, G_TLS_ERROR, G_TLS_ERROR_NOT_TLS);
2939 #elif defined(BACKEND_IS_OPENSSL)
2940   /* FIXME: This is not OK. There should be a NOT_TLS errors. But some times
2941    * we either get no error or BROKEN_PIPE
2942    */
2943 #endif
2944 }
2945
2946 static void
2947 test_tls_info (TestConnection *test,
2948                gconstpointer   data)
2949 {
2950   GIOStream *connection;
2951   char *ciphersuite_name;
2952   GError *error = NULL;
2953
2954   connection = start_async_server_and_connect_to_it (test, G_TLS_AUTHENTICATION_NONE);
2955   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
2956   g_assert_no_error (error);
2957   g_object_unref (connection);
2958
2959   g_assert_cmpint (g_tls_connection_get_protocol_version (G_TLS_CONNECTION (test->client_connection)), ==, G_TLS_PROTOCOL_VERSION_UNKNOWN);
2960   g_assert_null (g_tls_connection_get_ciphersuite_name (G_TLS_CONNECTION (test->client_connection)));
2961
2962   /* No validation at all in this test */
2963   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
2964                                                 0);
2965
2966
2967   read_test_data_async (test);
2968   g_main_loop_run (test->loop);
2969   wait_until_server_finished (test);
2970
2971   g_assert_no_error (test->read_error);
2972   g_assert_no_error (test->server_error);
2973
2974   g_assert_cmpint (g_tls_connection_get_protocol_version (G_TLS_CONNECTION (test->client_connection)), !=, G_TLS_PROTOCOL_VERSION_UNKNOWN);
2975   ciphersuite_name = g_tls_connection_get_ciphersuite_name (G_TLS_CONNECTION (test->client_connection));
2976   g_assert_nonnull (ciphersuite_name);
2977   g_free (ciphersuite_name);
2978 }
2979
2980 static void
2981 test_connection_oscp_must_staple (TestConnection *test,
2982                                   gconstpointer   data)
2983 {
2984   GSocketClient *client;
2985   GIOStream *connection;
2986   GError *error = NULL;
2987
2988   test->database = g_tls_file_database_new (tls_test_file_path ("ca.pem"), &error);
2989   g_assert_no_error (error);
2990   g_assert_nonnull (test->database);
2991
2992   test->server_certificate = g_tls_certificate_new_from_file (tls_test_file_path ("server-ocsp-required-by-server-and-key.pem"), &error);
2993   g_assert_no_error (error);
2994   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_WAIT);
2995
2996   client = g_socket_client_new ();
2997   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
2998                                                      NULL, &error));
2999   g_assert_no_error (error);
3000   g_object_unref (client);
3001
3002   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
3003   g_assert_no_error (error);
3004   g_assert_nonnull (test->client_connection);
3005   g_object_unref (connection);
3006
3007   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
3008
3009   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
3010                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
3011
3012   read_test_data_async (test);
3013   g_main_loop_run (test->loop);
3014
3015   close_server_connection (test);
3016   wait_until_server_finished (test);
3017
3018   /* The server certificate states it supports status_request but our server does not
3019    * actually set or support that.
3020    * To be secure this must error as a bad certificate. */
3021   g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
3022
3023   g_clear_error (&test->read_error);
3024   g_clear_error (&test->server_error);
3025 }
3026
3027 static void
3028 test_connection_oscp_must_staple_intermediate_certificate (TestConnection *test,
3029                                                            gconstpointer   data)
3030 {
3031   GSocketClient *client;
3032   GIOStream *connection;
3033   GError *error = NULL;
3034
3035 #ifdef BACKEND_IS_OPENSSL
3036   g_test_skip ("OCSP Must-Staple on intermediate certificates is not supported with the OpenSSL backend");
3037   return;
3038 #endif
3039
3040   test->database = g_tls_file_database_new (tls_test_file_path ("ca-ocsp.pem"), &error);
3041   g_assert_no_error (error);
3042   g_assert_nonnull (test->database);
3043
3044   test->server_certificate = g_tls_certificate_new_from_file (tls_test_file_path ("server-ocsp-required-by-ca-and-key.pem"), &error);
3045   g_assert_no_error (error);
3046   start_async_server_service (test, G_TLS_AUTHENTICATION_NONE, WRITE_THEN_WAIT);
3047
3048   client = g_socket_client_new ();
3049   connection = G_IO_STREAM (g_socket_client_connect (client, G_SOCKET_CONNECTABLE (test->address),
3050                                                      NULL, &error));
3051   g_assert_no_error (error);
3052   g_object_unref (client);
3053
3054   test->client_connection = g_tls_client_connection_new (connection, test->identity, &error);
3055   g_assert_no_error (error);
3056   g_assert_nonnull (test->client_connection);
3057   g_object_unref (connection);
3058
3059   g_tls_connection_set_database (G_TLS_CONNECTION (test->client_connection), test->database);
3060
3061   g_tls_client_connection_set_validation_flags (G_TLS_CLIENT_CONNECTION (test->client_connection),
3062                                                 G_TLS_CERTIFICATE_VALIDATE_ALL);
3063
3064   read_test_data_async (test);
3065   g_main_loop_run (test->loop);
3066
3067   close_server_connection (test);
3068   wait_until_server_finished (test);
3069
3070   /* The CA certificate states it supports status_request but our server does not
3071    * actually set or support that.
3072    * To be secure this must error as a bad certificate. */
3073   g_assert_error (test->read_error, G_TLS_ERROR, G_TLS_ERROR_BAD_CERTIFICATE);
3074
3075   g_clear_error (&test->read_error);
3076   g_clear_error (&test->server_error);
3077 }
3078
3079 int
3080 main (int   argc,
3081       char *argv[])
3082 {
3083   int ret;
3084 #ifdef BACKEND_IS_GNUTLS
3085   char *module_path;
3086   const char *spy_path;
3087 #endif
3088
3089   g_test_init (&argc, &argv, NULL);
3090   g_test_bug_base ("http://bugzilla.gnome.org/");
3091
3092   g_setenv ("GSETTINGS_BACKEND", "memory", TRUE);
3093   g_setenv ("GIO_USE_TLS", BACKEND, TRUE);
3094
3095   g_assert_true (g_ascii_strcasecmp (G_OBJECT_TYPE_NAME (g_tls_backend_get_default ()), "GTlsBackend" BACKEND) == 0);
3096
3097 #ifdef BACKEND_IS_GNUTLS
3098   module_path = g_test_build_filename (G_TEST_BUILT, "mock-pkcs11.so", NULL);
3099   g_assert_true (g_file_test (module_path, G_FILE_TEST_EXISTS));
3100
3101   /* This just adds extra logging which is useful for debugging */
3102   spy_path = g_getenv ("PKCS11SPY_PATH");
3103   if (!spy_path)
3104     {
3105       spy_path = "/usr/lib64/pkcs11-spy.so"; /* Fedora's path */
3106       if (!g_file_test (spy_path, G_FILE_TEST_EXISTS))
3107         spy_path = "/usr/lib/x86_64-linux-gnu/pkcs11-spy.so"; /* Debian/Ubuntu's path */
3108     }
3109
3110   if (g_file_test (spy_path, G_FILE_TEST_EXISTS))
3111     {
3112       g_debug ("Using PKCS #11 Spy");
3113       g_setenv ("PKCS11SPY", module_path, TRUE);
3114       g_free (module_path);
3115       module_path = g_strdup (spy_path);
3116     }
3117
3118   ret = gnutls_pkcs11_init (GNUTLS_PKCS11_FLAG_MANUAL, NULL);
3119   g_assert_cmpint (ret, ==, GNUTLS_E_SUCCESS);
3120   ret = gnutls_pkcs11_add_provider (module_path, NULL);
3121   g_assert_cmpint (ret, ==, GNUTLS_E_SUCCESS);
3122   g_free (module_path);
3123 #endif
3124
3125   g_test_add ("/tls/" BACKEND "/connection/basic", TestConnection, NULL,
3126               setup_connection, test_basic_connection, teardown_connection);
3127   g_test_add ("/tls/" BACKEND "/connection/verified", TestConnection, NULL,
3128               setup_connection, test_verified_connection, teardown_connection);
3129   g_test_add ("/tls/" BACKEND "/connection/verified-chain", TestConnection, NULL,
3130               setup_connection, test_verified_chain, teardown_connection);
3131   g_test_add ("/tls/" BACKEND "/connection/verified-chain-with-redundant-root-cert", TestConnection, NULL,
3132               setup_connection, test_verified_chain_with_redundant_root_cert, teardown_connection);
3133   g_test_add ("/tls/" BACKEND "/connection/verified-chain-with-duplicate-server-cert", TestConnection, NULL,
3134               setup_connection, test_verified_chain_with_duplicate_server_cert, teardown_connection);
3135   g_test_add ("/tls/" BACKEND "/connection/verified-unordered-chain", TestConnection, NULL,
3136               setup_connection, test_verified_unordered_chain, teardown_connection);
3137   g_test_add ("/tls/" BACKEND "/connection/verified-chain-with-alternative-ca-cert", TestConnection, NULL,
3138               setup_connection, test_verified_chain_with_alternative_ca_cert, teardown_connection);
3139   g_test_add ("/tls/" BACKEND "/connection/invalid-chain-with-alternative-ca-cert", TestConnection, NULL,
3140               setup_connection, test_invalid_chain_with_alternative_ca_cert, teardown_connection);
3141   g_test_add ("/tls/" BACKEND "/connection/client-auth", TestConnection, NULL,
3142               setup_connection, test_client_auth_connection, teardown_connection);
3143   g_test_add ("/tls/" BACKEND "/connection/client-auth-rehandshake", TestConnection, NULL,
3144               setup_connection, test_client_auth_rehandshake, teardown_connection);
3145   g_test_add ("/tls/" BACKEND "/connection/client-auth-failure", TestConnection, NULL,
3146               setup_connection, test_client_auth_failure, teardown_connection);
3147   g_test_add ("/tls/" BACKEND "/connection/client-auth-fail-missing-client-private-key", TestConnection, NULL,
3148               setup_connection, test_client_auth_fail_missing_client_private_key, teardown_connection);
3149   g_test_add ("/tls/" BACKEND "/connection/client-auth-request-cert", TestConnection, NULL,
3150               setup_connection, test_client_auth_request_cert, teardown_connection);
3151   g_test_add ("/tls/" BACKEND "/connection/client-auth-request-fail", TestConnection, NULL,
3152               setup_connection, test_client_auth_request_fail, teardown_connection);
3153   g_test_add ("/tls/" BACKEND "/connection/client-auth-request-none", TestConnection, NULL,
3154               setup_connection, test_client_auth_request_none, teardown_connection);
3155   g_test_add ("/tls/" BACKEND "/connection/client-auth-pkcs11", TestConnection, NULL,
3156               setup_connection, test_client_auth_pkcs11_connection, teardown_connection);
3157   g_test_add ("/tls/" BACKEND "/connection/no-database", TestConnection, NULL,
3158               setup_connection, test_connection_no_database, teardown_connection);
3159   g_test_add ("/tls/" BACKEND "/connection/failed", TestConnection, NULL,
3160               setup_connection, test_failed_connection, teardown_connection);
3161   g_test_add ("/tls/" BACKEND "/connection/socket-client", TestConnection, NULL,
3162               setup_connection, test_connection_socket_client, teardown_connection);
3163   g_test_add ("/tls/" BACKEND "/connection/socket-client-failed", TestConnection, NULL,
3164               setup_connection, test_connection_socket_client_failed, teardown_connection);
3165   g_test_add ("/tls/" BACKEND "/connection/read-time-out-then-write", TestConnection, NULL,
3166               setup_connection, test_connection_read_time_out_write, teardown_connection);
3167   g_test_add ("/tls/" BACKEND "/connection/simultaneous-async", TestConnection, NULL,
3168               setup_connection, test_simultaneous_async, teardown_connection);
3169   g_test_add ("/tls/" BACKEND "/connection/simultaneous-sync", TestConnection, NULL,
3170               setup_connection, test_simultaneous_sync, teardown_connection);
3171   g_test_add ("/tls/" BACKEND "/connection/simultaneous-async-rehandshake", TestConnection, NULL,
3172               setup_connection, test_simultaneous_async_rehandshake, teardown_connection);
3173   g_test_add ("/tls/" BACKEND "/connection/simultaneous-sync-rehandshake", TestConnection, NULL,
3174               setup_connection, test_simultaneous_sync_rehandshake, teardown_connection);
3175   g_test_add ("/tls/" BACKEND "/connection/close-immediately", TestConnection, NULL,
3176               setup_connection, test_close_immediately, teardown_connection);
3177   g_test_add ("/tls/" BACKEND "/connection/unclean-close-by-server", TestConnection, NULL,
3178               setup_connection, test_unclean_close_by_server, teardown_connection);
3179   g_test_add ("/tls/" BACKEND "/connection/async-implicit-handshake", TestConnection, NULL,
3180               setup_connection, test_async_implicit_handshake, teardown_connection);
3181   g_test_add ("/tls/" BACKEND "/connection/output-stream-close", TestConnection, NULL,
3182               setup_connection, test_output_stream_close, teardown_connection);
3183   g_test_add ("/tls/" BACKEND "/connection/garbage-database", TestConnection, NULL,
3184               setup_connection, test_garbage_database, teardown_connection);
3185   g_test_add ("/tls/" BACKEND "/connection/readwrite-after-connection-destroyed", TestConnection, NULL,
3186               setup_connection, test_readwrite_after_connection_destroyed, teardown_connection);
3187   g_test_add ("/tls/" BACKEND "/connection/alpn/match", TestConnection, NULL,
3188               setup_connection, test_alpn_match, teardown_connection);
3189   g_test_add ("/tls/" BACKEND "/connection/alpn/no-match", TestConnection, NULL,
3190               setup_connection, test_alpn_no_match, teardown_connection);
3191   g_test_add ("/tls/" BACKEND "/connection/alpn/client-only", TestConnection, NULL,
3192               setup_connection, test_alpn_client_only, teardown_connection);
3193   g_test_add ("/tls/" BACKEND "/connection/alpn/server-only", TestConnection, NULL,
3194               setup_connection, test_alpn_server_only, teardown_connection);
3195   g_test_add ("/tls/" BACKEND "/connection/sync-op-during-handshake", TestConnection, NULL,
3196               setup_connection, test_sync_op_during_handshake, teardown_connection);
3197   g_test_add ("/tls/" BACKEND "/connection/socket-timeout", TestConnection, NULL,
3198               setup_connection, test_socket_timeout, teardown_connection);
3199   g_test_add ("/tls/" BACKEND "/connection/missing-server-identity", TestConnection, NULL,
3200               setup_connection, test_connection_missing_server_identity, teardown_connection);
3201   g_test_add ("/tls/" BACKEND "/connection/peer-certificate-notify", TestConnection, NULL,
3202               setup_connection, test_peer_certificate_notify, teardown_connection);
3203   g_test_add ("/tls/" BACKEND "/connection/binding/match-tls-unique", TestConnection, NULL,
3204               setup_connection, test_connection_binding_match_tls_unique, teardown_connection);
3205   g_test_add ("/tls/" BACKEND "/connection/binding/match-tls-server-end-point", TestConnection, NULL,
3206               setup_connection, test_connection_binding_match_tls_server_end_point, teardown_connection);
3207   g_test_add ("/tls/" BACKEND "/connection/binding/match-tls-exporter", TestConnection, NULL,
3208               setup_connection, test_connection_binding_match_tls_exporter, teardown_connection);
3209   g_test_add ("/tls/" BACKEND "/connection/tls-info", TestConnection, NULL,
3210               setup_connection, test_tls_info, teardown_connection);
3211   g_test_add ("/tls/" BACKEND "/connection/oscp/must-staple", TestConnection, NULL,
3212               setup_connection, test_connection_oscp_must_staple, teardown_connection);
3213   g_test_add ("/tls/" BACKEND "/connection/oscp/must-staple-intermediate-certificate", TestConnection, NULL,
3214               setup_connection, test_connection_oscp_must_staple_intermediate_certificate, teardown_connection);
3215
3216   ret = g_test_run ();
3217
3218   /* for valgrinding */
3219   g_main_context_unref (g_main_context_default ());
3220
3221   return ret;
3222 }