Imported Upstream version 3.0.30
[platform/upstream/gnutls.git] / tests / resume.c
1 /*
2  * Copyright (C) 2004-2012 Free Software Foundation, Inc.
3  *
4  * Author: Simon Josefsson
5  *
6  * This file is part of GnuTLS.
7  *
8  * GnuTLS is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * GnuTLS is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with GnuTLS; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 /* Parts copied from GnuTLS example programs. */
24
25 #ifdef HAVE_CONFIG_H
26 #include <config.h>
27 #endif
28
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #if !defined(_WIN32)
35 #include <sys/wait.h>
36 #include <netinet/in.h>
37 #include <arpa/inet.h>
38 #endif
39 #include <unistd.h>
40 #include <gnutls/gnutls.h>
41
42 #include "tcp.c"
43
44 #include "utils.h"
45
46 static void wrap_db_init (void);
47 static void wrap_db_deinit (void);
48 static int wrap_db_store (void *dbf, gnutls_datum_t key, gnutls_datum_t data);
49 static gnutls_datum_t wrap_db_fetch (void *dbf, gnutls_datum_t key);
50 static int wrap_db_delete (void *dbf, gnutls_datum_t key);
51
52 #define TLS_SESSION_CACHE 50
53
54 struct params_res
55 {
56   const char *desc;
57   int enable_db;
58   int enable_session_ticket_server;
59   int enable_session_ticket_client;
60   int expect_resume;
61 };
62
63 pid_t child;
64
65 struct params_res resume_tests[] = {
66   {"try to resume from db", 50, 0, 0, 1},
67   {"try to resume from session ticket", 0, 1, 1, 1},
68   {"try to resume from session ticket (server only)", 0, 1, 0, 0},
69   {"try to resume from session ticket (client only)", 0, 0, 1, 0},
70   {NULL, -1}
71 };
72
73 /* A very basic TLS client, with anonymous authentication.
74  */
75
76 #define MAX_BUF 5*1024
77 #define MSG "Hello TLS"
78
79 static void
80 tls_log_func (int level, const char *str)
81 {
82   fprintf (stderr, "%s |<%d>| %s", child ? "server" : "client", level, str);
83 }
84
85 static void
86 client (struct params_res *params)
87 {
88   int ret, sd, ii;
89   gnutls_session_t session;
90   char buffer[MAX_BUF + 1];
91   gnutls_anon_client_credentials_t anoncred;
92   /* Need to enable anonymous KX specifically. */
93
94   /* variables used in session resuming
95    */
96   int t;
97   gnutls_datum_t session_data;
98
99   if (debug)
100     {
101       gnutls_global_set_log_function (tls_log_func);
102       gnutls_global_set_log_level (2);
103     }
104   gnutls_global_init ();
105
106   gnutls_anon_allocate_client_credentials (&anoncred);
107
108   for (t = 0; t < 2; t++)
109     {                           /* connect 2 times to the server */
110       /* connect to the peer
111        */
112       sd = tcp_connect ();
113
114       /* Initialize TLS session
115        */
116       gnutls_init (&session, GNUTLS_CLIENT);
117
118       /* Use default priorities */
119       gnutls_priority_set_direct (session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL);
120
121       /* put the anonymous credentials to the current session
122        */
123       gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred);
124
125       if (params->enable_session_ticket_client)
126         gnutls_session_ticket_enable_client (session);
127
128       if (t > 0)
129         {
130           /* if this is not the first time we connect */
131           gnutls_session_set_data (session, session_data.data,
132                                    session_data.size);
133           gnutls_free (session_data.data);
134         }
135
136       gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
137
138       /* Perform the TLS handshake
139        */
140       ret = gnutls_handshake (session);
141
142       if (ret < 0)
143         {
144           fail ("client: Handshake failed\n");
145           gnutls_perror (ret);
146           goto end;
147         }
148       else
149         {
150           if (debug)
151             success ("client: Handshake was completed\n");
152         }
153
154       if (t == 0)
155         {                       /* the first time we connect */
156           /* get the session data size */
157           ret = gnutls_session_get_data2 (session, &session_data);
158           if (ret < 0)
159             fail ("Getting resume data failed\n");
160         }
161       else
162         {                       /* the second time we connect */
163
164           /* check if we actually resumed the previous session */
165           if (gnutls_session_is_resumed (session) != 0)
166             {
167               if (params->expect_resume)
168                 {
169                   if (debug)
170                     success ("- Previous session was resumed\n");
171                 }
172               else
173                 fail ("- Previous session was resumed\n");
174             }
175           else
176             {
177               if (params->expect_resume)
178                 {
179                   fail ("*** Previous session was NOT resumed\n");
180                 }
181               else
182                 {
183                   if (debug)
184                     success
185                       ("*** Previous session was NOT resumed (expected)\n");
186                 }
187             }
188         }
189
190       gnutls_record_send (session, MSG, strlen (MSG));
191
192       ret = gnutls_record_recv (session, buffer, MAX_BUF);
193       if (ret == 0)
194         {
195           if (debug)
196             success ("client: Peer has closed the TLS connection\n");
197           goto end;
198         }
199       else if (ret < 0)
200         {
201           fail ("client: Error: %s\n", gnutls_strerror (ret));
202           goto end;
203         }
204
205       if (debug )
206         {
207           printf ("- Received %d bytes: ", ret);
208           for (ii = 0; ii < ret; ii++)
209             {
210               fputc (buffer[ii], stdout);
211             }
212           fputs ("\n", stdout);
213         }
214
215       gnutls_bye (session, GNUTLS_SHUT_RDWR);
216
217
218       tcp_close (sd);
219
220       gnutls_deinit (session);
221     }
222
223 end:
224   gnutls_anon_free_client_credentials (anoncred);
225 }
226
227 /* This is a sample TLS 1.0 echo server, for anonymous authentication only.
228  */
229
230 #define SA struct sockaddr
231 #define PORT 5556               /* listen to 5556 port */
232 #define DH_BITS 1024
233
234 /* These are global */
235 gnutls_anon_server_credentials_t anoncred;
236 static gnutls_datum_t session_ticket_key = { NULL, 0 };
237
238 static gnutls_session_t
239 initialize_tls_session (struct params_res *params)
240 {
241   gnutls_session_t session;
242
243   gnutls_init (&session, GNUTLS_SERVER);
244
245   /* avoid calling all the priority functions, since the defaults
246    * are adequate.
247    */
248   gnutls_priority_set_direct (session, "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-ALL:+ANON-DH", NULL);
249
250   gnutls_credentials_set (session, GNUTLS_CRD_ANON, anoncred);
251
252   gnutls_dh_set_prime_bits (session, DH_BITS);
253
254   if (params->enable_db)
255     {
256       gnutls_db_set_retrieve_function (session, wrap_db_fetch);
257       gnutls_db_set_remove_function (session, wrap_db_delete);
258       gnutls_db_set_store_function (session, wrap_db_store);
259       gnutls_db_set_ptr (session, NULL);
260     }
261
262   if (params->enable_session_ticket_server)
263     gnutls_session_ticket_enable_server (session, &session_ticket_key);
264
265   return session;
266 }
267
268 static gnutls_dh_params_t dh_params;
269
270 static int
271 generate_dh_params (void)
272 {
273   const gnutls_datum_t p3 = { (void *) pkcs3, strlen (pkcs3) };
274   /* Generate Diffie-Hellman parameters - for use with DHE
275    * kx algorithms. These should be discarded and regenerated
276    * once a day, once a week or once a month. Depending on the
277    * security requirements.
278    */
279   gnutls_dh_params_init (&dh_params);
280   return gnutls_dh_params_import_pkcs3 (dh_params, &p3, GNUTLS_X509_FMT_PEM);
281 }
282
283 int err, listen_sd, i;
284 int sd, ret;
285 struct sockaddr_in sa_serv;
286 struct sockaddr_in sa_cli;
287 socklen_t client_len;
288 char topbuf[512];
289 gnutls_session_t session;
290 char buffer[MAX_BUF + 1];
291 int optval = 1;
292
293 static void
294 global_start (void)
295 {
296   /* Socket operations
297    */
298   listen_sd = socket (AF_INET, SOCK_STREAM, 0);
299   if (err == -1)
300     {
301       perror ("socket");
302       fail ("server: socket failed\n");
303       return;
304     }
305
306   memset (&sa_serv, '\0', sizeof (sa_serv));
307   sa_serv.sin_family = AF_INET;
308   sa_serv.sin_addr.s_addr = INADDR_ANY;
309   sa_serv.sin_port = htons (PORT);      /* Server Port number */
310
311   setsockopt (listen_sd, SOL_SOCKET, SO_REUSEADDR, (void *) &optval,
312               sizeof (int));
313
314   err = bind (listen_sd, (SA *) & sa_serv, sizeof (sa_serv));
315   if (err == -1)
316     {
317       perror ("bind");
318       fail ("server: bind failed\n");
319       return;
320     }
321
322   err = listen (listen_sd, 1024);
323   if (err == -1)
324     {
325       perror ("listen");
326       fail ("server: listen failed\n");
327       return;
328     }
329
330   if (debug)
331     success ("server: ready. Listening to port '%d'.\n", PORT);
332 }
333
334 static void
335 global_stop (void)
336 {
337   if (debug)
338     success ("global stop\n");
339
340   gnutls_anon_free_server_credentials (anoncred);
341
342   gnutls_dh_params_deinit (dh_params);
343
344   gnutls_global_deinit ();
345
346   shutdown (listen_sd, SHUT_RDWR);
347 }
348
349 static void
350 server (struct params_res *params)
351 {
352   size_t t;
353
354   /* this must be called once in the program, it is mostly for the server.
355    */
356   if (debug)
357     {
358       gnutls_global_set_log_function (tls_log_func);
359       gnutls_global_set_log_level (2);
360     }
361
362   gnutls_global_init ();
363   gnutls_anon_allocate_server_credentials (&anoncred);
364
365   if (debug)
366     success ("Launched, generating DH parameters...\n");
367
368   generate_dh_params ();
369
370   gnutls_anon_set_server_dh_params (anoncred, dh_params);
371
372   if (params->enable_db)
373     {
374       wrap_db_init ();
375     }
376
377   if (params->enable_session_ticket_server)
378     gnutls_session_ticket_key_generate (&session_ticket_key);
379
380   for (t = 0; t < 2; t++)
381     {
382       client_len = sizeof (sa_cli);
383
384       session = initialize_tls_session (params);
385
386       sd = accept (listen_sd, (SA *) & sa_cli, &client_len);
387
388       if (debug)
389         success ("server: connection from %s, port %d\n",
390                  inet_ntop (AF_INET, &sa_cli.sin_addr, topbuf,
391                             sizeof (topbuf)), ntohs (sa_cli.sin_port));
392
393       gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);
394       ret = gnutls_handshake (session);
395       if (ret < 0)
396         {
397           close (sd);
398           gnutls_deinit (session);
399           fail ("server: Handshake has failed (%s)\n\n",
400                 gnutls_strerror (ret));
401           return;
402         }
403       if (debug)
404         success ("server: Handshake was completed\n");
405
406       /* see the Getting peer's information example */
407       /* print_info(session); */
408
409       i = 0;
410       for (;;)
411         {
412           memset (buffer, 0, MAX_BUF + 1);
413           ret = gnutls_record_recv (session, buffer, MAX_BUF);
414
415           if (ret == 0)
416             {
417               if (debug)
418                 success ("server: Peer has closed the GnuTLS connection\n");
419               break;
420             }
421           else if (ret < 0)
422             {
423               fail ("server: Received corrupted data(%d). Closing...\n", ret);
424               break;
425             }
426           else if (ret > 0)
427             {
428               /* echo data back to the client
429                */
430               gnutls_record_send (session, buffer, strlen (buffer));
431             }
432         }
433       /* do not wait for the peer to close the connection.
434        */
435       gnutls_bye (session, GNUTLS_SHUT_WR);
436
437       close (sd);
438
439       gnutls_deinit (session);
440     }
441
442   close (listen_sd);
443
444   if (params->enable_db)
445     {
446       wrap_db_deinit ();
447     }
448
449   gnutls_free (session_ticket_key.data);
450   session_ticket_key.data = NULL;
451
452   if (debug)
453     success ("server: finished\n");
454 }
455
456 void
457 doit (void)
458 {
459   int i;
460
461   for (i = 0; resume_tests[i].desc; i++)
462     {
463       printf ("%s\n", resume_tests[i].desc);
464
465       global_start ();
466       if (error_count)
467         return;
468
469       child = fork ();
470       if (child < 0)
471         {
472           perror ("fork");
473           fail ("fork");
474           return;
475         }
476
477       if (child)
478         {
479           int status;
480           /* parent */
481           server (&resume_tests[i]);
482           wait (&status);
483           if (WEXITSTATUS(status) > 0)
484             error_count++;
485           global_stop ();
486         }
487       else
488         {
489           client (&resume_tests[i]);
490           gnutls_global_deinit ();
491           if (error_count)
492             exit(1);
493           exit (0);
494         }
495     }
496 }
497
498 /* Functions and other stuff needed for session resuming.
499  * This is done using a very simple list which holds session ids
500  * and session data.
501  */
502
503 #define MAX_SESSION_ID_SIZE 32
504 #define MAX_SESSION_DATA_SIZE 1024
505
506 typedef struct
507 {
508   unsigned char session_id[MAX_SESSION_ID_SIZE];
509   unsigned int session_id_size;
510
511   char session_data[MAX_SESSION_DATA_SIZE];
512   int session_data_size;
513 } CACHE;
514
515 static CACHE *cache_db;
516 static int cache_db_ptr = 0;
517
518 static void
519 wrap_db_init (void)
520 {
521
522   /* allocate cache_db */
523   cache_db = calloc (1, TLS_SESSION_CACHE * sizeof (CACHE));
524 }
525
526 static void
527 wrap_db_deinit (void)
528 {
529   free (cache_db);
530   cache_db = NULL;
531   return;
532 }
533
534 static int
535 wrap_db_store (void *dbf, gnutls_datum_t key, gnutls_datum_t data)
536 {
537   if (debug)
538     success ("resume db storing... (%d-%d)\n", key.size, data.size);
539
540   if (debug)
541     {
542       unsigned int i;
543       printf ("key:\n");
544       for (i = 0; i < key.size; i++)
545         {
546           printf ("%02x ", key.data[i] & 0xFF);
547           if ((i + 1) % 16 == 0)
548             printf ("\n");
549         }
550       printf ("\n");
551       printf ("data:\n");
552       for (i = 0; i < data.size; i++)
553         {
554           printf ("%02x ", data.data[i] & 0xFF);
555           if ((i + 1) % 16 == 0)
556             printf ("\n");
557         }
558       printf ("\n");
559     }
560
561   if (cache_db == NULL)
562     return -1;
563
564   if (key.size > MAX_SESSION_ID_SIZE)
565     return -1;
566
567   if (data.size > MAX_SESSION_DATA_SIZE)
568     return -1;
569
570   memcpy (cache_db[cache_db_ptr].session_id, key.data, key.size);
571   cache_db[cache_db_ptr].session_id_size = key.size;
572
573   memcpy (cache_db[cache_db_ptr].session_data, data.data, data.size);
574   cache_db[cache_db_ptr].session_data_size = data.size;
575
576   cache_db_ptr++;
577   cache_db_ptr %= TLS_SESSION_CACHE;
578
579   return 0;
580 }
581
582 static gnutls_datum_t
583 wrap_db_fetch (void *dbf, gnutls_datum_t key)
584 {
585   gnutls_datum_t res = { NULL, 0 };
586   int i;
587
588   if (debug)
589     success ("resume db fetch... (%d)\n", key.size);
590   if (debug)
591     {
592       unsigned int i;
593       printf ("key:\n");
594       for (i = 0; i < key.size; i++)
595         {
596           printf ("%02x ", key.data[i] & 0xFF);
597           if ((i + 1) % 16 == 0)
598             printf ("\n");
599         }
600       printf ("\n");
601     }
602
603   if (cache_db == NULL)
604     return res;
605
606   for (i = 0; i < TLS_SESSION_CACHE; i++)
607     {
608       if (key.size == cache_db[i].session_id_size &&
609           memcmp (key.data, cache_db[i].session_id, key.size) == 0)
610         {
611           if (debug)
612             success ("resume db fetch... return info\n");
613
614           res.size = cache_db[i].session_data_size;
615
616           res.data = gnutls_malloc (res.size);
617           if (res.data == NULL)
618             return res;
619
620           memcpy (res.data, cache_db[i].session_data, res.size);
621
622           if (debug)
623             {
624               unsigned int i;
625               printf ("data:\n");
626               for (i = 0; i < res.size; i++)
627                 {
628                   printf ("%02x ", res.data[i] & 0xFF);
629                   if ((i + 1) % 16 == 0)
630                     printf ("\n");
631                 }
632               printf ("\n");
633             }
634
635           return res;
636         }
637     }
638
639   if (debug)
640     success ("resume db fetch... NOT FOUND\n");
641   return res;
642 }
643
644 static int
645 wrap_db_delete (void *dbf, gnutls_datum_t key)
646 {
647   int i;
648
649   if (cache_db == NULL)
650     return -1;
651
652   for (i = 0; i < TLS_SESSION_CACHE; i++)
653     {
654       if (key.size == cache_db[i].session_id_size &&
655           memcmp (key.data, cache_db[i].session_id, key.size) == 0)
656         {
657
658           cache_db[i].session_id_size = 0;
659           cache_db[i].session_data_size = 0;
660
661           return 0;
662         }
663     }
664
665   return -1;
666
667 }