Tizen 2.0 Release
[external/libgnutls26.git] / lib / gnutls_handshake.c
1 /*
2  * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
3  * 2009, 2010 Free Software Foundation, Inc.
4  *
5  * Author: Nikos Mavrogiannopoulos
6  *
7  * This file is part of GnuTLS.
8  *
9  * The GnuTLS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1 of
12  * the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
22  * USA
23  *
24  */
25
26 /* Functions that relate to the TLS handshake procedure.
27  */
28
29 #include "gnutls_int.h"
30 #include "gnutls_errors.h"
31 #include "gnutls_dh.h"
32 #include "debug.h"
33 #include "gnutls_algorithms.h"
34 #include "gnutls_compress.h"
35 #include "gnutls_cipher.h"
36 #include "gnutls_buffers.h"
37 #include "gnutls_mbuffers.h"
38 #include "gnutls_kx.h"
39 #include "gnutls_handshake.h"
40 #include "gnutls_num.h"
41 #include "gnutls_hash_int.h"
42 #include "gnutls_db.h"
43 #include "gnutls_extensions.h"
44 #include "gnutls_supplemental.h"
45 #include "gnutls_auth.h"
46 #include "gnutls_v2_compat.h"
47 #include "auth_cert.h"
48 #include "gnutls_cert.h"
49 #include "gnutls_constate.h"
50 #include <gnutls_record.h>
51 #include <gnutls_state.h>
52 #include <ext_srp.h>
53 #include <ext_session_ticket.h>
54 #include <ext_safe_renegotiation.h>
55 #include <gnutls_rsa_export.h>  /* for gnutls_get_rsa_params() */
56 #include <auth_anon.h>          /* for gnutls_anon_server_credentials_t */
57 #include <auth_psk.h>           /* for gnutls_psk_server_credentials_t */
58 #include <random.h>
59
60 #ifdef HANDSHAKE_DEBUG
61 #define ERR(x, y) _gnutls_handshake_log("HSK[%p]: %s (%d)\n", session, x,y)
62 #else
63 #define ERR(x, y)
64 #endif
65
66 #define TRUE 1
67 #define FALSE 0
68
69 static int _gnutls_handshake_hash_init (gnutls_session_t session);
70 static int _gnutls_server_select_comp_method (gnutls_session_t session,
71                                               opaque * data, int datalen);
72 static int
73 _gnutls_handshake_hash_add_recvd (gnutls_session_t session,
74                                   gnutls_handshake_description_t recv_type,
75                                   opaque * header, uint16_t header_size,
76                                   opaque * dataptr, uint32_t datalen);
77
78
79
80 /* Clears the handshake hash buffers and handles.
81  */
82 void
83 _gnutls_handshake_hash_buffers_clear (gnutls_session_t session)
84 {
85   if (session->security_parameters.handshake_mac_handle_type ==
86       HANDSHAKE_MAC_TYPE_10)
87     {
88       _gnutls_hash_deinit (&session->internals.handshake_mac_handle.tls10.md5,
89                            NULL);
90       _gnutls_hash_deinit (&session->internals.handshake_mac_handle.tls10.sha,
91                            NULL);
92     }
93   else if (session->security_parameters.handshake_mac_handle_type ==
94            HANDSHAKE_MAC_TYPE_12)
95     {
96       _gnutls_hash_deinit (&session->internals.handshake_mac_handle.tls12.
97                            sha256, NULL);
98       _gnutls_hash_deinit (&session->internals.handshake_mac_handle.tls12.
99                            sha1, NULL);
100     }
101   session->security_parameters.handshake_mac_handle_type = 0;
102   session->internals.handshake_mac_handle_init = 0;
103   _gnutls_handshake_buffer_clear (session);
104 }
105
106 /* this will copy the required values for resuming to
107  * internals, and to security_parameters.
108  * this will keep as less data to security_parameters.
109  */
110 static void
111 resume_copy_required_values (gnutls_session_t session)
112 {
113   /* get the new random values */
114   memcpy (session->internals.resumed_security_parameters.server_random,
115           session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
116   memcpy (session->internals.resumed_security_parameters.client_random,
117           session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);
118
119   /* keep the ciphersuite and compression 
120    * That is because the client must see these in our
121    * hello message.
122    */
123   memcpy (session->security_parameters.current_cipher_suite.suite,
124           session->internals.resumed_security_parameters.current_cipher_suite.
125           suite, 2);
126   session->internals.compression_method = session->internals.resumed_compression_method;
127
128   _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
129                                   &session->
130                                   internals.resumed_security_parameters.current_cipher_suite);
131   _gnutls_epoch_set_compression (session, EPOCH_NEXT,
132                                  session->
133                                  internals.resumed_compression_method);
134
135   /* or write_compression_algorithm
136    * they are the same
137    */
138
139   session->security_parameters.entity =
140     session->internals.resumed_security_parameters.entity;
141
142   _gnutls_set_current_version (session,
143                                session->internals.resumed_security_parameters.
144                                version);
145
146   session->security_parameters.cert_type =
147     session->internals.resumed_security_parameters.cert_type;
148
149   memcpy (session->security_parameters.session_id,
150           session->internals.resumed_security_parameters.session_id,
151           sizeof (session->security_parameters.session_id));
152   session->security_parameters.session_id_size =
153     session->internals.resumed_security_parameters.session_id_size;
154
155 }
156
157 void
158 _gnutls_set_server_random (gnutls_session_t session, uint8_t * rnd)
159 {
160   memcpy (session->security_parameters.server_random, rnd,
161           GNUTLS_RANDOM_SIZE);
162 }
163
164 void
165 _gnutls_set_client_random (gnutls_session_t session, uint8_t * rnd)
166 {
167   memcpy (session->security_parameters.client_random, rnd,
168           GNUTLS_RANDOM_SIZE);
169 }
170
171 /* Calculate The SSL3 Finished message
172  */
173 #define SSL3_CLIENT_MSG "CLNT"
174 #define SSL3_SERVER_MSG "SRVR"
175 #define SSL_MSG_LEN 4
176 static int
177 _gnutls_ssl3_finished (gnutls_session_t session, int type, opaque * ret)
178 {
179   const int siz = SSL_MSG_LEN;
180   digest_hd_st td_md5;
181   digest_hd_st td_sha;
182   const char *mesg;
183   int rc;
184
185   if (session->security_parameters.handshake_mac_handle_type ==
186       HANDSHAKE_MAC_TYPE_10)
187     {
188       rc =
189         _gnutls_hash_copy (&td_md5,
190                            &session->internals.handshake_mac_handle.tls10.
191                            md5);
192       if (rc < 0)
193         {
194           gnutls_assert ();
195           return rc;
196         }
197
198       rc =
199         _gnutls_hash_copy (&td_sha,
200                            &session->internals.handshake_mac_handle.tls10.
201                            sha);
202       if (rc < 0)
203         {
204           gnutls_assert ();
205           _gnutls_hash_deinit (&td_md5, NULL);
206           return rc;
207         }
208     }
209   else
210     {
211       gnutls_assert ();
212       return GNUTLS_E_INTERNAL_ERROR;
213     }
214
215   if (type == GNUTLS_SERVER)
216     {
217       mesg = SSL3_SERVER_MSG;
218     }
219   else
220     {
221       mesg = SSL3_CLIENT_MSG;
222     }
223
224   _gnutls_hash (&td_md5, mesg, siz);
225   _gnutls_hash (&td_sha, mesg, siz);
226
227   _gnutls_mac_deinit_ssl3_handshake (&td_md5, ret,
228                                      session->
229                                      security_parameters.master_secret,
230                                      GNUTLS_MASTER_SIZE);
231   _gnutls_mac_deinit_ssl3_handshake (&td_sha, &ret[16],
232                                      session->
233                                      security_parameters.master_secret,
234                                      GNUTLS_MASTER_SIZE);
235
236   return 0;
237 }
238
239 /* Hash the handshake messages as required by TLS 1.0
240  */
241 #define SERVER_MSG "server finished"
242 #define CLIENT_MSG "client finished"
243 #define TLS_MSG_LEN 15
244 static int
245 _gnutls_finished (gnutls_session_t session, int type, void *ret)
246 {
247   const int siz = TLS_MSG_LEN;
248   opaque concat[MAX_HASH_SIZE + 16 /*MD5 */ ];
249   size_t len = 20 + 16;
250   const char *mesg;
251   digest_hd_st td_md5;
252   digest_hd_st td_sha;
253   int rc;
254
255   if (session->security_parameters.handshake_mac_handle_type ==
256       HANDSHAKE_MAC_TYPE_10)
257     {
258       rc =
259         _gnutls_hash_copy (&td_md5,
260                            &session->internals.handshake_mac_handle.tls10.
261                            md5);
262       if (rc < 0)
263         {
264           gnutls_assert ();
265           return rc;
266         }
267
268       rc =
269         _gnutls_hash_copy (&td_sha,
270                            &session->internals.handshake_mac_handle.tls10.
271                            sha);
272       if (rc < 0)
273         {
274           gnutls_assert ();
275           _gnutls_hash_deinit (&td_md5, NULL);
276           return rc;
277         }
278
279       _gnutls_hash_deinit (&td_md5, concat);
280       _gnutls_hash_deinit (&td_sha, &concat[16]);
281     }
282   else if (session->security_parameters.handshake_mac_handle_type ==
283            HANDSHAKE_MAC_TYPE_12)
284     {
285       rc =
286         _gnutls_hash_copy (&td_sha,
287                            &session->internals.handshake_mac_handle.tls12.
288                            sha256);
289       if (rc < 0)
290         {
291           gnutls_assert ();
292           return rc;
293         }
294
295       _gnutls_hash_deinit (&td_sha, concat);
296       len = _gnutls_hash_get_algo_len (td_sha.algorithm);
297     }
298
299   if (type == GNUTLS_SERVER)
300     {
301       mesg = SERVER_MSG;
302     }
303   else
304     {
305       mesg = CLIENT_MSG;
306     }
307
308   return _gnutls_PRF (session, session->security_parameters.master_secret,
309                       GNUTLS_MASTER_SIZE, mesg, siz, concat, len, 12, ret);
310 }
311
312 /* this function will produce GNUTLS_RANDOM_SIZE==32 bytes of random data
313  * and put it to dst.
314  */
315 int
316 _gnutls_tls_create_random (opaque * dst)
317 {
318   uint32_t tim;
319   int ret;
320
321   /* Use weak random numbers for the most of the
322    * buffer except for the first 4 that are the
323    * system's time.
324    */
325
326   tim = gnutls_time (NULL);
327   /* generate server random value */
328   _gnutls_write_uint32 (tim, dst);
329
330   ret = _gnutls_rnd (GNUTLS_RND_NONCE, &dst[4], GNUTLS_RANDOM_SIZE - 4);
331   if (ret < 0)
332     {
333       gnutls_assert ();
334       return ret;
335     }
336
337   return 0;
338 }
339
340 /* returns the 0 on success or a negative value.
341  */
342 int
343 _gnutls_negotiate_version (gnutls_session_t session,
344                            gnutls_protocol_t adv_version)
345 {
346   int ret;
347
348   /* if we do not support that version  */
349   if (_gnutls_version_is_supported (session, adv_version) == 0)
350     {
351       /* If he requested something we do not support
352        * then we send him the highest we support.
353        */
354       ret = _gnutls_version_max (session);
355       if (ret == GNUTLS_VERSION_UNKNOWN)
356         {
357           /* this check is not really needed.
358            */
359           gnutls_assert ();
360           return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
361         }
362     }
363   else
364     {
365       ret = adv_version;
366     }
367
368   _gnutls_set_current_version (session, ret);
369
370   return ret;
371 }
372
373 int
374 _gnutls_user_hello_func (gnutls_session_t session,
375                          gnutls_protocol_t adv_version)
376 {
377   int ret;
378
379   if (session->internals.user_hello_func != NULL)
380     {
381       ret = session->internals.user_hello_func (session);
382       if (ret < 0)
383         {
384           gnutls_assert ();
385           return ret;
386         }
387       /* Here we need to renegotiate the version since the callee might
388        * have disabled some TLS versions.
389        */
390       ret = _gnutls_negotiate_version (session, adv_version);
391       if (ret < 0)
392         {
393           gnutls_assert ();
394           return ret;
395         }
396     }
397   return 0;
398 }
399
400 /* Read a client hello packet. 
401  * A client hello must be a known version client hello
402  * or version 2.0 client hello (only for compatibility
403  * since SSL version 2.0 is not supported).
404  */
405 static int
406 _gnutls_read_client_hello (gnutls_session_t session, opaque * data,
407                            int datalen)
408 {
409   uint8_t session_id_len;
410   int pos = 0, ret;
411   uint16_t suite_size, comp_size;
412   gnutls_protocol_t adv_version;
413   int neg_version;
414   int len = datalen;
415   opaque rnd[GNUTLS_RANDOM_SIZE], *suite_ptr, *comp_ptr, *session_id;
416
417   if (session->internals.v2_hello != 0)
418     {                           /* version 2.0 */
419       return _gnutls_read_client_hello_v2 (session, data, datalen);
420     }
421   DECR_LEN (len, 2);
422
423   _gnutls_handshake_log ("HSK[%p]: Client's version: %d.%d\n", session,
424                          data[pos], data[pos + 1]);
425
426   adv_version = _gnutls_version_get (data[pos], data[pos + 1]);
427   set_adv_version (session, data[pos], data[pos + 1]);
428   pos += 2;
429
430   neg_version = _gnutls_negotiate_version (session, adv_version);
431   if (neg_version < 0)
432     {
433       gnutls_assert ();
434       return neg_version;
435     }
436
437   /* Read client random value.
438    */
439   DECR_LEN (len, GNUTLS_RANDOM_SIZE);
440   _gnutls_set_client_random (session, &data[pos]);
441   pos += GNUTLS_RANDOM_SIZE;
442
443   _gnutls_tls_create_random (rnd);
444   _gnutls_set_server_random (session, rnd);
445
446   session->security_parameters.timestamp = gnutls_time (NULL);
447
448   DECR_LEN (len, 1);
449   session_id_len = data[pos++];
450
451   /* RESUME SESSION 
452    */
453   if (session_id_len > TLS_MAX_SESSION_ID_SIZE)
454     {
455       gnutls_assert ();
456       return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
457     }
458   DECR_LEN (len, session_id_len);
459
460   session_id = &data[pos];
461   ret = _gnutls_server_restore_session (session, session_id, session_id_len);
462   pos += session_id_len;
463
464   if (ret == 0)
465     {                           /* resumed using default TLS resumption! */
466       /* Parse only the safe renegotiation extension
467        * We don't want to parse any other extensions since
468        * we don't want new extension values to overwrite the
469        * resumed ones.
470        */
471
472       /* move forward to extensions */
473       DECR_LEN (len, 2);
474       suite_size = _gnutls_read_uint16 (&data[pos]);
475       pos += 2;
476
477       DECR_LEN (len, suite_size);
478       pos += suite_size;
479
480       DECR_LEN (len, 1);
481       comp_size = data[pos++];  /* z is the number of compression methods */
482       DECR_LEN (len, comp_size);
483       pos += comp_size;
484
485       ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
486                                       &data[pos], len);
487       if (ret < 0)
488         {
489           gnutls_assert ();
490           return ret;
491         }
492
493       resume_copy_required_values (session);
494       session->internals.resumed = RESUME_TRUE;
495
496       return _gnutls_user_hello_func (session, adv_version);
497     }
498   else
499     {
500       _gnutls_generate_session_id (session->security_parameters.session_id,
501                                    &session->
502                                    security_parameters.session_id_size);
503
504       session->internals.resumed = RESUME_FALSE;
505     }
506
507   /* Remember ciphersuites for later
508    */
509   DECR_LEN (len, 2);
510   suite_size = _gnutls_read_uint16 (&data[pos]);
511   pos += 2;
512
513   DECR_LEN (len, suite_size);
514   suite_ptr = &data[pos];
515   pos += suite_size;
516
517   /* Point to the compression methods
518    */
519   DECR_LEN (len, 1);
520   comp_size = data[pos++];      /* z is the number of compression methods */
521
522   DECR_LEN (len, comp_size);
523   comp_ptr = &data[pos];
524   pos += comp_size;
525
526   /* Parse the extensions (if any)
527    *
528    * Unconditionally try to parse extensions; safe renegotiation uses them in
529    * sslv3 and higher, even though sslv3 doesn't officially support them.
530    */
531   ret = _gnutls_parse_extensions (session, GNUTLS_EXT_APPLICATION,
532                                   &data[pos], len);
533   /* len is the rest of the parsed length */
534   if (ret < 0)
535     {
536       gnutls_assert ();
537       return ret;
538     }
539
540   ret = _gnutls_user_hello_func (session, adv_version);
541   if (ret < 0)
542     {
543       gnutls_assert ();
544       return ret;
545     }
546
547   ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
548                                   &data[pos], len);
549   if (ret < 0)
550     {
551       gnutls_assert ();
552       return ret;
553     }
554
555   ret = _gnutls_parse_extensions (session, GNUTLS_EXT_TLS, &data[pos], len);
556   if (ret < 0)
557     {
558       gnutls_assert ();
559       return ret;
560     }
561
562   /* resumed by session_ticket extension */
563   if (session->internals.resumed == RESUME_TRUE)
564     {
565       /* to indicate the client that the current session is resumed */
566       memcpy (session->internals.resumed_security_parameters.session_id,
567               session_id, session_id_len);
568       session->internals.resumed_security_parameters.session_id_size =
569         session_id_len;
570
571       session->internals.resumed_security_parameters.max_record_recv_size =
572         session->security_parameters.max_record_recv_size;
573       session->internals.resumed_security_parameters.max_record_send_size =
574         session->security_parameters.max_record_send_size;
575
576       resume_copy_required_values (session);
577
578       return _gnutls_user_hello_func (session, adv_version);
579     }
580
581   /* select an appropriate cipher suite
582    */
583   ret = _gnutls_server_select_suite (session, suite_ptr, suite_size);
584   if (ret < 0)
585     {
586       gnutls_assert ();
587       return ret;
588     }
589
590   /* select appropriate compression method */
591   ret = _gnutls_server_select_comp_method (session, comp_ptr, comp_size);
592   if (ret < 0)
593     {
594       gnutls_assert ();
595       return ret;
596     }
597
598   return 0;
599 }
600
601 /* here we hash all pending data. 
602  */
603 inline static int
604 _gnutls_handshake_hash_pending (gnutls_session_t session)
605 {
606   size_t siz;
607   int ret;
608   opaque *data;
609
610   if (session->internals.handshake_mac_handle_init == 0)
611     {
612       gnutls_assert ();
613       return GNUTLS_E_INTERNAL_ERROR;
614     }
615
616   /* We check if there are pending data to hash.
617    */
618   if ((ret = _gnutls_handshake_buffer_get_ptr (session, &data, &siz)) < 0)
619     {
620       gnutls_assert ();
621       return ret;
622     }
623
624   if (siz > 0)
625     {
626       if (session->security_parameters.handshake_mac_handle_type ==
627           HANDSHAKE_MAC_TYPE_10)
628         {
629           _gnutls_hash (&session->internals.handshake_mac_handle.tls10.sha,
630                         data, siz);
631           _gnutls_hash (&session->internals.handshake_mac_handle.tls10.md5,
632                         data, siz);
633         }
634       else if (session->security_parameters.handshake_mac_handle_type ==
635                HANDSHAKE_MAC_TYPE_12)
636         {
637           _gnutls_hash (&session->internals.handshake_mac_handle.tls12.sha256,
638                         data, siz);
639           _gnutls_hash (&session->internals.handshake_mac_handle.tls12.sha1,
640                         data, siz);
641         }
642     }
643
644   _gnutls_handshake_buffer_empty (session);
645
646   return 0;
647 }
648
649
650 /* This is to be called after sending CHANGE CIPHER SPEC packet
651  * and initializing encryption. This is the first encrypted message
652  * we send.
653  */
654 static int
655 _gnutls_send_finished (gnutls_session_t session, int again)
656 {
657   mbuffer_st *bufel;
658   opaque *data;
659   int ret;
660   size_t vdata_size = 0;
661
662   if (again == 0)
663     {
664       bufel =
665         _gnutls_handshake_alloc (MAX_VERIFY_DATA_SIZE, MAX_VERIFY_DATA_SIZE);
666       if (bufel == NULL)
667         {
668           gnutls_assert ();
669           return GNUTLS_E_MEMORY_ERROR;
670         }
671       data = _mbuffer_get_udata_ptr (bufel);
672
673       /* This is needed in order to hash all the required
674        * messages.
675        */
676       if ((ret = _gnutls_handshake_hash_pending (session)) < 0)
677         {
678           gnutls_assert ();
679           return ret;
680         }
681
682       if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
683         {
684           ret =
685             _gnutls_ssl3_finished (session,
686                                    session->security_parameters.entity, data);
687           _mbuffer_set_udata_size (bufel, 36);
688         }
689       else
690         {                       /* TLS 1.0+ */
691           ret = _gnutls_finished (session,
692                                   session->security_parameters.entity, data);
693           _mbuffer_set_udata_size (bufel, 12);
694         }
695
696       if (ret < 0)
697         {
698           gnutls_assert ();
699           return ret;
700         }
701
702       vdata_size = _mbuffer_get_udata_size (bufel);
703
704       if (session->internals.finished_func)
705         session->internals.finished_func (session, data, vdata_size);
706
707       ret = _gnutls_ext_sr_finished (session, data, vdata_size, 0);
708       if (ret < 0)
709         {
710           gnutls_assert ();
711           return ret;
712         }
713
714       if ((session->internals.resumed == RESUME_FALSE
715            && session->security_parameters.entity == GNUTLS_CLIENT)
716           || (session->internals.resumed == RESUME_TRUE
717               && session->security_parameters.entity == GNUTLS_SERVER))
718         {
719           /* if we are a client not resuming - or we are a server resuming */
720           _gnutls_handshake_log ("HSK[%p]: recording tls-unique CB (send)\n",
721                                  session);
722           memcpy (session->internals.cb_tls_unique, data, vdata_size);
723           session->internals.cb_tls_unique_len = vdata_size;
724         }
725
726       ret =
727         _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_FINISHED);
728     }
729   else
730     {
731       ret = _gnutls_send_handshake (session, NULL, GNUTLS_HANDSHAKE_FINISHED);
732     }
733
734   return ret;
735 }
736
737 /* This is to be called after sending our finished message. If everything
738  * went fine we have negotiated a secure connection 
739  */
740 static int
741 _gnutls_recv_finished (gnutls_session_t session)
742 {
743   uint8_t data[MAX_VERIFY_DATA_SIZE], *vrfy;
744   int data_size;
745   int ret;
746   int vrfysize;
747
748   ret =
749     _gnutls_recv_handshake (session, &vrfy, &vrfysize,
750                             GNUTLS_HANDSHAKE_FINISHED, MANDATORY_PACKET);
751   if (ret < 0)
752     {
753       ERR ("recv finished int", ret);
754       gnutls_assert ();
755       return ret;
756     }
757
758
759   if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
760     {
761       data_size = 36;
762     }
763   else
764     {
765       data_size = 12;
766     }
767
768   if (vrfysize != data_size)
769     {
770       gnutls_assert ();
771       gnutls_free (vrfy);
772       return GNUTLS_E_ERROR_IN_FINISHED_PACKET;
773     }
774
775   if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
776     {
777       ret =
778         _gnutls_ssl3_finished (session,
779                                (session->security_parameters.entity + 1) % 2,
780                                data);
781     }
782   else
783     {                           /* TLS 1.0 */
784       ret =
785         _gnutls_finished (session,
786                           (session->security_parameters.entity +
787                            1) % 2, data);
788     }
789
790   if (ret < 0)
791     {
792       gnutls_assert ();
793       gnutls_free (vrfy);
794       return ret;
795     }
796
797   ret = memcmp (vrfy, data, data_size);
798   gnutls_free (vrfy);
799   
800   if (ret != 0)
801     {
802       gnutls_assert ();
803       return GNUTLS_E_ERROR_IN_FINISHED_PACKET;
804     }
805
806   ret = _gnutls_ext_sr_finished (session, data, data_size, 1);
807   if (ret < 0)
808     {
809       gnutls_assert ();
810       return ret;
811     }
812
813   if ((session->internals.resumed == RESUME_TRUE
814        && session->security_parameters.entity == GNUTLS_CLIENT)
815       || (session->internals.resumed == RESUME_FALSE
816           && session->security_parameters.entity == GNUTLS_SERVER))
817     {
818       /* if we are a client resuming - or we are a server not resuming */
819       _gnutls_handshake_log ("HSK[%p]: recording tls-unique CB (recv)\n",
820                              session);
821       memcpy (session->internals.cb_tls_unique, data, data_size);
822       session->internals.cb_tls_unique_len = data_size;
823     }
824
825   session->internals.initial_negotiation_completed = 1;
826
827   return 0;
828 }
829
830 /* returns PK_RSA if the given cipher suite list only supports,
831  * RSA algorithms, PK_DSA if DSS, and PK_ANY for both or PK_NONE for none.
832  */
833 static int
834 _gnutls_server_find_pk_algos_in_ciphersuites (const opaque *
835                                               data, unsigned int datalen)
836 {
837   unsigned int j;
838   gnutls_pk_algorithm_t algo = GNUTLS_PK_NONE, prev_algo = 0;
839   gnutls_kx_algorithm_t kx;
840   cipher_suite_st cs;
841
842   if (datalen % 2 != 0)
843     {
844       gnutls_assert ();
845       return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
846     }
847
848   for (j = 0; j < datalen; j += 2)
849     {
850       memcpy (&cs.suite, &data[j], 2);
851       kx = _gnutls_cipher_suite_get_kx_algo (&cs);
852
853       if (_gnutls_map_kx_get_cred (kx, 1) == GNUTLS_CRD_CERTIFICATE)
854         {
855           algo = _gnutls_map_pk_get_pk (kx);
856
857           if (algo != prev_algo && prev_algo != 0)
858             return GNUTLS_PK_ANY;
859           prev_algo = algo;
860         }
861     }
862
863   return algo;
864 }
865
866 /* This selects the best supported ciphersuite from the given ones. Then
867  * it adds the suite to the session and performs some checks.
868  */
869 int
870 _gnutls_server_select_suite (gnutls_session_t session, opaque * data,
871                              int datalen)
872 {
873   int x, i, j;
874   cipher_suite_st *ciphers, cs;
875   int retval, err;
876   gnutls_pk_algorithm_t pk_algo;        /* will hold the pk algorithms
877                                          * supported by the peer.
878                                          */
879
880   /* First, check for safe renegotiation SCSV.
881    */
882   if (session->internals.priorities.sr != SR_DISABLED)
883     {
884       int offset;
885
886       for (offset = 0; offset < datalen; offset += 2)
887         {
888           /* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */
889           if (data[offset] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR &&
890               data[offset + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR)
891             {
892               _gnutls_handshake_log
893                 ("HSK[%p]: Received safe renegotiation CS\n", session);
894               retval = _gnutls_ext_sr_recv_cs (session);
895               if (retval < 0)
896                 {
897                   gnutls_assert ();
898                   return retval;
899                 }
900               break;
901             }
902         }
903     }
904
905   pk_algo = _gnutls_server_find_pk_algos_in_ciphersuites (data, datalen);
906
907   x = _gnutls_supported_ciphersuites (session, &ciphers);
908   if (x < 0)
909     {                           /* the case x==0 is handled within the function. */
910       gnutls_assert ();
911       return x;
912     }
913
914   /* Here we remove any ciphersuite that does not conform
915    * the certificate requested, or to the
916    * authentication requested (e.g. SRP).
917    */
918   x = _gnutls_remove_unwanted_ciphersuites (session, &ciphers, x, pk_algo);
919   if (x <= 0)
920     {
921       gnutls_assert ();
922       gnutls_free (ciphers);
923       if (x < 0)
924         return x;
925       else
926         return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
927     }
928
929   /* Data length should be zero mod 2 since
930    * every ciphersuite is 2 bytes. (this check is needed
931    * see below).
932    */
933   if (datalen % 2 != 0)
934     {
935       gnutls_assert ();
936       return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
937     }
938 #ifdef HANDSHAKE_DEBUG
939
940   _gnutls_handshake_log ("HSK[%p]: Requested cipher suites: \n", session);
941   for (j = 0; j < datalen; j += 2)
942     {
943       memcpy (&cs.suite, &data[j], 2);
944       _gnutls_handshake_log ("\t%s\n", _gnutls_cipher_suite_get_name (&cs));
945     }
946   _gnutls_handshake_log ("HSK[%p]: Supported cipher suites: \n", session);
947   for (j = 0; j < x; j++)
948     _gnutls_handshake_log ("\t%s\n",
949                            _gnutls_cipher_suite_get_name (&ciphers[j]));
950 #endif
951   memset (session->security_parameters.current_cipher_suite.suite, '\0', 2);
952
953   retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;
954
955   for (j = 0; j < datalen; j += 2)
956     {
957       for (i = 0; i < x; i++)
958         {
959           if (memcmp (ciphers[i].suite, &data[j], 2) == 0)
960             {
961               memcpy (&cs.suite, &data[j], 2);
962
963               _gnutls_handshake_log
964                 ("HSK[%p]: Selected cipher suite: %s\n", session,
965                  _gnutls_cipher_suite_get_name (&cs));
966               memcpy (session->security_parameters.current_cipher_suite.suite,
967                       ciphers[i].suite, 2);
968               _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
969                                               &session->
970                                               security_parameters.current_cipher_suite);
971
972
973               retval = 0;
974               goto finish;
975             }
976         }
977     }
978
979 finish:
980   gnutls_free (ciphers);
981
982   if (retval != 0)
983     {
984       gnutls_assert ();
985       return retval;
986     }
987
988   /* check if the credentials (username, public key etc.) are ok
989    */
990   if (_gnutls_get_kx_cred
991       (session,
992        _gnutls_cipher_suite_get_kx_algo (&session->
993                                          security_parameters.current_cipher_suite),
994        &err) == NULL && err != 0)
995     {
996       gnutls_assert ();
997       return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
998     }
999
1000
1001   /* set the mod_auth_st to the appropriate struct
1002    * according to the KX algorithm. This is needed since all the
1003    * handshake functions are read from there;
1004    */
1005   session->internals.auth_struct =
1006     _gnutls_kx_auth_struct (_gnutls_cipher_suite_get_kx_algo
1007                             (&session->
1008                              security_parameters.current_cipher_suite));
1009   if (session->internals.auth_struct == NULL)
1010     {
1011
1012       _gnutls_handshake_log
1013         ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
1014          session);
1015       gnutls_assert ();
1016       return GNUTLS_E_INTERNAL_ERROR;
1017     }
1018
1019   return 0;
1020
1021 }
1022
1023
1024 /* This selects the best supported compression method from the ones provided 
1025  */
1026 static int
1027 _gnutls_server_select_comp_method (gnutls_session_t session,
1028                                    opaque * data, int datalen)
1029 {
1030   int x, i, j;
1031   uint8_t *comps;
1032
1033   x = _gnutls_supported_compression_methods (session, &comps);
1034   if (x < 0)
1035     {
1036       gnutls_assert ();
1037       return x;
1038     }
1039
1040   memset (&session->internals.compression_method, 0,
1041           sizeof (gnutls_compression_method_t));
1042
1043   for (j = 0; j < datalen; j++)
1044     {
1045       for (i = 0; i < x; i++)
1046         {
1047           if (comps[i] == data[j])
1048             {
1049               gnutls_compression_method_t method =
1050                 _gnutls_compression_get_id (comps[i]);
1051
1052               session->internals.compression_method = method;
1053               gnutls_free (comps);
1054
1055               _gnutls_epoch_set_compression (session, EPOCH_NEXT, method);
1056
1057               _gnutls_handshake_log
1058                 ("HSK[%p]: Selected Compression Method: %s\n", session,
1059                  gnutls_compression_get_name (session->
1060                                               internals.compression_method));
1061
1062
1063               return 0;
1064             }
1065         }
1066     }
1067
1068   /* we were not able to find a compatible compression
1069    * algorithm
1070    */
1071   gnutls_free (comps);
1072   gnutls_assert ();
1073   return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1074
1075 }
1076
1077 /* This function sends an empty handshake packet. (like hello request).
1078  * If the previous _gnutls_send_empty_handshake() returned
1079  * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED, then it must be called again 
1080  * (until it returns ok), with NULL parameters.
1081  */
1082 static int
1083 _gnutls_send_empty_handshake (gnutls_session_t session,
1084                               gnutls_handshake_description_t type, int again)
1085 {
1086   mbuffer_st *bufel;
1087
1088   if (again == 0)
1089     {
1090       bufel = _gnutls_handshake_alloc (0, 0);
1091       if (bufel == NULL)
1092         {
1093           gnutls_assert ();
1094           return GNUTLS_E_MEMORY_ERROR;
1095         }
1096     }
1097   else
1098     bufel = NULL;
1099
1100   return _gnutls_send_handshake (session, bufel, type);
1101 }
1102
1103
1104 /* This function will hash the handshake message we sent.
1105  */
1106 static int
1107 _gnutls_handshake_hash_add_sent (gnutls_session_t session,
1108                                  gnutls_handshake_description_t type,
1109                                  opaque * dataptr, uint32_t datalen)
1110 {
1111   int ret;
1112
1113   if (session->security_parameters.entity == GNUTLS_CLIENT
1114       && type == GNUTLS_HANDSHAKE_CLIENT_HELLO)
1115     {
1116       /* do not hash immediatelly since the hash has not yet been initialized */
1117       if ((ret =
1118            _gnutls_handshake_buffer_put (session, dataptr, datalen)) < 0)
1119         {
1120           gnutls_assert ();
1121           return ret;
1122         }
1123       return 0;
1124     }
1125
1126   if ((ret = _gnutls_handshake_hash_pending (session)) < 0)
1127     {
1128       gnutls_assert ();
1129       return ret;
1130     }
1131
1132   if (type != GNUTLS_HANDSHAKE_HELLO_REQUEST)
1133     {
1134       if (session->security_parameters.handshake_mac_handle_type ==
1135           HANDSHAKE_MAC_TYPE_10)
1136         {
1137           _gnutls_hash (&session->internals.handshake_mac_handle.tls10.sha,
1138                         dataptr, datalen);
1139           _gnutls_hash (&session->internals.handshake_mac_handle.tls10.md5,
1140                         dataptr, datalen);
1141         }
1142       else if (session->security_parameters.handshake_mac_handle_type ==
1143                HANDSHAKE_MAC_TYPE_12)
1144         {
1145           _gnutls_hash (&session->internals.handshake_mac_handle.tls12.sha256,
1146                         dataptr, datalen);
1147           _gnutls_hash (&session->internals.handshake_mac_handle.tls12.sha1,
1148                         dataptr, datalen);
1149         }
1150     }
1151
1152   return 0;
1153 }
1154
1155
1156 /* This function sends a handshake message of type 'type' containing the
1157  * data specified here. If the previous _gnutls_send_handshake() returned
1158  * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED, then it must be called again 
1159  * (until it returns ok), with NULL parameters.
1160  */
1161 int
1162 _gnutls_send_handshake (gnutls_session_t session, mbuffer_st * bufel,
1163                         gnutls_handshake_description_t type)
1164 {
1165   int ret;
1166   uint8_t *data;
1167   uint32_t datasize;
1168   int pos = 0;
1169
1170   if (bufel == NULL)
1171     {
1172       /* we are resuming a previously interrupted
1173        * send.
1174        */
1175       ret = _gnutls_handshake_io_write_flush (session);
1176       return ret;
1177
1178     }
1179
1180   /* first run */
1181   data = _mbuffer_get_uhead_ptr (bufel);
1182   datasize =
1183     _mbuffer_get_udata_size (bufel) + _mbuffer_get_uhead_size (bufel);
1184
1185   data[pos++] = (uint8_t) type;
1186   _gnutls_write_uint24 (_mbuffer_get_udata_size (bufel), &data[pos]);
1187   pos += 3;
1188
1189   _gnutls_handshake_log ("HSK[%p]: %s was sent [%ld bytes]\n",
1190                          session, _gnutls_handshake2str (type),
1191                          (long) datasize);
1192
1193
1194   /* Here we keep the handshake messages in order to hash them...
1195    */
1196   if (type != GNUTLS_HANDSHAKE_HELLO_REQUEST)
1197     if ((ret =
1198          _gnutls_handshake_hash_add_sent (session, type, data, datasize)) < 0)
1199       {
1200         gnutls_assert ();
1201         gnutls_free (bufel);
1202         return ret;
1203       }
1204
1205   session->internals.last_handshake_out = type;
1206
1207   _gnutls_handshake_io_cache_int (session, type, bufel);
1208
1209   switch (type)
1210     {
1211     case GNUTLS_HANDSHAKE_CERTIFICATE_PKT:     /* this one is followed by ServerHelloDone
1212                                                  * or ClientKeyExchange always.
1213                                                  */
1214     case GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE: /* as above */
1215     case GNUTLS_HANDSHAKE_SERVER_HELLO:        /* as above */
1216     case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST: /* as above */
1217     case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET:  /* followed by ChangeCipherSpec */
1218
1219       /* now for client Certificate, ClientKeyExchange and
1220        * CertificateVerify are always followed by ChangeCipherSpec
1221        */
1222     case GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY:
1223     case GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE:
1224       ret = 0;
1225       break;
1226     default:
1227       /* send cached messages */
1228       ret = _gnutls_handshake_io_write_flush (session);
1229       break;
1230     }
1231
1232   return ret;
1233 }
1234
1235 /* This function will read the handshake header and return it to the caller. If the
1236  * received handshake packet is not the one expected then it buffers the header, and
1237  * returns UNEXPECTED_HANDSHAKE_PACKET.
1238  *
1239  * FIXME: This function is complex.
1240  */
1241 #define SSL2_HEADERS 1
1242 static int
1243 _gnutls_recv_handshake_header (gnutls_session_t session,
1244                                gnutls_handshake_description_t type,
1245                                gnutls_handshake_description_t * recv_type)
1246 {
1247   int ret;
1248   uint32_t length32 = 0;
1249   uint8_t *dataptr = NULL;      /* for realloc */
1250   size_t handshake_header_size = HANDSHAKE_HEADER_SIZE;
1251
1252   /* if we have data into the buffer then return them, do not read the next packet.
1253    * In order to return we need a full TLS handshake header, or in case of a version 2
1254    * packet, then we return the first byte.
1255    */
1256   if (session->internals.handshake_header_buffer.header_size ==
1257       handshake_header_size || (session->internals.v2_hello != 0
1258                                 && type == GNUTLS_HANDSHAKE_CLIENT_HELLO
1259                                 && session->internals.handshake_header_buffer.
1260                                 packet_length > 0))
1261     {
1262
1263       *recv_type = session->internals.handshake_header_buffer.recv_type;
1264
1265       if (*recv_type != type)
1266         {
1267           gnutls_assert ();
1268           _gnutls_handshake_log
1269             ("HSK[%p]: Handshake type mismatch (under attack?)\n", session);
1270           return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
1271         }
1272
1273       return session->internals.handshake_header_buffer.packet_length;
1274     }
1275
1276   /* Note: SSL2_HEADERS == 1 */
1277
1278   dataptr = session->internals.handshake_header_buffer.header;
1279
1280   /* If we haven't already read the handshake headers.
1281    */
1282   if (session->internals.handshake_header_buffer.header_size < SSL2_HEADERS)
1283     {
1284       ret =
1285         _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE,
1286                                        type, dataptr, SSL2_HEADERS);
1287
1288       if (ret < 0)
1289         {
1290           return ret;
1291         }
1292
1293       /* The case ret==0 is caught here.
1294        */
1295       if (ret != SSL2_HEADERS)
1296         {
1297           gnutls_assert ();
1298           return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1299         }
1300       session->internals.handshake_header_buffer.header_size = SSL2_HEADERS;
1301     }
1302
1303   if (session->internals.v2_hello == 0
1304       || type != GNUTLS_HANDSHAKE_CLIENT_HELLO)
1305     {
1306       ret =
1307         _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE,
1308                                        type,
1309                                        &dataptr
1310                                        [session->
1311                                         internals.handshake_header_buffer.
1312                                         header_size],
1313                                        HANDSHAKE_HEADER_SIZE -
1314                                        session->
1315                                        internals.handshake_header_buffer.
1316                                        header_size);
1317       if (ret <= 0)
1318         {
1319           gnutls_assert ();
1320           return (ret < 0) ? ret : GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1321         }
1322       if ((size_t) ret !=
1323           HANDSHAKE_HEADER_SIZE -
1324           session->internals.handshake_header_buffer.header_size)
1325         {
1326           gnutls_assert ();
1327           return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1328         }
1329       *recv_type = dataptr[0];
1330
1331       /* we do not use DECR_LEN because we know
1332        * that the packet has enough data.
1333        */
1334       length32 = _gnutls_read_uint24 (&dataptr[1]);
1335       handshake_header_size = HANDSHAKE_HEADER_SIZE;
1336
1337       _gnutls_handshake_log ("HSK[%p]: %s was received [%ld bytes]\n",
1338                              session, _gnutls_handshake2str (dataptr[0]),
1339                              (long int) (length32 + HANDSHAKE_HEADER_SIZE));
1340
1341     }
1342   else
1343     {                           /* v2 hello */
1344       length32 = session->internals.v2_hello - SSL2_HEADERS;    /* we've read the first byte */
1345
1346       handshake_header_size = SSL2_HEADERS;     /* we've already read one byte */
1347
1348       *recv_type = dataptr[0];
1349
1350       _gnutls_handshake_log ("HSK[%p]: %s(v2) was received [%ld bytes]\n",
1351                              session, _gnutls_handshake2str (*recv_type),
1352                              (long int) (length32 + handshake_header_size));
1353
1354       if (*recv_type != GNUTLS_HANDSHAKE_CLIENT_HELLO)
1355         {                       /* it should be one or nothing */
1356           gnutls_assert ();
1357           return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
1358         }
1359     }
1360
1361   /* put the packet into the buffer */
1362   session->internals.handshake_header_buffer.header_size =
1363     handshake_header_size;
1364   session->internals.handshake_header_buffer.packet_length = length32;
1365   session->internals.handshake_header_buffer.recv_type = *recv_type;
1366
1367   if (*recv_type != type)
1368     {
1369       gnutls_assert ();
1370       return GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
1371     }
1372
1373   return length32;
1374 }
1375
1376 #define _gnutls_handshake_header_buffer_clear( session) session->internals.handshake_header_buffer.header_size = 0
1377
1378
1379
1380 /* This function will hash the handshake headers and the
1381  * handshake data.
1382  */
1383 static int
1384 _gnutls_handshake_hash_add_recvd (gnutls_session_t session,
1385                                   gnutls_handshake_description_t recv_type,
1386                                   opaque * header, uint16_t header_size,
1387                                   opaque * dataptr, uint32_t datalen)
1388 {
1389   int ret;
1390
1391   /* The idea here is to hash the previous message we received,
1392    * and add the one we just received into the handshake_hash_buffer.
1393    */
1394   if ((session->security_parameters.entity == GNUTLS_SERVER
1395        || recv_type != GNUTLS_HANDSHAKE_SERVER_HELLO)
1396       && (session->security_parameters.entity == GNUTLS_CLIENT
1397           || recv_type != GNUTLS_HANDSHAKE_CLIENT_HELLO))
1398     {
1399       if ((ret = _gnutls_handshake_hash_pending (session)) < 0)
1400         {
1401           gnutls_assert ();
1402           return ret;
1403         }
1404     }
1405
1406   /* here we buffer the handshake messages - needed at Finished message */
1407   if (recv_type != GNUTLS_HANDSHAKE_HELLO_REQUEST)
1408     {
1409
1410       if ((ret =
1411            _gnutls_handshake_buffer_put (session, header, header_size)) < 0)
1412         {
1413           gnutls_assert ();
1414           return ret;
1415         }
1416
1417       if (datalen > 0)
1418         {
1419           if ((ret =
1420                _gnutls_handshake_buffer_put (session, dataptr, datalen)) < 0)
1421             {
1422               gnutls_assert ();
1423               return ret;
1424             }
1425         }
1426     }
1427
1428   return 0;
1429 }
1430
1431
1432 /* This function will receive handshake messages of the given types,
1433  * and will pass the message to the right place in order to be processed.
1434  * E.g. for the SERVER_HELLO message (if it is expected), it will be
1435  * passed to _gnutls_recv_hello().
1436  */
1437 int
1438 _gnutls_recv_handshake (gnutls_session_t session, uint8_t ** data,
1439                         int *datalen, gnutls_handshake_description_t type,
1440                         Optional optional)
1441 {
1442   int ret;
1443   uint32_t length32 = 0;
1444   opaque *dataptr = NULL;
1445   gnutls_handshake_description_t recv_type;
1446
1447   ret = _gnutls_recv_handshake_header (session, type, &recv_type);
1448   if (ret < 0)
1449     {
1450
1451       if (ret == GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET
1452           && optional == OPTIONAL_PACKET)
1453         {
1454           if (datalen != NULL)
1455             *datalen = 0;
1456           if (data != NULL)
1457             *data = NULL;
1458           return 0;             /* ok just ignore the packet */
1459         }
1460
1461       return ret;
1462     }
1463
1464   session->internals.last_handshake_in = recv_type;
1465
1466   length32 = ret;
1467
1468   if (length32 > 0)
1469     dataptr = gnutls_malloc (length32);
1470   else if (recv_type != GNUTLS_HANDSHAKE_SERVER_HELLO_DONE)
1471     {
1472       gnutls_assert ();
1473       return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1474     }
1475
1476   if (dataptr == NULL && length32 > 0)
1477     {
1478       gnutls_assert ();
1479       return GNUTLS_E_MEMORY_ERROR;
1480     }
1481
1482   if (datalen != NULL)
1483     *datalen = length32;
1484
1485   if (length32 > 0)
1486     {
1487       ret =
1488         _gnutls_handshake_io_recv_int (session, GNUTLS_HANDSHAKE,
1489                                        type, dataptr, length32);
1490       if (ret <= 0)
1491         {
1492           gnutls_assert ();
1493           gnutls_free (dataptr);
1494           return (ret == 0) ? GNUTLS_E_UNEXPECTED_PACKET_LENGTH : ret;
1495         }
1496     }
1497
1498   if (data != NULL && length32 > 0)
1499     *data = dataptr;
1500
1501
1502   ret = _gnutls_handshake_hash_add_recvd (session, recv_type,
1503                                           session->
1504                                           internals.handshake_header_buffer.
1505                                           header,
1506                                           session->
1507                                           internals.handshake_header_buffer.
1508                                           header_size, dataptr, length32);
1509   if (ret < 0)
1510     {
1511       gnutls_assert ();
1512       _gnutls_handshake_header_buffer_clear (session);
1513       return ret;
1514     }
1515
1516   /* If we fail before this then we will reuse the handshake header
1517    * have have received above. if we get here the we clear the handshake
1518    * header we received.
1519    */
1520   _gnutls_handshake_header_buffer_clear (session);
1521
1522   switch (recv_type)
1523     {
1524     case GNUTLS_HANDSHAKE_CLIENT_HELLO:
1525     case GNUTLS_HANDSHAKE_SERVER_HELLO:
1526       ret = _gnutls_recv_hello (session, dataptr, length32);
1527
1528       /* dataptr is freed because the caller does not
1529        * need it */
1530       gnutls_free (dataptr);
1531       if (data != NULL)
1532         *data = NULL;
1533
1534       if (ret < 0)
1535         break;
1536
1537       /* initialize the hashes for both - (client will know server's version
1538        * and server as well at this point) */
1539       if ((ret = _gnutls_handshake_hash_init (session)) < 0)
1540         {
1541           gnutls_assert ();
1542           return ret;
1543         }
1544
1545       break;
1546     case GNUTLS_HANDSHAKE_SERVER_HELLO_DONE:
1547       if (length32 == 0)
1548         ret = 0;
1549       else
1550         ret = GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1551       break;
1552     case GNUTLS_HANDSHAKE_CERTIFICATE_PKT:
1553     case GNUTLS_HANDSHAKE_FINISHED:
1554     case GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE:
1555     case GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE:
1556     case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST:
1557     case GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY:
1558     case GNUTLS_HANDSHAKE_SUPPLEMENTAL:
1559     case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET:
1560       ret = length32;
1561       break;
1562     default:
1563       gnutls_assert ();
1564       gnutls_free (dataptr);
1565       if (data != NULL)
1566         *data = NULL;
1567       ret = GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
1568     }
1569
1570   return ret;
1571 }
1572
1573 /* This function checks if the given cipher suite is supported, and sets it
1574  * to the session;
1575  */
1576 static int
1577 _gnutls_client_set_ciphersuite (gnutls_session_t session, opaque suite[2])
1578 {
1579   uint8_t z;
1580   cipher_suite_st *cipher_suites;
1581   int cipher_suite_num;
1582   int i, err;
1583
1584   z = 1;
1585   cipher_suite_num = _gnutls_supported_ciphersuites (session, &cipher_suites);
1586   if (cipher_suite_num < 0)
1587     {
1588       gnutls_assert ();
1589       return cipher_suite_num;
1590     }
1591
1592   for (i = 0; i < cipher_suite_num; i++)
1593     {
1594       if (memcmp (&cipher_suites[i], suite, 2) == 0)
1595         {
1596           z = 0;
1597           break;
1598         }
1599     }
1600
1601   gnutls_free (cipher_suites);
1602
1603   if (z != 0)
1604     {
1605       gnutls_assert ();
1606       return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
1607     }
1608
1609   memcpy (session->security_parameters.current_cipher_suite.suite, suite, 2);
1610   _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
1611                                   &session->
1612                                   security_parameters.current_cipher_suite);
1613
1614   _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session,
1615                          _gnutls_cipher_suite_get_name
1616                          (&session->
1617                           security_parameters.current_cipher_suite));
1618
1619
1620   /* check if the credentials (username, public key etc.) are ok.
1621    * Actually checks if they exist.
1622    */
1623   if (_gnutls_get_kx_cred
1624       (session,
1625        _gnutls_cipher_suite_get_kx_algo
1626        (&session->security_parameters.current_cipher_suite), &err) == NULL
1627       && err != 0)
1628     {
1629       gnutls_assert ();
1630       return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1631     }
1632
1633
1634   /* set the mod_auth_st to the appropriate struct
1635    * according to the KX algorithm. This is needed since all the
1636    * handshake functions are read from there;
1637    */
1638   session->internals.auth_struct =
1639     _gnutls_kx_auth_struct (_gnutls_cipher_suite_get_kx_algo
1640                             (&session->
1641                              security_parameters.current_cipher_suite));
1642
1643   if (session->internals.auth_struct == NULL)
1644     {
1645
1646       _gnutls_handshake_log
1647         ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
1648          session);
1649       gnutls_assert ();
1650       return GNUTLS_E_INTERNAL_ERROR;
1651     }
1652
1653
1654   return 0;
1655 }
1656
1657 /* This function sets the given comp method to the session.
1658  */
1659 static int
1660 _gnutls_client_set_comp_method (gnutls_session_t session, opaque comp_method)
1661 {
1662   int comp_methods_num;
1663   uint8_t *compression_methods;
1664   int i;
1665
1666   comp_methods_num = _gnutls_supported_compression_methods (session,
1667                                                             &compression_methods);
1668   if (comp_methods_num < 0)
1669     {
1670       gnutls_assert ();
1671       return comp_methods_num;
1672     }
1673
1674   for (i = 0; i < comp_methods_num; i++)
1675     {
1676       if (compression_methods[i] == comp_method)
1677         {
1678           comp_methods_num = 0;
1679           break;
1680         }
1681     }
1682
1683   gnutls_free (compression_methods);
1684
1685   if (comp_methods_num != 0)
1686     {
1687       gnutls_assert ();
1688       return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1689     }
1690
1691   session->internals.compression_method =
1692     _gnutls_compression_get_id (comp_method);
1693   _gnutls_epoch_set_compression (session, EPOCH_NEXT,
1694                                  session->internals.compression_method);
1695
1696   return 0;
1697 }
1698
1699 /* This function returns 0 if we are resuming a session or -1 otherwise.
1700  * This also sets the variables in the session. Used only while reading a server
1701  * hello.
1702  */
1703 static int
1704 _gnutls_client_check_if_resuming (gnutls_session_t session,
1705                                   opaque * session_id, int session_id_len)
1706 {
1707   opaque buf[2 * TLS_MAX_SESSION_ID_SIZE + 1];
1708
1709   _gnutls_handshake_log ("HSK[%p]: SessionID length: %d\n", session,
1710                          session_id_len);
1711   _gnutls_handshake_log ("HSK[%p]: SessionID: %s\n", session,
1712                          _gnutls_bin2hex (session_id, session_id_len, buf,
1713                                           sizeof (buf), NULL));
1714
1715   if (session_id_len > 0 &&
1716       session->internals.resumed_security_parameters.session_id_size ==
1717       session_id_len
1718       && memcmp (session_id,
1719                  session->internals.resumed_security_parameters.session_id,
1720                  session_id_len) == 0)
1721     {
1722       /* resume session */
1723       memcpy (session->internals.resumed_security_parameters.server_random,
1724               session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
1725       memcpy (session->internals.resumed_security_parameters.client_random,
1726               session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);
1727
1728       _gnutls_epoch_set_cipher_suite
1729         (session, EPOCH_NEXT,
1730          &session->internals.
1731          resumed_security_parameters.current_cipher_suite);
1732       _gnutls_epoch_set_compression (session, EPOCH_NEXT,
1733                                      session->
1734                                      internals.resumed_compression_method);
1735
1736       session->internals.resumed = RESUME_TRUE; /* we are resuming */
1737
1738       return 0;
1739     }
1740   else
1741     {
1742       /* keep the new session id */
1743       session->internals.resumed = RESUME_FALSE;        /* we are not resuming */
1744       session->security_parameters.session_id_size = session_id_len;
1745       memcpy (session->security_parameters.session_id,
1746               session_id, session_id_len);
1747
1748       return -1;
1749     }
1750 }
1751
1752
1753 /* This function reads and parses the server hello handshake message.
1754  * This function also restores resumed parameters if we are resuming a
1755  * session.
1756  */
1757 static int
1758 _gnutls_read_server_hello (gnutls_session_t session,
1759                            opaque * data, int datalen)
1760 {
1761   uint8_t session_id_len = 0;
1762   int pos = 0;
1763   int ret = 0;
1764   gnutls_protocol_t version;
1765   int len = datalen;
1766
1767   if (datalen < 38)
1768     {
1769       gnutls_assert ();
1770       return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1771     }
1772
1773   _gnutls_handshake_log ("HSK[%p]: Server's version: %d.%d\n",
1774                          session, data[pos], data[pos + 1]);
1775
1776   DECR_LEN (len, 2);
1777   version = _gnutls_version_get (data[pos], data[pos + 1]);
1778   if (_gnutls_version_is_supported (session, version) == 0)
1779     {
1780       gnutls_assert ();
1781       return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
1782     }
1783   else
1784     {
1785       _gnutls_set_current_version (session, version);
1786     }
1787
1788   pos += 2;
1789
1790   DECR_LEN (len, GNUTLS_RANDOM_SIZE);
1791   _gnutls_set_server_random (session, &data[pos]);
1792   pos += GNUTLS_RANDOM_SIZE;
1793
1794
1795   /* Read session ID
1796    */
1797   DECR_LEN (len, 1);
1798   session_id_len = data[pos++];
1799
1800   if (len < session_id_len)
1801     {
1802       gnutls_assert ();
1803       return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
1804     }
1805   DECR_LEN (len, session_id_len);
1806
1807   /* check if we are resuming and set the appropriate
1808    * values;
1809    */
1810   if (_gnutls_client_check_if_resuming
1811       (session, &data[pos], session_id_len) == 0)
1812     {
1813       pos += session_id_len + 2 + 1;
1814       DECR_LEN (len, 2 + 1);
1815
1816       ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
1817                                       &data[pos], len);
1818       if (ret < 0)
1819         {
1820           gnutls_assert ();
1821           return ret;
1822         }
1823       return 0;
1824     }
1825
1826   pos += session_id_len;
1827
1828   /* Check if the given cipher suite is supported and copy
1829    * it to the session.
1830    */
1831
1832   DECR_LEN (len, 2);
1833   ret = _gnutls_client_set_ciphersuite (session, &data[pos]);
1834   if (ret < 0)
1835     {
1836       gnutls_assert ();
1837       return ret;
1838     }
1839   pos += 2;
1840
1841   /* move to compression 
1842    */
1843   DECR_LEN (len, 1);
1844
1845   ret = _gnutls_client_set_comp_method (session, data[pos++]);
1846   if (ret < 0)
1847     {
1848       gnutls_assert ();
1849       return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1850     }
1851
1852   /* Parse extensions.
1853    */
1854   ret = _gnutls_parse_extensions (session, GNUTLS_EXT_ANY, &data[pos], len);
1855   if (ret < 0)
1856     {
1857       gnutls_assert ();
1858       return ret;
1859     }
1860
1861   return ret;
1862 }
1863
1864
1865 /* This function copies the appropriate ciphersuites to a locally allocated buffer
1866  * Needed in client hello messages. Returns the new data length. If add_scsv is
1867  * true, add the special safe renegotiation CS.
1868  */
1869 static int
1870 _gnutls_copy_ciphersuites (gnutls_session_t session,
1871                            opaque * ret_data, size_t ret_data_size,
1872                            int add_scsv)
1873 {
1874   int ret, i;
1875   cipher_suite_st *cipher_suites;
1876   uint16_t cipher_num;
1877   int datalen, pos;
1878   uint16_t loop_max;
1879
1880   ret = _gnutls_supported_ciphersuites_sorted (session, &cipher_suites);
1881   if (ret < 0)
1882     {
1883       gnutls_assert ();
1884       return ret;
1885     }
1886
1887   /* Here we remove any ciphersuite that does not conform
1888    * the certificate requested, or to the
1889    * authentication requested (eg SRP).
1890    */
1891   ret =
1892     _gnutls_remove_unwanted_ciphersuites (session, &cipher_suites, ret, -1);
1893   if (ret < 0)
1894     {
1895       gnutls_assert ();
1896       gnutls_free (cipher_suites);
1897       return ret;
1898     }
1899
1900   /* If no cipher suites were enabled.
1901    */
1902   if (ret == 0)
1903     {
1904       gnutls_assert ();
1905       gnutls_free (cipher_suites);
1906       return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1907     }
1908
1909   if (add_scsv)
1910     ++ret;
1911
1912   cipher_num = ret;
1913
1914   cipher_num *= sizeof (uint16_t);      /* in order to get bytes */
1915
1916   datalen = pos = 0;
1917
1918   datalen += sizeof (uint16_t) + cipher_num;
1919
1920   if ((size_t) datalen > ret_data_size)
1921     {
1922       gnutls_assert ();
1923       return GNUTLS_E_INTERNAL_ERROR;
1924     }
1925
1926   _gnutls_write_uint16 (cipher_num, ret_data);
1927   pos += 2;
1928
1929   loop_max = add_scsv ? cipher_num - 2 : cipher_num;
1930
1931   for (i = 0; i < (loop_max / 2); i++)
1932     {
1933       memcpy (&ret_data[pos], cipher_suites[i].suite, 2);
1934       pos += 2;
1935     }
1936
1937   if (add_scsv)
1938     {
1939       /* Safe renegotiation signalling CS value is { 0x00, 0xff } */
1940       ret_data[pos++] = 0x00;
1941       ret_data[pos++] = 0xff;
1942       ret = _gnutls_ext_sr_send_cs (session);
1943       if (ret < 0)
1944         {
1945           gnutls_assert ();
1946           gnutls_free (cipher_suites);
1947           return ret;
1948         }
1949     }
1950
1951   gnutls_free (cipher_suites);
1952
1953   return datalen;
1954 }
1955
1956
1957 /* This function copies the appropriate compression methods, to a locally allocated buffer 
1958  * Needed in hello messages. Returns the new data length.
1959  */
1960 static int
1961 _gnutls_copy_comp_methods (gnutls_session_t session,
1962                            opaque * ret_data, size_t ret_data_size)
1963 {
1964   int ret, i;
1965   uint8_t *compression_methods, comp_num;
1966   int datalen, pos;
1967
1968   ret = _gnutls_supported_compression_methods (session, &compression_methods);
1969   if (ret < 0)
1970     {
1971       gnutls_assert ();
1972       return ret;
1973     }
1974
1975   comp_num = ret;
1976
1977   datalen = pos = 0;
1978   datalen += comp_num + 1;
1979
1980   if ((size_t) datalen > ret_data_size)
1981     {
1982       gnutls_assert ();
1983       return GNUTLS_E_INTERNAL_ERROR;
1984     }
1985
1986   ret_data[pos++] = comp_num;   /* put the number of compression methods */
1987
1988   for (i = 0; i < comp_num; i++)
1989     {
1990       ret_data[pos++] = compression_methods[i];
1991     }
1992
1993   gnutls_free (compression_methods);
1994
1995   return datalen;
1996 }
1997
1998 /* This should be sufficient by now. It should hold all the extensions
1999  * plus the headers in a hello message.
2000  */
2001 #define MAX_EXT_DATA_LENGTH 32*1024
2002
2003 /* This function sends the client hello handshake message.
2004  */
2005 static int
2006 _gnutls_send_client_hello (gnutls_session_t session, int again)
2007 {
2008   mbuffer_st *bufel = NULL;
2009   opaque *data = NULL;
2010   int extdatalen;
2011   int pos = 0, type;
2012   int datalen = 0, ret = 0;
2013   opaque rnd[GNUTLS_RANDOM_SIZE];
2014   gnutls_protocol_t hver;
2015   opaque *extdata = NULL;
2016   int rehandshake = 0;
2017   uint8_t session_id_len =
2018     session->internals.resumed_security_parameters.session_id_size;
2019
2020   /* note that rehandshake is different than resuming
2021    */
2022   if (session->security_parameters.session_id_size)
2023     rehandshake = 1;
2024
2025   if (again == 0)
2026     {
2027
2028       datalen = 2 + (session_id_len + 1) + GNUTLS_RANDOM_SIZE;
2029       /* 2 for version, (4 for unix time + 28 for random bytes==GNUTLS_RANDOM_SIZE) 
2030        */
2031
2032       bufel =
2033         _gnutls_handshake_alloc (datalen, datalen + MAX_EXT_DATA_LENGTH);
2034       if (bufel == NULL)
2035         {
2036           gnutls_assert ();
2037           return GNUTLS_E_MEMORY_ERROR;
2038         }
2039       data = _mbuffer_get_udata_ptr (bufel);
2040       extdatalen = MAX_EXT_DATA_LENGTH;
2041
2042       extdata = gnutls_malloc (extdatalen);
2043       if (extdata == NULL)
2044         {
2045           gnutls_assert ();
2046           return GNUTLS_E_MEMORY_ERROR;
2047         }
2048
2049       /* if we are resuming a session then we set the
2050        * version number to the previously established.
2051        */
2052       if (session_id_len == 0)
2053         {
2054           if (rehandshake)      /* already negotiated version thus version_max == negotiated version */
2055             hver = session->security_parameters.version;
2056           else                  /* new handshake. just get the max */
2057             hver = _gnutls_version_max (session);
2058         }
2059       else
2060         {
2061           /* we are resuming a session */
2062           hver = session->internals.resumed_security_parameters.version;
2063         }
2064
2065       if (hver == GNUTLS_VERSION_UNKNOWN || hver == 0)
2066         {
2067           gnutls_assert ();
2068           gnutls_free (bufel);
2069           gnutls_free (extdata);
2070           return GNUTLS_E_INTERNAL_ERROR;
2071         }
2072
2073       data[pos++] = _gnutls_version_get_major (hver);
2074       data[pos++] = _gnutls_version_get_minor (hver);
2075
2076       /* Set the version we advertized as maximum 
2077        * (RSA uses it).
2078        */
2079       _gnutls_set_adv_version (session, hver);
2080       _gnutls_set_current_version (session, hver);
2081
2082       if (session->internals.priorities.ssl3_record_version != 0)
2083         {
2084           /* Advertize the SSL 3.0 record packet version in
2085            * record packets during the handshake.
2086            * That is to avoid confusing implementations
2087            * that do not support TLS 1.2 and don't know
2088            * how 3,3 version of record packets look like.
2089            */
2090           _gnutls_record_set_default_version (session, 3, 0);
2091         }
2092
2093       /* In order to know when this session was initiated.
2094        */
2095       session->security_parameters.timestamp = gnutls_time (NULL);
2096
2097       /* Generate random data 
2098        */
2099       _gnutls_tls_create_random (rnd);
2100       _gnutls_set_client_random (session, rnd);
2101
2102       memcpy (&data[pos], rnd, GNUTLS_RANDOM_SIZE);
2103       pos += GNUTLS_RANDOM_SIZE;
2104
2105       /* Copy the Session ID 
2106        */
2107       data[pos++] = session_id_len;
2108
2109       if (session_id_len > 0)
2110         {
2111           memcpy (&data[pos],
2112                   session->internals.resumed_security_parameters.session_id,
2113                   session_id_len);
2114           pos += session_id_len;
2115         }
2116
2117
2118       /* Copy the ciphersuites.
2119        *
2120        * If using SSLv3 Send TLS_RENEGO_PROTECTION_REQUEST SCSV for MITM
2121        * prevention on initial negotiation (but not renegotiation; that's
2122        * handled with the RI extension below).
2123        */
2124       if (!session->internals.initial_negotiation_completed &&
2125           session->security_parameters.entity == GNUTLS_CLIENT &&
2126           gnutls_protocol_get_version (session) == GNUTLS_SSL3)
2127         {
2128           ret =
2129             _gnutls_copy_ciphersuites (session, extdata, extdatalen, TRUE);
2130           _gnutls_extension_list_add (session,
2131                                       GNUTLS_EXTENSION_SAFE_RENEGOTIATION);
2132         }
2133       else
2134         ret = _gnutls_copy_ciphersuites (session, extdata, extdatalen, FALSE);
2135
2136       if (ret > 0)
2137         {
2138           ret = _mbuffer_append_data (bufel, extdata, ret);
2139           if (ret < 0)
2140             {
2141               gnutls_assert ();
2142               gnutls_free (extdata);
2143               return ret;
2144             }
2145         }
2146       else
2147         {
2148           if (extdatalen == 0)
2149             extdatalen = GNUTLS_E_INTERNAL_ERROR;
2150           gnutls_free (bufel);
2151           gnutls_free (extdata);
2152           gnutls_assert ();
2153           return ret;
2154         }
2155
2156
2157       /* Copy the compression methods.
2158        */
2159       ret = _gnutls_copy_comp_methods (session, extdata, extdatalen);
2160       if (ret > 0)
2161         {
2162           ret = _mbuffer_append_data (bufel, extdata, ret);
2163           if (ret < 0)
2164             {
2165               gnutls_assert ();
2166               gnutls_free (extdata);
2167               return ret;
2168             }
2169         }
2170       else
2171         {
2172           if (extdatalen == 0)
2173             extdatalen = GNUTLS_E_INTERNAL_ERROR;
2174           gnutls_free (bufel);
2175           gnutls_free (extdata);
2176           gnutls_assert ();
2177           return ret;
2178         }
2179
2180       /* Generate and copy TLS extensions.
2181        */
2182       if (_gnutls_version_has_extensions (hver))
2183         type = GNUTLS_EXT_ANY;
2184       else
2185         {
2186           if (session->internals.initial_negotiation_completed != 0)
2187             type = GNUTLS_EXT_MANDATORY;
2188           else
2189             type = GNUTLS_EXT_NONE;
2190         }
2191
2192       ret = _gnutls_gen_extensions (session, extdata, extdatalen, type);
2193
2194       if (ret > 0)
2195         {
2196           ret = _mbuffer_append_data (bufel, extdata, ret);
2197           if (ret < 0)
2198             {
2199               gnutls_assert ();
2200               gnutls_free (extdata);
2201               return ret;
2202             }
2203         }
2204       else if (ret < 0)
2205         {
2206           gnutls_assert ();
2207           gnutls_free (bufel);
2208           gnutls_free (extdata);
2209           return ret;
2210         }
2211     }
2212
2213   gnutls_free (extdata);
2214
2215   ret =
2216     _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_CLIENT_HELLO);
2217
2218   return ret;
2219 }
2220
2221 static int
2222 _gnutls_send_server_hello (gnutls_session_t session, int again)
2223 {
2224   mbuffer_st *bufel = NULL;
2225   opaque *data = NULL;
2226   opaque *extdata = NULL;
2227   int extdatalen;
2228   int pos = 0;
2229   int datalen, ret = 0;
2230   uint8_t comp;
2231   uint8_t session_id_len = session->security_parameters.session_id_size;
2232   opaque buf[2 * TLS_MAX_SESSION_ID_SIZE + 1];
2233
2234   datalen = 0;
2235
2236   if (again == 0)
2237     {
2238
2239       extdata = gnutls_malloc (MAX_EXT_DATA_LENGTH);
2240       if (extdata == NULL)
2241         {
2242           gnutls_assert ();
2243           return GNUTLS_E_MEMORY_ERROR;
2244         }
2245
2246       datalen = 2 + session_id_len + 1 + GNUTLS_RANDOM_SIZE + 3;
2247       ret =
2248         _gnutls_gen_extensions (session, extdata, MAX_EXT_DATA_LENGTH,
2249                                 GNUTLS_EXT_ANY);
2250
2251       if (ret < 0)
2252         {
2253           gnutls_assert ();
2254           goto fail;
2255         }
2256       extdatalen = ret;
2257
2258       bufel =
2259         _gnutls_handshake_alloc (datalen + extdatalen, datalen + extdatalen);
2260       if (bufel == NULL)
2261         {
2262           gnutls_assert ();
2263           ret = GNUTLS_E_MEMORY_ERROR;
2264           goto fail;
2265         }
2266       data = _mbuffer_get_udata_ptr (bufel);
2267
2268       data[pos++] =
2269         _gnutls_version_get_major (session->security_parameters.version);
2270       data[pos++] =
2271         _gnutls_version_get_minor (session->security_parameters.version);
2272
2273       memcpy (&data[pos],
2274               session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
2275       pos += GNUTLS_RANDOM_SIZE;
2276
2277       data[pos++] = session_id_len;
2278       if (session_id_len > 0)
2279         {
2280           memcpy (&data[pos], session->security_parameters.session_id,
2281                   session_id_len);
2282         }
2283       pos += session_id_len;
2284
2285       _gnutls_handshake_log ("HSK[%p]: SessionID: %s\n", session,
2286                              _gnutls_bin2hex (session->security_parameters.
2287                                               session_id, session_id_len, buf,
2288                                               sizeof (buf), NULL));
2289
2290       memcpy (&data[pos],
2291               session->security_parameters.current_cipher_suite.suite, 2);
2292       pos += 2;
2293
2294       comp =
2295         (uint8_t) _gnutls_compression_get_num (session->internals.
2296                                                compression_method);
2297       data[pos++] = comp;
2298
2299
2300       if (extdatalen > 0)
2301         {
2302           datalen += extdatalen;
2303
2304           memcpy (&data[pos], extdata, extdatalen);
2305         }
2306     }
2307
2308   ret =
2309     _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_SERVER_HELLO);
2310
2311 fail:
2312   gnutls_free (extdata);
2313   return ret;
2314 }
2315
2316 int
2317 _gnutls_send_hello (gnutls_session_t session, int again)
2318 {
2319   int ret;
2320
2321   if (session->security_parameters.entity == GNUTLS_CLIENT)
2322     {
2323       ret = _gnutls_send_client_hello (session, again);
2324
2325     }
2326   else
2327     {                           /* SERVER */
2328       ret = _gnutls_send_server_hello (session, again);
2329     }
2330
2331   return ret;
2332 }
2333
2334 /* RECEIVE A HELLO MESSAGE. This should be called from gnutls_recv_handshake_int only if a
2335  * hello message is expected. It uses the security_parameters.current_cipher_suite
2336  * and internals.compression_method.
2337  */
2338 int
2339 _gnutls_recv_hello (gnutls_session_t session, opaque * data, int datalen)
2340 {
2341   int ret;
2342
2343   if (session->security_parameters.entity == GNUTLS_CLIENT)
2344     {
2345       ret = _gnutls_read_server_hello (session, data, datalen);
2346       if (ret < 0)
2347         {
2348           gnutls_assert ();
2349           return ret;
2350         }
2351     }
2352   else
2353     {                           /* Server side reading a client hello */
2354
2355       ret = _gnutls_read_client_hello (session, data, datalen);
2356       if (ret < 0)
2357         {
2358           gnutls_assert ();
2359           return ret;
2360         }
2361     }
2362
2363   ret = _gnutls_ext_sr_verify (session);
2364   if (ret < 0)
2365     {
2366       gnutls_assert ();
2367       return ret;
2368     }
2369
2370   return 0;
2371 }
2372
2373 /* The packets in gnutls_handshake (it's more broad than original TLS handshake)
2374  *
2375  *     Client                                               Server
2376  *
2377  *     ClientHello                  -------->
2378  *                                  <--------         ServerHello
2379  *
2380  *                                                    Certificate*
2381  *                                              ServerKeyExchange*
2382  *                                  <--------   CertificateRequest*
2383  *
2384  *                                  <--------      ServerHelloDone
2385  *     Certificate*
2386  *     ClientKeyExchange
2387  *     CertificateVerify*
2388  *     [ChangeCipherSpec]
2389  *     Finished                     -------->
2390  *                                                NewSessionTicket
2391  *                                              [ChangeCipherSpec]
2392  *                                  <--------             Finished
2393  *
2394  * (*): means optional packet.
2395  */
2396
2397 /* Handshake when resumming session:
2398  *      Client                                                Server
2399  *
2400  *      ClientHello                   -------->
2401  *                                                      ServerHello
2402  *                                               [ChangeCipherSpec]
2403  *                                   <--------             Finished
2404  *     [ChangeCipherSpec]
2405  *     Finished                      -------->
2406  * 
2407  */
2408
2409 /**
2410  * gnutls_rehandshake:
2411  * @session: is a #gnutls_session_t structure.
2412  *
2413  * This function will renegotiate security parameters with the
2414  * client.  This should only be called in case of a server.
2415  *
2416  * This message informs the peer that we want to renegotiate
2417  * parameters (perform a handshake).
2418  *
2419  * If this function succeeds (returns 0), you must call the
2420  * gnutls_handshake() function in order to negotiate the new
2421  * parameters.
2422  *
2423  * Since TLS is full duplex some application data might have been
2424  * sent during peer's processing of this message. In that case
2425  * one should call gnutls_record_recv() until GNUTLS_E_REHANDSHAKE
2426  * is returned to clear any pending data. Care must be taken if
2427  * rehandshake is mandatory to terminate if it does not start after
2428  * some threshold.
2429  *
2430  * If the client does not wish to renegotiate parameters he will
2431  * should with an alert message, thus the return code will be
2432  * %GNUTLS_E_WARNING_ALERT_RECEIVED and the alert will be
2433  * %GNUTLS_A_NO_RENEGOTIATION.  A client may also choose to ignore
2434  * this message.
2435  *
2436  * Returns: %GNUTLS_E_SUCCESS on success, otherwise an error.
2437  **/
2438 int
2439 gnutls_rehandshake (gnutls_session_t session)
2440 {
2441   int ret;
2442
2443   /* only server sends that handshake packet */
2444   if (session->security_parameters.entity == GNUTLS_CLIENT)
2445     return GNUTLS_E_INVALID_REQUEST;
2446
2447   ret =
2448     _gnutls_send_empty_handshake (session, GNUTLS_HANDSHAKE_HELLO_REQUEST,
2449                                   AGAIN (STATE50));
2450   STATE = STATE50;
2451
2452   if (ret < 0)
2453     {
2454       gnutls_assert ();
2455       return ret;
2456     }
2457   STATE = STATE0;
2458
2459   return 0;
2460 }
2461
2462 inline static int
2463 _gnutls_abort_handshake (gnutls_session_t session, int ret)
2464 {
2465   if (((ret == GNUTLS_E_WARNING_ALERT_RECEIVED) &&
2466        (gnutls_alert_get (session) == GNUTLS_A_NO_RENEGOTIATION))
2467       || ret == GNUTLS_E_GOT_APPLICATION_DATA)
2468     return 0;
2469
2470   /* this doesn't matter */
2471   return GNUTLS_E_INTERNAL_ERROR;
2472 }
2473
2474
2475 /* This function initialized the handshake hash session.
2476  * required for finished messages.
2477  */
2478 static int
2479 _gnutls_handshake_hash_init (gnutls_session_t session)
2480 {
2481   gnutls_protocol_t ver = gnutls_protocol_get_version (session);
2482
2483   if (session->internals.handshake_mac_handle_init == 0)
2484     {
2485       int ret;
2486
2487       /* set the hash type for handshake message hashing */
2488       if (_gnutls_version_has_selectable_prf (ver))
2489         session->security_parameters.handshake_mac_handle_type =
2490           HANDSHAKE_MAC_TYPE_12;
2491       else
2492         session->security_parameters.handshake_mac_handle_type =
2493           HANDSHAKE_MAC_TYPE_10;
2494
2495       if (session->security_parameters.handshake_mac_handle_type ==
2496           HANDSHAKE_MAC_TYPE_10)
2497         {
2498           ret =
2499             _gnutls_hash_init (&session->internals.handshake_mac_handle.tls10.
2500                                md5, GNUTLS_MAC_MD5);
2501
2502           if (ret < 0)
2503             {
2504               gnutls_assert ();
2505               return ret;
2506             }
2507
2508           ret =
2509             _gnutls_hash_init (&session->internals.handshake_mac_handle.tls10.
2510                                sha, GNUTLS_MAC_SHA1);
2511           if (ret < 0)
2512             {
2513               gnutls_assert ();
2514               _gnutls_hash_deinit (&session->internals.handshake_mac_handle.
2515                                    tls10.md5, NULL);
2516               return GNUTLS_E_MEMORY_ERROR;
2517             }
2518         }
2519       else if (session->security_parameters.handshake_mac_handle_type ==
2520                HANDSHAKE_MAC_TYPE_12)
2521         {
2522           /* The algorithm to compute hash over handshake messages must be
2523              same as the one used as the basis for PRF.  By now we use
2524              SHA256. */
2525           ret =
2526             _gnutls_hash_init (&session->internals.handshake_mac_handle.tls12.
2527                                sha256, GNUTLS_DIG_SHA256);
2528           if (ret < 0)
2529             {
2530               gnutls_assert ();
2531               return GNUTLS_E_MEMORY_ERROR;
2532             }
2533
2534           ret =
2535             _gnutls_hash_init (&session->internals.handshake_mac_handle.tls12.
2536                                sha1, GNUTLS_DIG_SHA1);
2537           if (ret < 0)
2538             {
2539               gnutls_assert ();
2540               _gnutls_hash_deinit (&session->internals.handshake_mac_handle.
2541                                    tls12.sha256, NULL);
2542               return GNUTLS_E_MEMORY_ERROR;
2543             }
2544         }
2545
2546       session->internals.handshake_mac_handle_init = 1;
2547     }
2548
2549   return 0;
2550 }
2551
2552 static int
2553 _gnutls_send_supplemental (gnutls_session_t session, int again)
2554 {
2555   mbuffer_st *bufel;
2556   int ret = 0;
2557
2558   _gnutls_debug_log ("EXT[%p]: Sending supplemental data\n", session);
2559
2560   if (again)
2561     ret =
2562       _gnutls_send_handshake (session, NULL, GNUTLS_HANDSHAKE_SUPPLEMENTAL);
2563   else
2564     {
2565       gnutls_buffer_st buf;
2566       _gnutls_buffer_init (&buf);
2567
2568       ret = _gnutls_gen_supplemental (session, &buf);
2569       if (ret < 0)
2570         {
2571           gnutls_assert ();
2572           return ret;
2573         }
2574
2575       bufel = _gnutls_handshake_alloc (buf.length, buf.length);
2576       if (bufel == NULL)
2577         {
2578           gnutls_assert ();
2579           return GNUTLS_E_MEMORY_ERROR;
2580         }
2581
2582       _mbuffer_set_udata (bufel, buf.data, buf.length);
2583       _gnutls_buffer_clear (&buf);
2584
2585       ret = _gnutls_send_handshake (session, bufel,
2586                                     GNUTLS_HANDSHAKE_SUPPLEMENTAL);
2587     }
2588
2589   return ret;
2590 }
2591
2592 static int
2593 _gnutls_recv_supplemental (gnutls_session_t session)
2594 {
2595   uint8_t *data = NULL;
2596   int datalen = 0;
2597   int ret;
2598
2599   _gnutls_debug_log ("EXT[%p]: Expecting supplemental data\n", session);
2600
2601   ret = _gnutls_recv_handshake (session, &data, &datalen,
2602                                 GNUTLS_HANDSHAKE_SUPPLEMENTAL,
2603                                 OPTIONAL_PACKET);
2604   if (ret < 0)
2605     {
2606       gnutls_assert ();
2607       return ret;
2608     }
2609
2610   ret = _gnutls_parse_supplemental (session, data, datalen);
2611   if (ret < 0)
2612     {
2613       gnutls_assert ();
2614       return ret;
2615     }
2616
2617   gnutls_free (data);
2618
2619   return ret;
2620 }
2621
2622 /**
2623  * gnutls_handshake:
2624  * @session: is a #gnutls_session_t structure.
2625  *
2626  * This function does the handshake of the TLS/SSL protocol, and
2627  * initializes the TLS connection.
2628  *
2629  * This function will fail if any problem is encountered, and will
2630  * return a negative error code. In case of a client, if the client
2631  * has asked to resume a session, but the server couldn't, then a
2632  * full handshake will be performed.
2633  *
2634  * The non-fatal errors such as %GNUTLS_E_AGAIN and
2635  * %GNUTLS_E_INTERRUPTED interrupt the handshake procedure, which
2636  * should be later be resumed.  Call this function again, until it
2637  * returns 0; cf.  gnutls_record_get_direction() and
2638  * gnutls_error_is_fatal().
2639  *
2640  * If this function is called by a server after a rehandshake request
2641  * then %GNUTLS_E_GOT_APPLICATION_DATA or
2642  * %GNUTLS_E_WARNING_ALERT_RECEIVED may be returned.  Note that these
2643  * are non fatal errors, only in the specific case of a rehandshake.
2644  * Their meaning is that the client rejected the rehandshake request or
2645  * in the case of %GNUTLS_E_GOT_APPLICATION_DATA it might also mean that
2646  * some data were pending.
2647  *
2648  * Returns: %GNUTLS_E_SUCCESS on success, otherwise an error.
2649  **/
2650 int
2651 gnutls_handshake (gnutls_session_t session)
2652 {
2653   int ret;
2654   record_parameters_st *params;
2655
2656   ret = _gnutls_epoch_get (session, session->security_parameters.epoch_next,
2657                            &params);
2658   if (ret < 0)
2659     {
2660       /* We assume the epoch is not allocated if _gnutls_epoch_get fails. */
2661       ret =
2662         _gnutls_epoch_alloc (session, session->security_parameters.epoch_next,
2663                              NULL);
2664       if (ret < 0)
2665         {
2666           gnutls_assert ();
2667           return ret;
2668         }
2669     }
2670
2671   if (session->security_parameters.entity == GNUTLS_CLIENT)
2672     {
2673       ret = _gnutls_handshake_client (session);
2674     }
2675   else
2676     {
2677       ret = _gnutls_handshake_server (session);
2678     }
2679   if (ret < 0)
2680     {
2681       /* In the case of a rehandshake abort
2682        * we should reset the handshake's internal state.
2683        */
2684       if (_gnutls_abort_handshake (session, ret) == 0)
2685         STATE = STATE0;
2686
2687       return ret;
2688     }
2689
2690   ret = _gnutls_handshake_common (session);
2691
2692   if (ret < 0)
2693     {
2694       if (_gnutls_abort_handshake (session, ret) == 0)
2695         STATE = STATE0;
2696
2697       return ret;
2698     }
2699
2700   STATE = STATE0;
2701
2702   _gnutls_handshake_io_buffer_clear (session);
2703   _gnutls_handshake_internal_state_clear (session);
2704
2705   session->security_parameters.epoch_next++;
2706
2707   return 0;
2708 }
2709
2710
2711 #define IMED_RET( str, ret, allow_alert) do { \
2712         if (ret < 0) { \
2713                 /* EAGAIN and INTERRUPTED are always non-fatal */ \
2714                 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) \
2715                         return ret; \
2716                 /* a warning alert might interrupt handshake */ \
2717                 if (allow_alert != 0 && ret==GNUTLS_E_WARNING_ALERT_RECEIVED) return ret; \
2718                 gnutls_assert(); \
2719                 ERR( str, ret); \
2720                 _gnutls_handshake_hash_buffers_clear(session); \
2721                 return ret; \
2722         } } while (0)
2723
2724
2725
2726 /*
2727  * _gnutls_handshake_client 
2728  * This function performs the client side of the handshake of the TLS/SSL protocol.
2729  */
2730 int
2731 _gnutls_handshake_client (gnutls_session_t session)
2732 {
2733   int ret = 0;
2734
2735 #ifdef HANDSHAKE_DEBUG
2736   char buf[64];
2737
2738   if (session->internals.resumed_security_parameters.session_id_size > 0)
2739     _gnutls_handshake_log ("HSK[%p]: Ask to resume: %s\n", session,
2740                            _gnutls_bin2hex (session->
2741                                             internals.resumed_security_parameters.session_id,
2742                                             session->
2743                                             internals.resumed_security_parameters.session_id_size,
2744                                             buf, sizeof (buf), NULL));
2745 #endif
2746
2747   switch (STATE)
2748     {
2749     case STATE0:
2750     case STATE1:
2751       ret = _gnutls_send_hello (session, AGAIN (STATE1));
2752       STATE = STATE1;
2753       IMED_RET ("send hello", ret, 1);
2754
2755     case STATE2:
2756       /* receive the server hello */
2757       ret =
2758         _gnutls_recv_handshake (session, NULL, NULL,
2759                                 GNUTLS_HANDSHAKE_SERVER_HELLO,
2760                                 MANDATORY_PACKET);
2761       STATE = STATE2;
2762       IMED_RET ("recv hello", ret, 1);
2763
2764     case STATE70:
2765       if (session->security_parameters.do_recv_supplemental)
2766         {
2767           ret = _gnutls_recv_supplemental (session);
2768           STATE = STATE70;
2769           IMED_RET ("recv supplemental", ret, 1);
2770         }
2771
2772     case STATE3:
2773       /* RECV CERTIFICATE */
2774       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
2775         ret = _gnutls_recv_server_certificate (session);
2776       STATE = STATE3;
2777       IMED_RET ("recv server certificate", ret, 1);
2778
2779     case STATE4:
2780       /* receive the server key exchange */
2781       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
2782         ret = _gnutls_recv_server_kx_message (session);
2783       STATE = STATE4;
2784       IMED_RET ("recv server kx message", ret, 1);
2785
2786     case STATE5:
2787       /* receive the server certificate request - if any 
2788        */
2789
2790       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
2791         ret = _gnutls_recv_server_certificate_request (session);
2792       STATE = STATE5;
2793       IMED_RET ("recv server certificate request message", ret, 1);
2794
2795     case STATE6:
2796       /* receive the server hello done */
2797       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
2798         ret =
2799           _gnutls_recv_handshake (session, NULL, NULL,
2800                                   GNUTLS_HANDSHAKE_SERVER_HELLO_DONE,
2801                                   MANDATORY_PACKET);
2802       STATE = STATE6;
2803       IMED_RET ("recv server hello done", ret, 1);
2804
2805     case STATE71:
2806       if (session->security_parameters.do_send_supplemental)
2807         {
2808           ret = _gnutls_send_supplemental (session, AGAIN (STATE71));
2809           STATE = STATE71;
2810           IMED_RET ("send supplemental", ret, 0);
2811         }
2812
2813     case STATE7:
2814       /* send our certificate - if any and if requested
2815        */
2816       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
2817         ret = _gnutls_send_client_certificate (session, AGAIN (STATE7));
2818       STATE = STATE7;
2819       IMED_RET ("send client certificate", ret, 0);
2820
2821     case STATE8:
2822       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
2823         ret = _gnutls_send_client_kx_message (session, AGAIN (STATE8));
2824       STATE = STATE8;
2825       IMED_RET ("send client kx", ret, 0);
2826
2827     case STATE9:
2828       /* send client certificate verify */
2829       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
2830         ret =
2831           _gnutls_send_client_certificate_verify (session, AGAIN (STATE9));
2832       STATE = STATE9;
2833       IMED_RET ("send client certificate verify", ret, 1);
2834
2835       STATE = STATE0;
2836     default:
2837       break;
2838     }
2839
2840
2841   return 0;
2842 }
2843
2844 /* This function sends the final handshake packets and initializes connection 
2845  */
2846 static int
2847 _gnutls_send_handshake_final (gnutls_session_t session, int init)
2848 {
2849   int ret = 0;
2850
2851   /* Send the CHANGE CIPHER SPEC PACKET */
2852
2853   switch (STATE)
2854     {
2855     case STATE0:
2856     case STATE20:
2857
2858       STATE = STATE20;
2859       ret = _gnutls_handshake_io_write_flush (session);
2860       if (ret < 0)
2861         {
2862           gnutls_assert ();
2863           return ret;
2864         }
2865
2866     case STATE21:
2867       ret = _gnutls_send_change_cipher_spec (session, AGAIN (STATE21));
2868       STATE = STATE21;
2869
2870       if (ret < 0)
2871         {
2872           ERR ("send ChangeCipherSpec", ret);
2873           gnutls_assert ();
2874           return ret;
2875         }
2876       /* Initialize the connection session (start encryption) - in case of client 
2877        */
2878       if (init == TRUE)
2879         {
2880           ret = _gnutls_connection_state_init (session);
2881           if (ret < 0)
2882             {
2883               gnutls_assert ();
2884               return ret;
2885             }
2886         }
2887
2888       ret = _gnutls_write_connection_state_init (session);
2889       if (ret < 0)
2890         {
2891           gnutls_assert ();
2892           return ret;
2893         }
2894
2895     case STATE22:
2896       /* send the finished message */
2897       ret = _gnutls_send_finished (session, AGAIN (STATE22));
2898       STATE = STATE22;
2899       if (ret < 0)
2900         {
2901           ERR ("send Finished", ret);
2902           gnutls_assert ();
2903           return ret;
2904         }
2905
2906       STATE = STATE0;
2907     default:
2908       break;
2909     }
2910
2911   return 0;
2912 }
2913
2914 /* This function receives the final handshake packets 
2915  * And executes the appropriate function to initialize the
2916  * read session.
2917  */
2918 static int
2919 _gnutls_recv_handshake_final (gnutls_session_t session, int init)
2920 {
2921   int ret = 0;
2922   uint8_t ch;
2923
2924   switch (STATE)
2925     {
2926     case STATE0:
2927     case STATE30:
2928       ret = _gnutls_recv_int (session, GNUTLS_CHANGE_CIPHER_SPEC, -1, &ch, 1);
2929       STATE = STATE30;
2930       if (ret <= 0)
2931         {
2932           ERR ("recv ChangeCipherSpec", ret);
2933           gnutls_assert ();
2934           return (ret < 0) ? ret : GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
2935         }
2936
2937       /* Initialize the connection session (start encryption) - in case of server */
2938       if (init == TRUE)
2939         {
2940           ret = _gnutls_connection_state_init (session);
2941           if (ret < 0)
2942             {
2943               gnutls_assert ();
2944               return ret;
2945             }
2946         }
2947
2948       ret = _gnutls_read_connection_state_init (session);
2949       if (ret < 0)
2950         {
2951           gnutls_assert ();
2952           return ret;
2953         }
2954
2955     case STATE31:
2956       ret = _gnutls_recv_finished (session);
2957       STATE = STATE31;
2958       if (ret < 0)
2959         {
2960           ERR ("recv finished", ret);
2961           gnutls_assert ();
2962           return ret;
2963         }
2964       STATE = STATE0;
2965     default:
2966       break;
2967     }
2968
2969
2970   return 0;
2971 }
2972
2973 /*
2974  * _gnutls_handshake_server
2975  * This function does the server stuff of the handshake protocol.
2976  */
2977 int
2978 _gnutls_handshake_server (gnutls_session_t session)
2979 {
2980   int ret = 0;
2981
2982   switch (STATE)
2983     {
2984     case STATE0:
2985     case STATE1:
2986       ret =
2987         _gnutls_recv_handshake (session, NULL, NULL,
2988                                 GNUTLS_HANDSHAKE_CLIENT_HELLO,
2989                                 MANDATORY_PACKET);
2990       STATE = STATE1;
2991       IMED_RET ("recv hello", ret, 1);
2992
2993     case STATE2:
2994       ret = _gnutls_send_hello (session, AGAIN (STATE2));
2995       STATE = STATE2;
2996       IMED_RET ("send hello", ret, 1);
2997
2998     case STATE70:
2999       if (session->security_parameters.do_send_supplemental)
3000         {
3001           ret = _gnutls_send_supplemental (session, AGAIN (STATE70));
3002           STATE = STATE70;
3003           IMED_RET ("send supplemental data", ret, 0);
3004         }
3005
3006       /* SEND CERTIFICATE + KEYEXCHANGE + CERTIFICATE_REQUEST */
3007     case STATE3:
3008       /* NOTE: these should not be send if we are resuming */
3009
3010       if (session->internals.resumed == RESUME_FALSE)
3011         ret = _gnutls_send_server_certificate (session, AGAIN (STATE3));
3012       STATE = STATE3;
3013       IMED_RET ("send server certificate", ret, 0);
3014
3015     case STATE4:
3016       /* send server key exchange (A) */
3017       if (session->internals.resumed == RESUME_FALSE)
3018         ret = _gnutls_send_server_kx_message (session, AGAIN (STATE4));
3019       STATE = STATE4;
3020       IMED_RET ("send server kx", ret, 0);
3021
3022     case STATE5:
3023       /* Send certificate request - if requested to */
3024       if (session->internals.resumed == RESUME_FALSE)
3025         ret =
3026           _gnutls_send_server_certificate_request (session, AGAIN (STATE5));
3027       STATE = STATE5;
3028       IMED_RET ("send server cert request", ret, 0);
3029
3030     case STATE6:
3031       /* send the server hello done */
3032       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
3033         ret =
3034           _gnutls_send_empty_handshake (session,
3035                                         GNUTLS_HANDSHAKE_SERVER_HELLO_DONE,
3036                                         AGAIN (STATE6));
3037       STATE = STATE6;
3038       IMED_RET ("send server hello done", ret, 1);
3039
3040     case STATE71:
3041       if (session->security_parameters.do_recv_supplemental)
3042         {
3043           ret = _gnutls_recv_supplemental (session);
3044           STATE = STATE71;
3045           IMED_RET ("recv client supplemental", ret, 1);
3046         }
3047
3048       /* RECV CERTIFICATE + KEYEXCHANGE + CERTIFICATE_VERIFY */
3049     case STATE7:
3050       /* receive the client certificate message */
3051       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
3052         ret = _gnutls_recv_client_certificate (session);
3053       STATE = STATE7;
3054       IMED_RET ("recv client certificate", ret, 1);
3055
3056     case STATE8:
3057       /* receive the client key exchange message */
3058       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
3059         ret = _gnutls_recv_client_kx_message (session);
3060       STATE = STATE8;
3061       IMED_RET ("recv client kx", ret, 1);
3062
3063     case STATE9:
3064       /* receive the client certificate verify message */
3065       if (session->internals.resumed == RESUME_FALSE)   /* if we are not resuming */
3066         ret = _gnutls_recv_client_certificate_verify_message (session);
3067       STATE = STATE9;
3068       IMED_RET ("recv client certificate verify", ret, 1);
3069
3070       STATE = STATE0;           /* finished thus clear session */
3071     default:
3072       break;
3073     }
3074
3075   return 0;
3076 }
3077
3078 int
3079 _gnutls_handshake_common (gnutls_session_t session)
3080 {
3081   int ret = 0;
3082
3083   /* send and recv the change cipher spec and finished messages */
3084   if ((session->internals.resumed == RESUME_TRUE
3085        && session->security_parameters.entity == GNUTLS_CLIENT)
3086       || (session->internals.resumed == RESUME_FALSE
3087           && session->security_parameters.entity == GNUTLS_SERVER))
3088     {
3089       /* if we are a client resuming - or we are a server not resuming */
3090
3091       ret = _gnutls_recv_handshake_final (session, TRUE);
3092       IMED_RET ("recv handshake final", ret, 1);
3093
3094 #ifdef ENABLE_SESSION_TICKET
3095       switch (STATE)
3096         {
3097         case STATE0:
3098         case STATE40:
3099           ret = _gnutls_send_new_session_ticket (session, AGAIN (STATE40));
3100           STATE = STATE40;
3101           IMED_RET ("send handshake new session ticket", ret, 0);
3102           STATE = STATE0;
3103         default:
3104           break;
3105         }
3106 #endif
3107
3108       ret = _gnutls_send_handshake_final (session, FALSE);
3109       IMED_RET ("send handshake final", ret, 1);
3110
3111       /* only store if we are not resuming */
3112       if (session->security_parameters.entity == GNUTLS_SERVER)
3113         {
3114           /* in order to support session resuming */
3115           _gnutls_server_register_current_session (session);
3116         }
3117     }
3118   else
3119     {                           /* if we are a client not resuming - or we are a server resuming */
3120
3121       ret = _gnutls_send_handshake_final (session, TRUE);
3122       IMED_RET ("send handshake final 2", ret, 1);
3123
3124 #ifdef ENABLE_SESSION_TICKET
3125       switch (STATE)
3126         {
3127         case STATE0:
3128         case STATE41:
3129           ret = _gnutls_recv_new_session_ticket (session);
3130           STATE = STATE41;
3131           IMED_RET ("recv handshake new session ticket", ret, 1);
3132           STATE = STATE0;
3133         default:
3134           break;
3135         }
3136 #endif
3137
3138       ret = _gnutls_recv_handshake_final (session, FALSE);
3139       IMED_RET ("recv handshake final 2", ret, 1);
3140
3141     }
3142
3143
3144   /* clear handshake buffer */
3145   _gnutls_handshake_hash_buffers_clear (session);
3146   return ret;
3147
3148 }
3149
3150 int
3151 _gnutls_generate_session_id (opaque * session_id, uint8_t * len)
3152 {
3153   int ret;
3154
3155   *len = TLS_MAX_SESSION_ID_SIZE;
3156
3157   ret = _gnutls_rnd (GNUTLS_RND_NONCE, session_id, *len);
3158   if (ret < 0)
3159     {
3160       gnutls_assert ();
3161       return ret;
3162     }
3163
3164   return 0;
3165 }
3166
3167 int
3168 _gnutls_recv_hello_request (gnutls_session_t session, void *data,
3169                             uint32_t data_size)
3170 {
3171   uint8_t type;
3172
3173   if (session->security_parameters.entity == GNUTLS_SERVER)
3174     {
3175       gnutls_assert ();
3176       return GNUTLS_E_UNEXPECTED_PACKET;
3177     }
3178   if (data_size < 1)
3179     {
3180       gnutls_assert ();
3181       return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
3182     }
3183   type = ((uint8_t *) data)[0];
3184   if (type == GNUTLS_HANDSHAKE_HELLO_REQUEST)
3185     return GNUTLS_E_REHANDSHAKE;
3186   else
3187     {
3188       gnutls_assert ();
3189       return GNUTLS_E_UNEXPECTED_PACKET;
3190     }
3191 }
3192
3193 /* Returns 1 if the given KX has not the corresponding parameters
3194  * (DH or RSA) set up. Otherwise returns 0.
3195  */
3196 inline static int
3197 check_server_params (gnutls_session_t session,
3198                      gnutls_kx_algorithm_t kx,
3199                      gnutls_kx_algorithm_t * alg, int alg_size)
3200 {
3201   int cred_type;
3202   gnutls_dh_params_t dh_params = NULL;
3203   gnutls_rsa_params_t rsa_params = NULL;
3204   int j;
3205
3206   cred_type = _gnutls_map_kx_get_cred (kx, 1);
3207
3208   /* Read the Diffie-Hellman parameters, if any.
3209    */
3210   if (cred_type == GNUTLS_CRD_CERTIFICATE)
3211     {
3212       int delete;
3213       gnutls_certificate_credentials_t x509_cred =
3214         (gnutls_certificate_credentials_t) _gnutls_get_cred (session->key,
3215                                                              cred_type, NULL);
3216
3217       if (x509_cred != NULL)
3218         {
3219           dh_params =
3220             _gnutls_get_dh_params (x509_cred->dh_params,
3221                                    x509_cred->params_func, session);
3222           rsa_params =
3223             _gnutls_certificate_get_rsa_params (x509_cred->rsa_params,
3224                                                 x509_cred->params_func,
3225                                                 session);
3226         }
3227
3228       /* Check also if the certificate supports the
3229        * KX method.
3230        */
3231       delete = 1;
3232       for (j = 0; j < alg_size; j++)
3233         {
3234           if (alg[j] == kx)
3235             {
3236               delete = 0;
3237               break;
3238             }
3239         }
3240
3241       if (delete == 1)
3242         return 1;
3243
3244 #ifdef ENABLE_ANON
3245     }
3246   else if (cred_type == GNUTLS_CRD_ANON)
3247     {
3248       gnutls_anon_server_credentials_t anon_cred =
3249         (gnutls_anon_server_credentials_t) _gnutls_get_cred (session->key,
3250                                                              cred_type, NULL);
3251
3252       if (anon_cred != NULL)
3253         {
3254           dh_params =
3255             _gnutls_get_dh_params (anon_cred->dh_params,
3256                                    anon_cred->params_func, session);
3257         }
3258 #endif
3259 #ifdef ENABLE_PSK
3260     }
3261   else if (cred_type == GNUTLS_CRD_PSK)
3262     {
3263       gnutls_psk_server_credentials_t psk_cred =
3264         (gnutls_psk_server_credentials_t) _gnutls_get_cred (session->key,
3265                                                             cred_type, NULL);
3266
3267       if (psk_cred != NULL)
3268         {
3269           dh_params =
3270             _gnutls_get_dh_params (psk_cred->dh_params, psk_cred->params_func,
3271                                    session);
3272         }
3273 #endif
3274     }
3275   else
3276     return 0;                   /* no need for params */
3277
3278
3279   /* If the key exchange method needs RSA or DH params,
3280    * but they are not set then remove it.
3281    */
3282   if (_gnutls_kx_needs_rsa_params (kx) != 0)
3283     {
3284       /* needs rsa params. */
3285       if (_gnutls_rsa_params_to_mpi (rsa_params) == NULL)
3286         {
3287           gnutls_assert ();
3288           return 1;
3289         }
3290     }
3291
3292   if (_gnutls_kx_needs_dh_params (kx) != 0)
3293     {
3294       /* needs DH params. */
3295       if (_gnutls_dh_params_to_mpi (dh_params) == NULL)
3296         {
3297           gnutls_assert ();
3298           return 1;
3299         }
3300     }
3301
3302   return 0;
3303 }
3304
3305 /* This function will remove algorithms that are not supported by
3306  * the requested authentication method. We remove an algorithm if
3307  * we have a certificate with keyUsage bits set.
3308  *
3309  * This does a more high level check than  gnutls_supported_ciphersuites(),
3310  * by checking certificates etc.
3311  */
3312 int
3313 _gnutls_remove_unwanted_ciphersuites (gnutls_session_t session,
3314                                       cipher_suite_st ** cipherSuites,
3315                                       int numCipherSuites,
3316                                       gnutls_pk_algorithm_t requested_pk_algo)
3317 {
3318
3319   int ret = 0;
3320   cipher_suite_st *newSuite, cs;
3321   int newSuiteSize = 0, i;
3322   gnutls_certificate_credentials_t cert_cred;
3323   gnutls_kx_algorithm_t kx;
3324   int server = session->security_parameters.entity == GNUTLS_SERVER ? 1 : 0;
3325   gnutls_kx_algorithm_t *alg = NULL;
3326   int alg_size = 0;
3327
3328   /* if we should use a specific certificate, 
3329    * we should remove all algorithms that are not supported
3330    * by that certificate and are on the same authentication
3331    * method (CERTIFICATE).
3332    */
3333
3334   cert_cred =
3335     (gnutls_certificate_credentials_t) _gnutls_get_cred (session->key,
3336                                                          GNUTLS_CRD_CERTIFICATE,
3337                                                          NULL);
3338
3339   /* If there are certificate credentials, find an appropriate certificate
3340    * or disable them;
3341    */
3342   if (session->security_parameters.entity == GNUTLS_SERVER
3343       && cert_cred != NULL)
3344     {
3345       ret = _gnutls_server_select_cert (session, requested_pk_algo);
3346       if (ret < 0)
3347         {
3348           gnutls_assert ();
3349           _gnutls_x509_log ("Could not find an appropriate certificate: %s\n",
3350                             gnutls_strerror (ret));
3351           cert_cred = NULL;
3352         }
3353     }
3354
3355   /* get all the key exchange algorithms that are 
3356    * supported by the X509 certificate parameters.
3357    */
3358   if ((ret =
3359        _gnutls_selected_cert_supported_kx (session, &alg, &alg_size)) < 0)
3360     {
3361       gnutls_assert ();
3362       return ret;
3363     }
3364
3365   newSuite = gnutls_malloc (numCipherSuites * sizeof (cipher_suite_st));
3366   if (newSuite == NULL)
3367     {
3368       gnutls_assert ();
3369       gnutls_free (alg);
3370       return GNUTLS_E_MEMORY_ERROR;
3371     }
3372
3373   /* now removes ciphersuites based on the KX algorithm
3374    */
3375   for (i = 0; i < numCipherSuites; i++)
3376     {
3377       int delete = 0;
3378
3379       /* finds the key exchange algorithm in
3380        * the ciphersuite
3381        */
3382       kx = _gnutls_cipher_suite_get_kx_algo (&(*cipherSuites)[i]);
3383
3384       /* if it is defined but had no credentials 
3385        */
3386       if (_gnutls_get_kx_cred (session, kx, NULL) == NULL)
3387         {
3388           delete = 1;
3389         }
3390       else
3391         {
3392           delete = 0;
3393
3394           if (server)
3395             delete = check_server_params (session, kx, alg, alg_size);
3396         }
3397
3398       /* These two SRP kx's are marked to require a CRD_CERTIFICATE,
3399          (see cred_mappings in gnutls_algorithms.c), but it also
3400          requires a SRP credential.  Don't use SRP kx unless we have a
3401          SRP credential too.  */
3402       if (kx == GNUTLS_KX_SRP_RSA || kx == GNUTLS_KX_SRP_DSS)
3403         {
3404           if (!_gnutls_get_cred (session->key, GNUTLS_CRD_SRP, NULL))
3405             delete = 1;
3406         }
3407
3408       memcpy (&cs.suite, &(*cipherSuites)[i].suite, 2);
3409
3410       if (delete == 0)
3411         {
3412
3413           _gnutls_handshake_log ("HSK[%p]: Keeping ciphersuite: %s\n",
3414                                  session,
3415                                  _gnutls_cipher_suite_get_name (&cs));
3416
3417           memcpy (newSuite[newSuiteSize].suite, (*cipherSuites)[i].suite, 2);
3418           newSuiteSize++;
3419         }
3420       else
3421         {
3422           _gnutls_handshake_log ("HSK[%p]: Removing ciphersuite: %s\n",
3423                                  session,
3424                                  _gnutls_cipher_suite_get_name (&cs));
3425
3426         }
3427     }
3428
3429   gnutls_free (alg);
3430   gnutls_free (*cipherSuites);
3431   *cipherSuites = newSuite;
3432
3433   ret = newSuiteSize;
3434
3435   return ret;
3436
3437 }
3438
3439 /**
3440  * gnutls_handshake_set_max_packet_length:
3441  * @session: is a #gnutls_session_t structure.
3442  * @max: is the maximum number.
3443  *
3444  * This function will set the maximum size of all handshake messages.
3445  * Handshakes over this size are rejected with
3446  * %GNUTLS_E_HANDSHAKE_TOO_LARGE error code.  The default value is
3447  * 48kb which is typically large enough.  Set this to 0 if you do not
3448  * want to set an upper limit.
3449  *
3450  * The reason for restricting the handshake message sizes are to
3451  * limit Denial of Service attacks.
3452  **/
3453 void
3454 gnutls_handshake_set_max_packet_length (gnutls_session_t session, size_t max)
3455 {
3456   session->internals.max_handshake_data_buffer_size = max;
3457 }
3458
3459 void
3460 _gnutls_set_adv_version (gnutls_session_t session, gnutls_protocol_t ver)
3461 {
3462   set_adv_version (session, _gnutls_version_get_major (ver),
3463                    _gnutls_version_get_minor (ver));
3464 }
3465
3466 gnutls_protocol_t
3467 _gnutls_get_adv_version (gnutls_session_t session)
3468 {
3469   return _gnutls_version_get (_gnutls_get_adv_version_major (session),
3470                               _gnutls_get_adv_version_minor (session));
3471 }
3472
3473 /**
3474  * gnutls_handshake_get_last_in:
3475  * @session: is a #gnutls_session_t structure.
3476  *
3477  * This function is only useful to check where the last performed
3478  * handshake failed.  If the previous handshake succeed or was not
3479  * performed at all then no meaningful value will be returned.
3480  *
3481  * Check %gnutls_handshake_description_t in gnutls.h for the
3482  * available handshake descriptions.
3483  *
3484  * Returns: the last handshake message type received, a
3485  * %gnutls_handshake_description_t.
3486  **/
3487 gnutls_handshake_description_t
3488 gnutls_handshake_get_last_in (gnutls_session_t session)
3489 {
3490   return session->internals.last_handshake_in;
3491 }
3492
3493 /**
3494  * gnutls_handshake_get_last_out:
3495  * @session: is a #gnutls_session_t structure.
3496  *
3497  * This function is only useful to check where the last performed
3498  * handshake failed.  If the previous handshake succeed or was not
3499  * performed at all then no meaningful value will be returned.
3500  *
3501  * Check %gnutls_handshake_description_t in gnutls.h for the
3502  * available handshake descriptions.
3503  *
3504  * Returns: the last handshake message type sent, a
3505  * %gnutls_handshake_description_t.
3506  **/
3507 gnutls_handshake_description_t
3508 gnutls_handshake_get_last_out (gnutls_session_t session)
3509 {
3510   return session->internals.last_handshake_out;
3511 }