added comments
[gnutls:gnutls.git] / lib / gnutls_handshake.c
1 /*
2  * Copyright (C) 2000-2014 Free Software Foundation, Inc.
3  *
4  * Author: Nikos Mavrogiannopoulos
5  *
6  * This file is part of GnuTLS.
7  *
8  * The GnuTLS is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * as published by the Free Software Foundation; either version 2.1 of
11  * the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>
20  *
21  */
22
23 /* Functions that relate to the TLS handshake procedure.
24  */
25
26 #include "gnutls_int.h"
27 #include "gnutls_errors.h"
28 #include "gnutls_dh.h"
29 #include "debug.h"
30 #include "algorithms.h"
31 #include "gnutls_compress.h"
32 #include "gnutls_cipher.h"
33 #include "gnutls_buffers.h"
34 #include "gnutls_mbuffers.h"
35 #include "gnutls_kx.h"
36 #include "gnutls_handshake.h"
37 #include "gnutls_num.h"
38 #include "gnutls_hash_int.h"
39 #include "gnutls_db.h"
40 #include "gnutls_extensions.h"
41 #include "gnutls_supplemental.h"
42 #include "gnutls_auth.h"
43 #include "gnutls_v2_compat.h"
44 #include <auth/cert.h>
45 #include "gnutls_constate.h"
46 #include <gnutls_record.h>
47 #include <gnutls_state.h>
48 #include <ext/srp.h>
49 #include <ext/session_ticket.h>
50 #include <ext/status_request.h>
51 #include <ext/safe_renegotiation.h>
52 #include <auth/anon.h>          /* for gnutls_anon_server_credentials_t */
53 #include <auth/psk.h>           /* for gnutls_psk_server_credentials_t */
54 #include <random.h>
55 #include <gnutls_dtls.h>
56
57 #ifdef HANDSHAKE_DEBUG
58 #define ERR(x, y) _gnutls_handshake_log("HSK[%p]: %s (%d)\n", session, x,y)
59 #else
60 #define ERR(x, y)
61 #endif
62
63 #define TRUE 1
64 #define FALSE 0
65
66 static int server_select_comp_method(gnutls_session_t session,
67                                              uint8_t * data, int datalen);
68 static int handshake_client(gnutls_session_t session);
69 static int handshake_server(gnutls_session_t session);
70
71 static int
72 recv_hello(gnutls_session_t session, uint8_t * data, int datalen);
73
74 static int
75 recv_handshake_final(gnutls_session_t session, int init);
76 static int
77 send_handshake_final(gnutls_session_t session, int init);
78
79 /* Empties but does not free the buffer
80  */
81 static inline void
82 handshake_hash_buffer_empty(gnutls_session_t session)
83 {
84
85         _gnutls_buffers_log("BUF[HSK]: Emptied buffer\n");
86
87         session->internals.handshake_hash_buffer_prev_len = 0;
88         session->internals.handshake_hash_buffer.length = 0;
89         return;
90 }
91
92 static int
93 handshake_hash_add_recvd(gnutls_session_t session,
94                                  gnutls_handshake_description_t recv_type,
95                                  uint8_t * header, uint16_t header_size,
96                                  uint8_t * dataptr, uint32_t datalen);
97
98 static int
99 handshake_hash_add_sent(gnutls_session_t session,
100                                 gnutls_handshake_description_t type,
101                                 uint8_t * dataptr, uint32_t datalen);
102
103 static int
104 recv_hello_verify_request(gnutls_session_t session,
105                                   uint8_t * data, int datalen);
106
107
108 /* Clears the handshake hash buffers and handles.
109  */
110 void _gnutls_handshake_hash_buffers_clear(gnutls_session_t session)
111 {
112         session->internals.handshake_hash_buffer_prev_len = 0;
113         session->internals.handshake_hash_buffer_client_kx_len = 0;
114         _gnutls_buffer_clear(&session->internals.handshake_hash_buffer);
115 }
116
117 /* this will copy the required values for resuming to
118  * internals, and to security_parameters.
119  * this will keep as less data to security_parameters.
120  */
121 static int resume_copy_required_values(gnutls_session_t session)
122 {
123         int ret;
124
125         /* get the new random values */
126         memcpy(session->internals.resumed_security_parameters.
127                server_random, session->security_parameters.server_random,
128                GNUTLS_RANDOM_SIZE);
129         memcpy(session->internals.resumed_security_parameters.
130                client_random, session->security_parameters.client_random,
131                GNUTLS_RANDOM_SIZE);
132
133         /* keep the ciphersuite and compression 
134          * That is because the client must see these in our
135          * hello message.
136          */
137         memcpy(session->security_parameters.cipher_suite,
138                session->internals.resumed_security_parameters.cipher_suite,
139                2);
140         session->security_parameters.compression_method =
141             session->internals.resumed_security_parameters.
142             compression_method;
143
144         ret = _gnutls_epoch_set_cipher_suite(session, EPOCH_NEXT,
145                                              session->internals.
146                                              resumed_security_parameters.
147                                              cipher_suite);
148         if (ret < 0)
149                 return gnutls_assert_val(ret);
150
151         ret = _gnutls_epoch_set_compression(session, EPOCH_NEXT,
152                                             session->internals.
153                                             resumed_security_parameters.
154                                             compression_method);
155         if (ret < 0)
156                 return gnutls_assert_val(ret);
157
158         /* or write_compression_algorithm
159          * they are the same
160          */
161
162         session->security_parameters.entity =
163             session->internals.resumed_security_parameters.entity;
164
165         if (session->internals.resumed_security_parameters.pversion ==
166             NULL)
167                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
168
169         if (_gnutls_set_current_version(session,
170                                     session->internals.
171                                     resumed_security_parameters.pversion->
172                                     id) < 0)
173                 return gnutls_assert_val(GNUTLS_E_UNSUPPORTED_VERSION_PACKET);
174
175         session->security_parameters.cert_type =
176             session->internals.resumed_security_parameters.cert_type;
177
178         memcpy(session->security_parameters.session_id,
179                session->internals.resumed_security_parameters.session_id,
180                sizeof(session->security_parameters.session_id));
181         session->security_parameters.session_id_size =
182             session->internals.resumed_security_parameters.session_id_size;
183
184         return 0;
185 }
186
187
188 /* this function will produce GNUTLS_RANDOM_SIZE==32 bytes of random data
189  * and put it to dst.
190  */
191 static int create_tls_random(uint8_t * dst)
192 {
193         uint32_t tim;
194         int ret;
195
196         /* Use weak random numbers for the most of the
197          * buffer except for the first 4 that are the
198          * system's time.
199          */
200
201         tim = gnutls_time(NULL);
202         /* generate server random value */
203         _gnutls_write_uint32(tim, dst);
204
205         ret =
206             _gnutls_rnd(GNUTLS_RND_NONCE, &dst[3], GNUTLS_RANDOM_SIZE - 3);
207         if (ret < 0) {
208                 gnutls_assert();
209                 return ret;
210         }
211
212         return 0;
213 }
214
215 int _gnutls_set_client_random(gnutls_session_t session, uint8_t * rnd)
216 {
217         int ret;
218
219         if (rnd != NULL)
220                 memcpy(session->security_parameters.client_random, rnd,
221                        GNUTLS_RANDOM_SIZE);
222         else {
223                 /* no random given, we generate. */
224                 if (session->internals.sc_random_set != 0) {
225                         memcpy(session->security_parameters.client_random,
226                                session->internals.
227                                resumed_security_parameters.client_random,
228                                GNUTLS_RANDOM_SIZE);
229                 } else {
230                         ret =
231                             create_tls_random(session->
232                                               security_parameters.
233                                               client_random);
234                         if (ret < 0)
235                                 return gnutls_assert_val(ret);
236                 }
237         }
238         return 0;
239 }
240
241 int _gnutls_set_server_random(gnutls_session_t session, uint8_t * rnd)
242 {
243         int ret;
244
245         if (rnd != NULL)
246                 memcpy(session->security_parameters.server_random, rnd,
247                        GNUTLS_RANDOM_SIZE);
248         else {
249                 /* no random given, we generate. */
250                 if (session->internals.sc_random_set != 0) {
251                         memcpy(session->security_parameters.server_random,
252                                session->internals.
253                                resumed_security_parameters.server_random,
254                                GNUTLS_RANDOM_SIZE);
255                 } else {
256                         ret =
257                             create_tls_random(session->
258                                               security_parameters.
259                                               server_random);
260                         if (ret < 0)
261                                 return gnutls_assert_val(ret);
262                 }
263         }
264         return 0;
265 }
266
267 /* Calculate The SSL3 Finished message
268  */
269 #define SSL3_CLIENT_MSG "CLNT"
270 #define SSL3_SERVER_MSG "SRVR"
271 #define SSL_MSG_LEN 4
272 static int
273 _gnutls_ssl3_finished(gnutls_session_t session, int type, uint8_t * ret,
274                       int sending)
275 {
276         digest_hd_st td_md5;
277         digest_hd_st td_sha;
278         const char *mesg;
279         int rc, len;
280
281         if (sending)
282                 len = session->internals.handshake_hash_buffer.length;
283         else
284                 len = session->internals.handshake_hash_buffer_prev_len;
285
286         rc = _gnutls_hash_init(&td_sha, hash_to_entry(GNUTLS_DIG_SHA1));
287         if (rc < 0)
288                 return gnutls_assert_val(rc);
289
290         rc = _gnutls_hash_init(&td_md5, hash_to_entry(GNUTLS_DIG_MD5));
291         if (rc < 0) {
292                 _gnutls_hash_deinit(&td_sha, NULL);
293                 return gnutls_assert_val(rc);
294         }
295
296         _gnutls_hash(&td_sha,
297                      session->internals.handshake_hash_buffer.data, len);
298         _gnutls_hash(&td_md5,
299                      session->internals.handshake_hash_buffer.data, len);
300
301         if (type == GNUTLS_SERVER)
302                 mesg = SSL3_SERVER_MSG;
303         else
304                 mesg = SSL3_CLIENT_MSG;
305
306         _gnutls_hash(&td_md5, mesg, SSL_MSG_LEN);
307         _gnutls_hash(&td_sha, mesg, SSL_MSG_LEN);
308
309         rc = _gnutls_mac_deinit_ssl3_handshake(&td_md5, ret,
310                                                session->security_parameters.
311                                                master_secret,
312                                                GNUTLS_MASTER_SIZE);
313         if (rc < 0) {
314                 _gnutls_hash_deinit(&td_md5, NULL);
315                 _gnutls_hash_deinit(&td_sha, NULL);
316                 return gnutls_assert_val(rc);
317         }
318
319         rc = _gnutls_mac_deinit_ssl3_handshake(&td_sha, &ret[16],
320                                                session->security_parameters.
321                                                master_secret,
322                                                GNUTLS_MASTER_SIZE);
323         if (rc < 0) {
324                 _gnutls_hash_deinit(&td_sha, NULL);
325                 return gnutls_assert_val(rc);
326         }
327
328         return 0;
329 }
330
331 /* Hash the handshake messages as required by TLS 1.0
332  */
333 #define SERVER_MSG "server finished"
334 #define CLIENT_MSG "client finished"
335 #define TLS_MSG_LEN 15
336 static int
337 _gnutls_finished(gnutls_session_t session, int type, void *ret,
338                  int sending)
339 {
340         const int siz = TLS_MSG_LEN;
341         uint8_t concat[MAX_HASH_SIZE + 16 /*MD5 */ ];
342         size_t hash_len;
343         const char *mesg;
344         int rc, len;
345
346         if (sending)
347                 len = session->internals.handshake_hash_buffer.length;
348         else
349                 len = session->internals.handshake_hash_buffer_prev_len;
350
351         if (!_gnutls_version_has_selectable_prf(get_version(session))) {
352                 rc = _gnutls_hash_fast(GNUTLS_DIG_SHA1,
353                                        session->internals.
354                                        handshake_hash_buffer.data, len,
355                                        &concat[16]);
356                 if (rc < 0)
357                         return gnutls_assert_val(rc);
358
359                 rc = _gnutls_hash_fast(GNUTLS_DIG_MD5,
360                                        session->internals.
361                                        handshake_hash_buffer.data, len,
362                                        concat);
363                 if (rc < 0)
364                         return gnutls_assert_val(rc);
365
366                 hash_len = 20 + 16;
367         } else {
368                 int algorithm =
369                     _gnutls_cipher_suite_get_prf(session->
370                                                  security_parameters.
371                                                  cipher_suite);
372
373                 rc = _gnutls_hash_fast(algorithm,
374                                        session->internals.
375                                        handshake_hash_buffer.data, len,
376                                        concat);
377                 if (rc < 0)
378                         return gnutls_assert_val(rc);
379
380                 hash_len =
381                     _gnutls_hash_get_algo_len(mac_to_entry(algorithm));
382         }
383
384         if (type == GNUTLS_SERVER) {
385                 mesg = SERVER_MSG;
386         } else {
387                 mesg = CLIENT_MSG;
388         }
389
390         return _gnutls_PRF(session,
391                            session->security_parameters.master_secret,
392                            GNUTLS_MASTER_SIZE, mesg, siz, concat, hash_len,
393                            12, ret);
394 }
395
396
397 /* returns the 0 on success or a negative error code.
398  */
399 int
400 _gnutls_negotiate_version(gnutls_session_t session,
401                           gnutls_protocol_t adv_version)
402 {
403         int ret;
404
405         /* if we do not support that version  */
406         if (_gnutls_version_is_supported(session, adv_version) == 0) {
407                 /* If he requested something we do not support
408                  * then we send him the highest we support.
409                  */
410                 ret = _gnutls_version_max(session);
411                 if (ret == GNUTLS_VERSION_UNKNOWN) {
412                         /* this check is not really needed.
413                          */
414                         gnutls_assert();
415                         return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
416                 }
417         } else {
418                 ret = adv_version;
419         }
420
421         if (_gnutls_set_current_version(session, ret) < 0)
422                 return gnutls_assert_val(GNUTLS_E_UNSUPPORTED_VERSION_PACKET);
423
424         return ret;
425 }
426
427 /* This function returns:
428  *  - zero on success
429  *  - GNUTLS_E_INT_RET_0 if GNUTLS_E_AGAIN || GNUTLS_E_INTERRUPTED were returned by the callback
430  *  - a negative error code on other error
431  */
432 int
433 _gnutls_user_hello_func(gnutls_session_t session,
434                         gnutls_protocol_t adv_version)
435 {
436         int ret, sret = 0;
437
438         if (session->internals.user_hello_func != NULL) {
439                 ret = session->internals.user_hello_func(session);
440
441                 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) {
442                         gnutls_assert();
443                         sret = GNUTLS_E_INT_RET_0;
444                 } else if (ret < 0) {
445                         gnutls_assert();
446                         return ret;
447                 }
448
449                 /* Here we need to renegotiate the version since the callee might
450                  * have disabled some TLS versions.
451                  */
452                 ret = _gnutls_negotiate_version(session, adv_version);
453                 if (ret < 0) {
454                         gnutls_assert();
455                         return ret;
456                 }
457         }
458         return sret;
459 }
460
461 /* Read a client hello packet. 
462  * A client hello must be a known version client hello
463  * or version 2.0 client hello (only for compatibility
464  * since SSL version 2.0 is not supported).
465  */
466 static int
467 read_client_hello(gnutls_session_t session, uint8_t * data,
468                           int datalen)
469 {
470         uint8_t session_id_len;
471         int pos = 0, ret;
472         uint16_t suite_size, comp_size;
473         gnutls_protocol_t adv_version;
474         int neg_version, sret = 0;
475         int len = datalen;
476         uint8_t *suite_ptr, *comp_ptr, *session_id;
477
478         DECR_LEN(len, 2);
479
480         _gnutls_handshake_log("HSK[%p]: Client's version: %d.%d\n",
481                               session, data[pos], data[pos + 1]);
482
483         adv_version = _gnutls_version_get(data[pos], data[pos + 1]);
484
485         set_adv_version(session, data[pos], data[pos + 1]);
486         pos += 2;
487
488         neg_version = _gnutls_negotiate_version(session, adv_version);
489         if (neg_version < 0) {
490                 gnutls_assert();
491                 return neg_version;
492         }
493
494         _gnutls_handshake_log("HSK[%p]: Selected version %s\n",
495                      session, gnutls_protocol_get_name(neg_version));
496
497         /* Read client random value.
498          */
499         DECR_LEN(len, GNUTLS_RANDOM_SIZE);
500         ret = _gnutls_set_client_random(session, &data[pos]);
501         if (ret < 0)
502                 return gnutls_assert_val(ret);
503
504         pos += GNUTLS_RANDOM_SIZE;
505
506         ret = _gnutls_set_server_random(session, NULL);
507         if (ret < 0)
508                 return gnutls_assert_val(ret);
509
510         session->security_parameters.timestamp = gnutls_time(NULL);
511
512         DECR_LEN(len, 1);
513         session_id_len = data[pos++];
514
515         /* RESUME SESSION 
516          */
517         if (session_id_len > GNUTLS_MAX_SESSION_ID_SIZE) {
518                 gnutls_assert();
519                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
520         }
521         DECR_LEN(len, session_id_len);
522         session_id = &data[pos];
523         pos += session_id_len;
524
525         if (IS_DTLS(session)) {
526                 int cookie_size;
527
528                 DECR_LEN(len, 1);
529                 cookie_size = data[pos++];
530                 DECR_LEN(len, cookie_size);
531                 pos += cookie_size;
532         }
533
534         ret =
535             _gnutls_server_restore_session(session, session_id,
536                                            session_id_len);
537
538         if (session_id_len > 0)
539                 session->internals.resumption_requested = 1;
540
541         if (ret == 0) {         /* resumed using default TLS resumption! */
542                 /* Parse only the safe renegotiation extension
543                  * We don't want to parse any other extensions since
544                  * we don't want new extension values to overwrite the
545                  * resumed ones.
546                  */
547
548                 /* move forward to extensions */
549                 DECR_LEN(len, 2);
550                 suite_size = _gnutls_read_uint16(&data[pos]);
551                 pos += 2;
552
553                 DECR_LEN(len, suite_size);
554                 pos += suite_size;
555
556                 DECR_LEN(len, 1);
557                 comp_size = data[pos++];        /* z is the number of compression methods */
558                 DECR_LEN(len, comp_size);
559                 pos += comp_size;
560
561                 ret =
562                     _gnutls_parse_extensions(session, GNUTLS_EXT_MANDATORY,
563                                              &data[pos], len);
564                 if (ret < 0) {
565                         gnutls_assert();
566                         return ret;
567                 }
568
569                 ret = resume_copy_required_values(session);
570                 if (ret < 0)
571                         return gnutls_assert_val(ret);
572
573                 session->internals.resumed = RESUME_TRUE;
574
575                 return _gnutls_user_hello_func(session, adv_version);
576         } else {
577                 _gnutls_generate_session_id(session->security_parameters.
578                                             session_id,
579                                             &session->security_parameters.
580                                             session_id_size);
581
582                 session->internals.resumed = RESUME_FALSE;
583         }
584
585         /* Remember ciphersuites for later
586          */
587         DECR_LEN(len, 2);
588         suite_size = _gnutls_read_uint16(&data[pos]);
589         pos += 2;
590
591         DECR_LEN(len, suite_size);
592         suite_ptr = &data[pos];
593         pos += suite_size;
594
595         /* Point to the compression methods
596          */
597         DECR_LEN(len, 1);
598         comp_size = data[pos++];        /* z is the number of compression methods */
599
600         DECR_LEN(len, comp_size);
601         comp_ptr = &data[pos];
602         pos += comp_size;
603
604         /* Parse the extensions (if any)
605          *
606          * Unconditionally try to parse extensions; safe renegotiation uses them in
607          * sslv3 and higher, even though sslv3 doesn't officially support them.
608          */
609         ret = _gnutls_parse_extensions(session, GNUTLS_EXT_APPLICATION,
610                                        &data[pos], len);
611         /* len is the rest of the parsed length */
612         if (ret < 0) {
613                 gnutls_assert();
614                 return ret;
615         }
616
617         /* we cache this error code */
618         sret = _gnutls_user_hello_func(session, adv_version);
619         if (sret < 0 && sret != GNUTLS_E_INT_RET_0) {
620                 gnutls_assert();
621                 return sret;
622         }
623
624         ret = _gnutls_parse_extensions(session, GNUTLS_EXT_MANDATORY,
625                                        &data[pos], len);
626         if (ret < 0) {
627                 gnutls_assert();
628                 return ret;
629         }
630
631         ret =
632             _gnutls_parse_extensions(session, GNUTLS_EXT_TLS, &data[pos],
633                                      len);
634         if (ret < 0) {
635                 gnutls_assert();
636                 return ret;
637         }
638
639         /* resumed by session_ticket extension */
640         if (session->internals.resumed != RESUME_FALSE) {
641                 /* to indicate the client that the current session is resumed */
642                 memcpy(session->internals.resumed_security_parameters.
643                        session_id, session_id, session_id_len);
644                 session->internals.resumed_security_parameters.
645                     session_id_size = session_id_len;
646
647                 session->internals.resumed_security_parameters.
648                     max_record_recv_size =
649                     session->security_parameters.max_record_recv_size;
650                 session->internals.resumed_security_parameters.
651                     max_record_send_size =
652                     session->security_parameters.max_record_send_size;
653
654                 ret = resume_copy_required_values(session);
655                 if (ret < 0)
656                         return gnutls_assert_val(ret);
657
658                 return 0;
659         }
660
661         /* select an appropriate cipher suite
662          */
663         ret = _gnutls_server_select_suite(session, suite_ptr, suite_size);
664         if (ret < 0) {
665                 gnutls_assert();
666                 return ret;
667         }
668
669         /* select appropriate compression method */
670         ret =
671             server_select_comp_method(session, comp_ptr,
672                                               comp_size);
673         if (ret < 0) {
674                 gnutls_assert();
675                 return ret;
676         }
677
678         return sret;
679 }
680
681 /* This is to be called after sending CHANGE CIPHER SPEC packet
682  * and initializing encryption. This is the first encrypted message
683  * we send.
684  */
685 static int _gnutls_send_finished(gnutls_session_t session, int again)
686 {
687         mbuffer_st *bufel;
688         uint8_t *data;
689         int ret;
690         size_t vdata_size = 0;
691         const version_entry_st *vers;
692
693         if (again == 0) {
694                 bufel =
695                     _gnutls_handshake_alloc(session, 
696                                             MAX_VERIFY_DATA_SIZE);
697                 if (bufel == NULL) {
698                         gnutls_assert();
699                         return GNUTLS_E_MEMORY_ERROR;
700                 }
701                 data = _mbuffer_get_udata_ptr(bufel);
702
703                 vers = get_version(session);
704                 if (unlikely(vers == NULL))
705                         return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
706
707                 if (vers->id == GNUTLS_SSL3) {
708                         ret =
709                             _gnutls_ssl3_finished(session,
710                                                   session->
711                                                   security_parameters.
712                                                   entity, data, 1);
713                         _mbuffer_set_udata_size(bufel, 36);
714                 } else {        /* TLS 1.0+ */
715                         ret = _gnutls_finished(session,
716                                                session->
717                                                security_parameters.entity,
718                                                data, 1);
719                         _mbuffer_set_udata_size(bufel, 12);
720                 }
721
722                 if (ret < 0) {
723                         gnutls_assert();
724                         return ret;
725                 }
726
727                 vdata_size = _mbuffer_get_udata_size(bufel);
728
729                 ret =
730                     _gnutls_ext_sr_finished(session, data, vdata_size, 0);
731                 if (ret < 0) {
732                         gnutls_assert();
733                         return ret;
734                 }
735
736                 if ((session->internals.resumed == RESUME_FALSE
737                      && session->security_parameters.entity ==
738                      GNUTLS_CLIENT)
739                     || (session->internals.resumed != RESUME_FALSE
740                         && session->security_parameters.entity ==
741                         GNUTLS_SERVER)) {
742                         /* if we are a client not resuming - or we are a server resuming */
743                         _gnutls_handshake_log
744                             ("HSK[%p]: recording tls-unique CB (send)\n",
745                              session);
746                         memcpy(session->internals.cb_tls_unique, data,
747                                vdata_size);
748                         session->internals.cb_tls_unique_len = vdata_size;
749                 }
750
751                 ret =
752                     _gnutls_send_handshake(session, bufel,
753                                            GNUTLS_HANDSHAKE_FINISHED);
754         } else {
755                 ret =
756                     _gnutls_send_handshake(session, NULL,
757                                            GNUTLS_HANDSHAKE_FINISHED);
758         }
759
760         return ret;
761 }
762
763 /* This is to be called after sending our finished message. If everything
764  * went fine we have negotiated a secure connection 
765  */
766 static int _gnutls_recv_finished(gnutls_session_t session)
767 {
768         uint8_t data[MAX_VERIFY_DATA_SIZE], *vrfy;
769         gnutls_buffer_st buf;
770         int data_size;
771         int ret;
772         int vrfy_size;
773         const version_entry_st *vers = get_version(session);
774
775         if (unlikely(vers == NULL))
776                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
777
778         ret =
779             _gnutls_recv_handshake(session, GNUTLS_HANDSHAKE_FINISHED,
780                                    0, &buf);
781         if (ret < 0) {
782                 ERR("recv finished int", ret);
783                 gnutls_assert();
784                 return ret;
785         }
786
787         vrfy = buf.data;
788         vrfy_size = buf.length;
789
790         if (vers->id == GNUTLS_SSL3)
791                 data_size = 36;
792         else
793                 data_size = 12;
794
795         if (vrfy_size != data_size) {
796                 gnutls_assert();
797                 ret = GNUTLS_E_ERROR_IN_FINISHED_PACKET;
798                 goto cleanup;
799         }
800
801         if (vers->id == GNUTLS_SSL3) {
802                 ret =
803                     _gnutls_ssl3_finished(session,
804                                           (session->security_parameters.
805                                            entity + 1) % 2, data, 0);
806         } else {                /* TLS 1.0 */
807                 ret =
808                     _gnutls_finished(session,
809                                      (session->security_parameters.entity +
810                                       1) % 2, data, 0);
811         }
812
813         if (ret < 0) {
814                 gnutls_assert();
815                 goto cleanup;
816         }
817
818         if (memcmp(vrfy, data, data_size) != 0) {
819                 gnutls_assert();
820                 ret = GNUTLS_E_ERROR_IN_FINISHED_PACKET;
821                 goto cleanup;
822         }
823
824         ret = _gnutls_ext_sr_finished(session, data, data_size, 1);
825         if (ret < 0) {
826                 gnutls_assert();
827                 goto cleanup;
828         }
829
830         if ((session->internals.resumed != RESUME_FALSE
831              && session->security_parameters.entity == GNUTLS_CLIENT)
832             || (session->internals.resumed == RESUME_FALSE
833                 && session->security_parameters.entity == GNUTLS_SERVER)) {
834                 /* if we are a client resuming - or we are a server not resuming */
835                 _gnutls_handshake_log
836                     ("HSK[%p]: recording tls-unique CB (recv)\n", session);
837                 memcpy(session->internals.cb_tls_unique, data, data_size);
838                 session->internals.cb_tls_unique_len = data_size;
839         }
840
841
842         session->internals.initial_negotiation_completed = 1;
843
844       cleanup:
845         _gnutls_buffer_clear(&buf);
846
847         return ret;
848 }
849
850 /* returns PK_RSA if the given cipher suite list only supports,
851  * RSA algorithms, PK_DSA if DSS, and PK_ANY for both or PK_NONE for none.
852  */
853 static int
854 server_find_pk_algos_in_ciphersuites(const uint8_t *
855                                      data, unsigned int datalen,
856                                      gnutls_pk_algorithm_t * algos,
857                                      size_t * algos_size)
858 {
859         unsigned int j, x;
860         gnutls_kx_algorithm_t kx;
861         gnutls_pk_algorithm_t pk;
862         unsigned found;
863         unsigned int max = *algos_size;
864
865         if (datalen % 2 != 0) {
866                 gnutls_assert();
867                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
868         }
869
870         *algos_size = 0;
871         for (j = 0; j < datalen; j += 2) {
872                 kx = _gnutls_cipher_suite_get_kx_algo(&data[j]);
873                 if (_gnutls_map_kx_get_cred(kx, 1) ==
874                     GNUTLS_CRD_CERTIFICATE) {
875                         pk = _gnutls_map_pk_get_pk(kx);
876                         found = 0;
877                         for (x = 0; x < *algos_size; x++) {
878                                 if (algos[x] == pk) {
879                                         found = 1;
880                                         break;
881                                 }
882                         }
883
884                         if (found == 0) {
885                                 algos[(*algos_size)++] =
886                                     _gnutls_map_pk_get_pk(kx);
887                                 if ((*algos_size) >= max)
888                                         return 0;
889                         }
890                 }
891         }
892
893         return 0;
894 }
895
896 /* This selects the best supported ciphersuite from the given ones. Then
897  * it adds the suite to the session and performs some checks.
898  */
899 int
900 _gnutls_server_select_suite(gnutls_session_t session, uint8_t * data,
901                             unsigned int datalen)
902 {
903         int ret;
904         unsigned int i, j, cipher_suites_size;
905         size_t pk_algos_size;
906         uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];
907         int retval;
908         gnutls_pk_algorithm_t pk_algos[MAX_ALGOS];      /* will hold the pk algorithms
909                                                          * supported by the peer.
910                                                          */
911
912         /* First, check for safe renegotiation SCSV.
913          */
914         if (session->internals.priorities.sr != SR_DISABLED) {
915                 unsigned int offset;
916
917                 for (offset = 0; offset < datalen; offset += 2) {
918                         /* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */
919                         if (data[offset] ==
920                             GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR
921                             && data[offset + 1] ==
922                             GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR) {
923                                 _gnutls_handshake_log
924                                     ("HSK[%p]: Received safe renegotiation CS\n",
925                                      session);
926                                 retval = _gnutls_ext_sr_recv_cs(session);
927                                 if (retval < 0) {
928                                         gnutls_assert();
929                                         return retval;
930                                 }
931                                 break;
932                         }
933                 }
934         }
935
936         pk_algos_size = MAX_ALGOS;
937         ret =
938             server_find_pk_algos_in_ciphersuites(data, datalen, pk_algos,
939                                                  &pk_algos_size);
940         if (ret < 0)
941                 return gnutls_assert_val(ret);
942
943         ret =
944             _gnutls_supported_ciphersuites(session, cipher_suites,
945                                            sizeof(cipher_suites));
946         if (ret < 0)
947                 return gnutls_assert_val(ret);
948
949         cipher_suites_size = ret;
950
951         /* Here we remove any ciphersuite that does not conform
952          * the certificate requested, or to the
953          * authentication requested (e.g. SRP).
954          */
955         ret =
956             _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,
957                                                  cipher_suites_size,
958                                                  pk_algos, pk_algos_size);
959         if (ret <= 0) {
960                 gnutls_assert();
961                 if (ret < 0)
962                         return ret;
963                 else
964                         return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
965         }
966
967         cipher_suites_size = ret;
968
969         /* Data length should be zero mod 2 since
970          * every ciphersuite is 2 bytes. (this check is needed
971          * see below).
972          */
973         if (datalen % 2 != 0) {
974                 gnutls_assert();
975                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
976         }
977
978         memset(session->security_parameters.cipher_suite, 0, 2);
979
980         retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;
981
982         _gnutls_handshake_log
983             ("HSK[%p]: Requested cipher suites[size: %d]: \n", session,
984              (int) datalen);
985
986         if (session->internals.priorities.server_precedence == 0) {
987                 for (j = 0; j < datalen; j += 2) {
988                         _gnutls_handshake_log("\t0x%.2x, 0x%.2x %s\n",
989                                               data[j], data[j + 1],
990                                               _gnutls_cipher_suite_get_name
991                                               (&data[j]));
992                         for (i = 0; i < cipher_suites_size; i += 2) {
993                                 if (memcmp(&cipher_suites[i], &data[j], 2)
994                                     == 0) {
995                                         _gnutls_handshake_log
996                                             ("HSK[%p]: Selected cipher suite: %s\n",
997                                              session,
998                                              _gnutls_cipher_suite_get_name
999                                              (&data[j]));
1000                                         memcpy(session->
1001                                                security_parameters.
1002                                                cipher_suite,
1003                                                &cipher_suites[i], 2);
1004                                         _gnutls_epoch_set_cipher_suite
1005                                             (session, EPOCH_NEXT,
1006                                              session->security_parameters.
1007                                              cipher_suite);
1008
1009
1010                                         retval = 0;
1011                                         goto finish;
1012                                 }
1013                         }
1014                 }
1015         } else {                /* server selects */
1016
1017                 for (i = 0; i < cipher_suites_size; i += 2) {
1018                         for (j = 0; j < datalen; j += 2) {
1019                                 if (memcmp(&cipher_suites[i], &data[j], 2)
1020                                     == 0) {
1021                                         _gnutls_handshake_log
1022                                             ("HSK[%p]: Selected cipher suite: %s\n",
1023                                              session,
1024                                              _gnutls_cipher_suite_get_name
1025                                              (&data[j]));
1026                                         memcpy(session->
1027                                                security_parameters.
1028                                                cipher_suite,
1029                                                &cipher_suites[i], 2);
1030                                         _gnutls_epoch_set_cipher_suite
1031                                             (session, EPOCH_NEXT,
1032                                              session->security_parameters.
1033                                              cipher_suite);
1034
1035
1036                                         retval = 0;
1037                                         goto finish;
1038                                 }
1039                         }
1040                 }
1041         }
1042       finish:
1043
1044         if (retval != 0) {
1045                 gnutls_assert();
1046                 return retval;
1047         }
1048
1049         /* check if the credentials (username, public key etc.) are ok
1050          */
1051         if (_gnutls_get_kx_cred
1052             (session,
1053              _gnutls_cipher_suite_get_kx_algo(session->security_parameters.
1054                                               cipher_suite)) == NULL) {
1055                 gnutls_assert();
1056                 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1057         }
1058
1059
1060         /* set the mod_auth_st to the appropriate struct
1061          * according to the KX algorithm. This is needed since all the
1062          * handshake functions are read from there;
1063          */
1064         session->internals.auth_struct =
1065             _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo
1066                                    (session->security_parameters.
1067                                     cipher_suite));
1068         if (session->internals.auth_struct == NULL) {
1069
1070                 _gnutls_handshake_log
1071                     ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
1072                      session);
1073                 gnutls_assert();
1074                 return GNUTLS_E_INTERNAL_ERROR;
1075         }
1076
1077         return 0;
1078
1079 }
1080
1081
1082 /* This selects the best supported compression method from the ones provided 
1083  */
1084 static int
1085 server_select_comp_method(gnutls_session_t session,
1086                           uint8_t * data, int datalen)
1087 {
1088         int x, i, j;
1089         uint8_t comps[MAX_ALGOS];
1090
1091         x = _gnutls_supported_compression_methods(session, comps,
1092                                                   MAX_ALGOS);
1093         if (x < 0) {
1094                 gnutls_assert();
1095                 return x;
1096         }
1097
1098         if (session->internals.priorities.server_precedence == 0) {
1099                 for (j = 0; j < datalen; j++) {
1100                         for (i = 0; i < x; i++) {
1101                                 if (comps[i] == data[j]) {
1102                                         gnutls_compression_method_t method
1103                                             =
1104                                             _gnutls_compression_get_id
1105                                             (comps[i]);
1106
1107                                         _gnutls_epoch_set_compression
1108                                             (session, EPOCH_NEXT, method);
1109                                         session->security_parameters.
1110                                             compression_method = method;
1111
1112                                         _gnutls_handshake_log
1113                                             ("HSK[%p]: Selected Compression Method: %s\n",
1114                                              session,
1115                                              gnutls_compression_get_name
1116                                              (method));
1117                                         return 0;
1118                                 }
1119                         }
1120                 }
1121         } else {
1122                 for (i = 0; i < x; i++) {
1123                         for (j = 0; j < datalen; j++) {
1124                                 if (comps[i] == data[j]) {
1125                                         gnutls_compression_method_t method
1126                                             =
1127                                             _gnutls_compression_get_id
1128                                             (comps[i]);
1129
1130                                         _gnutls_epoch_set_compression
1131                                             (session, EPOCH_NEXT, method);
1132                                         session->security_parameters.
1133                                             compression_method = method;
1134
1135                                         _gnutls_handshake_log
1136                                             ("HSK[%p]: Selected Compression Method: %s\n",
1137                                              session,
1138                                              gnutls_compression_get_name
1139                                              (method));
1140                                         return 0;
1141                                 }
1142                         }
1143                 }
1144         }
1145
1146         /* we were not able to find a compatible compression
1147          * algorithm
1148          */
1149         gnutls_assert();
1150         return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1151
1152 }
1153
1154 /* This function sends an empty handshake packet. (like hello request).
1155  * If the previous _gnutls_send_empty_handshake() returned
1156  * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED, then it must be called again 
1157  * (until it returns ok), with NULL parameters.
1158  */
1159 static int
1160 _gnutls_send_empty_handshake(gnutls_session_t session,
1161                              gnutls_handshake_description_t type,
1162                              int again)
1163 {
1164         mbuffer_st *bufel;
1165
1166         if (again == 0) {
1167                 bufel = _gnutls_handshake_alloc(session, 0);
1168                 if (bufel == NULL) {
1169                         gnutls_assert();
1170                         return GNUTLS_E_MEMORY_ERROR;
1171                 }
1172         } else
1173                 bufel = NULL;
1174
1175         return _gnutls_send_handshake(session, bufel, type);
1176 }
1177
1178 inline
1179     static int call_hook_func(gnutls_session_t session,
1180                               gnutls_handshake_description_t type,
1181                               int post, unsigned incoming,
1182                               const uint8_t *data, unsigned data_size)
1183 {
1184         gnutls_datum_t msg = {(void*)data, data_size};
1185
1186         if (session->internals.h_hook != NULL) {
1187                 if ((session->internals.h_type == type
1188                      || session->internals.h_type == GNUTLS_HANDSHAKE_ANY)
1189                     && (session->internals.h_post == post
1190                         || session->internals.h_post == GNUTLS_HOOK_BOTH))
1191                         return session->internals.h_hook(session, type,
1192                                                          post, incoming, &msg);
1193         }
1194         return 0;
1195 }
1196
1197 /* This function sends a handshake message of type 'type' containing the
1198  * data specified here. If the previous _gnutls_send_handshake() returned
1199  * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED, then it must be called again 
1200  * (until it returns ok), with NULL parameters.
1201  */
1202 int
1203 _gnutls_send_handshake(gnutls_session_t session, mbuffer_st * bufel,
1204                        gnutls_handshake_description_t type)
1205 {
1206         int ret;
1207         uint8_t *data;
1208         uint32_t datasize, i_datasize;
1209         int pos = 0;
1210
1211         if (bufel == NULL) {
1212                 /* we are resuming a previously interrupted
1213                  * send.
1214                  */
1215                 ret = _gnutls_handshake_io_write_flush(session);
1216                 return ret;
1217
1218         }
1219
1220         /* first run */
1221         data = _mbuffer_get_uhead_ptr(bufel);
1222         i_datasize = _mbuffer_get_udata_size(bufel);
1223         datasize = i_datasize + _mbuffer_get_uhead_size(bufel);
1224
1225         data[pos++] = (uint8_t) type;
1226         _gnutls_write_uint24(_mbuffer_get_udata_size(bufel), &data[pos]);
1227         pos += 3;
1228
1229         /* Add DTLS handshake fragment headers.  The message will be
1230          * fragmented later by the fragmentation sub-layer. All fields must
1231          * be set properly for HMAC. The HMAC requires we pretend that the
1232          * message was sent in a single fragment. */
1233         if (IS_DTLS(session)) {
1234                 _gnutls_write_uint16(session->internals.dtls.
1235                                      hsk_write_seq++, &data[pos]);
1236                 pos += 2;
1237
1238                 /* Fragment offset */
1239                 _gnutls_write_uint24(0, &data[pos]);
1240                 pos += 3;
1241
1242                 /* Fragment length */
1243                 _gnutls_write_uint24(i_datasize, &data[pos]);
1244                 /* pos += 3; */
1245         }
1246
1247         _gnutls_handshake_log("HSK[%p]: %s was queued [%ld bytes]\n",
1248                               session, _gnutls_handshake2str(type),
1249                               (long) datasize);
1250
1251         /* Here we keep the handshake messages in order to hash them...
1252          */
1253         if (type != GNUTLS_HANDSHAKE_HELLO_REQUEST)
1254                 if ((ret =
1255                      handshake_hash_add_sent(session, type, data,
1256                                                      datasize)) < 0) {
1257                         gnutls_assert();
1258                         _mbuffer_xfree(&bufel);
1259                         return ret;
1260                 }
1261
1262         ret = call_hook_func(session, type, GNUTLS_HOOK_PRE, 0,
1263                              _mbuffer_get_udata_ptr(bufel), _mbuffer_get_udata_size(bufel));
1264         if (ret < 0) {
1265                 gnutls_assert();
1266                 _mbuffer_xfree(&bufel);
1267                 return ret;
1268         }
1269
1270         session->internals.last_handshake_out = type;
1271
1272         ret = _gnutls_handshake_io_cache_int(session, type, bufel);
1273         if (ret < 0) {
1274                 _mbuffer_xfree(&bufel);
1275                 gnutls_assert();
1276                 return ret;
1277         }
1278
1279         ret = call_hook_func(session, type, GNUTLS_HOOK_POST, 0, 
1280                               _mbuffer_get_udata_ptr(bufel), _mbuffer_get_udata_size(bufel));
1281         if (ret < 0) {
1282                 gnutls_assert();
1283                 return ret;
1284         }
1285
1286         switch (type) {
1287         case GNUTLS_HANDSHAKE_CERTIFICATE_PKT:  /* this one is followed by ServerHelloDone
1288                                                  * or ClientKeyExchange always.
1289                                                  */
1290         case GNUTLS_HANDSHAKE_CERTIFICATE_STATUS:
1291         case GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE:      /* as above */
1292         case GNUTLS_HANDSHAKE_SERVER_HELLO:     /* as above */
1293         case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST:      /* as above */
1294         case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET:       /* followed by ChangeCipherSpec */
1295
1296                 /* now for client Certificate, ClientKeyExchange and
1297                  * CertificateVerify are always followed by ChangeCipherSpec
1298                  */
1299         case GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY:
1300         case GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE:
1301                 ret = 0;
1302                 break;
1303         default:
1304                 /* send cached messages */
1305                 ret = _gnutls_handshake_io_write_flush(session);
1306                 break;
1307         }
1308
1309         return ret;
1310 }
1311
1312 #define CHECK_SIZE(ll) \
1313   if ((session->internals.max_handshake_data_buffer_size > 0) && \
1314       (((ll) + session->internals.handshake_hash_buffer.length) > \
1315        session->internals.max_handshake_data_buffer_size)) \
1316     return gnutls_assert_val(GNUTLS_E_HANDSHAKE_TOO_LARGE)
1317
1318 /* This function add the handshake headers and the
1319  * handshake data to the handshake hash buffers. Needed
1320  * for the finished messages calculations.
1321  */
1322 static int
1323 handshake_hash_add_recvd(gnutls_session_t session,
1324                                  gnutls_handshake_description_t recv_type,
1325                                  uint8_t * header, uint16_t header_size,
1326                                  uint8_t * dataptr, uint32_t datalen)
1327 {
1328         int ret;
1329         const version_entry_st *vers = get_version(session);
1330
1331         if (unlikely(vers == NULL))
1332                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1333
1334         if ((vers->id != GNUTLS_DTLS0_9 &&
1335              recv_type == GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST) ||
1336             recv_type == GNUTLS_HANDSHAKE_HELLO_REQUEST)
1337                 return 0;
1338
1339         CHECK_SIZE(header_size + datalen);
1340
1341         session->internals.handshake_hash_buffer_prev_len =
1342             session->internals.handshake_hash_buffer.length;
1343
1344         if (vers->id != GNUTLS_DTLS0_9) {
1345                 ret =
1346                     _gnutls_buffer_append_data(&session->internals.
1347                                                handshake_hash_buffer,
1348                                                header, header_size);
1349                 if (ret < 0)
1350                         return gnutls_assert_val(ret);
1351         }
1352         if (datalen > 0) {
1353                 ret =
1354                     _gnutls_buffer_append_data(&session->internals.
1355                                                handshake_hash_buffer,
1356                                                dataptr, datalen);
1357                 if (ret < 0)
1358                         return gnutls_assert_val(ret);
1359         }
1360
1361         /* save the size until client KX. That is because the TLS
1362          * session hash is calculated up to this message.
1363          */
1364         if (recv_type == GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE)
1365                 session->internals.handshake_hash_buffer_client_kx_len =
1366                         session->internals.handshake_hash_buffer.length;
1367
1368         return 0;
1369 }
1370
1371 /* This function will store the handshake message we sent.
1372  */
1373 static int
1374 handshake_hash_add_sent(gnutls_session_t session,
1375                                 gnutls_handshake_description_t type,
1376                                 uint8_t * dataptr, uint32_t datalen)
1377 {
1378         int ret;
1379         const version_entry_st *vers = get_version(session);
1380
1381         if (unlikely(vers == NULL))
1382                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1383
1384         /* We don't check for GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST because it
1385          * is not sent via that channel.
1386          */
1387         if (type != GNUTLS_HANDSHAKE_HELLO_REQUEST) {
1388                 CHECK_SIZE(datalen);
1389
1390                 if (vers->id == GNUTLS_DTLS0_9) {
1391                         /* Old DTLS doesn't include the header in the MAC */
1392                         if (datalen < 12) {
1393                                 gnutls_assert();
1394                                 return GNUTLS_E_INTERNAL_ERROR;
1395                         }
1396                         dataptr += 12;
1397                         datalen -= 12;
1398
1399                         if (datalen == 0)
1400                                 return 0;
1401                 }
1402
1403                 ret =
1404                     _gnutls_buffer_append_data(&session->internals.
1405                                                handshake_hash_buffer,
1406                                                dataptr, datalen);
1407                 if (ret < 0)
1408                         return gnutls_assert_val(ret);
1409
1410                 if (type == GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE)
1411                         session->internals.handshake_hash_buffer_client_kx_len =
1412                                 session->internals.handshake_hash_buffer.length;
1413
1414                 return 0;
1415         }
1416
1417         return 0;
1418 }
1419
1420 /* This function will receive handshake messages of the given types,
1421  * and will pass the message to the right place in order to be processed.
1422  * E.g. for the SERVER_HELLO message (if it is expected), it will be
1423  * passed to _gnutls_recv_hello().
1424  */
1425 int
1426 _gnutls_recv_handshake(gnutls_session_t session,
1427                        gnutls_handshake_description_t type,
1428                        unsigned int optional, gnutls_buffer_st * buf)
1429 {
1430         int ret, ret2;
1431         handshake_buffer_st hsk;
1432
1433         ret = _gnutls_handshake_io_recv_int(session, type, &hsk, optional);
1434         if (ret < 0) {
1435                 if (optional != 0
1436                     && ret == GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET) {
1437                         if (buf)
1438                                 _gnutls_buffer_init(buf);
1439                         return 0;
1440                 }
1441
1442                 return gnutls_assert_val_fatal(ret);
1443         }
1444
1445         session->internals.last_handshake_in = hsk.htype;
1446
1447         ret = call_hook_func(session, hsk.htype, GNUTLS_HOOK_PRE, 1, hsk.data.data, hsk.data.length);
1448         if (ret < 0) {
1449                 gnutls_assert();
1450                 goto cleanup;
1451         }
1452
1453         ret = handshake_hash_add_recvd(session, hsk.htype,
1454                                        hsk.header, hsk.header_size,
1455                                        hsk.data.data,
1456                                        hsk.data.length);
1457         if (ret < 0) {
1458                 gnutls_assert();
1459                 goto cleanup;
1460         }
1461
1462         switch (hsk.htype) {
1463         case GNUTLS_HANDSHAKE_CLIENT_HELLO_V2:
1464         case GNUTLS_HANDSHAKE_CLIENT_HELLO:
1465         case GNUTLS_HANDSHAKE_SERVER_HELLO:
1466                 if (hsk.htype == GNUTLS_HANDSHAKE_CLIENT_HELLO_V2)
1467                         ret =
1468                             _gnutls_read_client_hello_v2(session,
1469                                                          hsk.data.data,
1470                                                          hsk.data.length);
1471                 else
1472                         ret =
1473                             recv_hello(session, hsk.data.data,
1474                                         hsk.data.length);
1475
1476                 if (ret < 0) {
1477                         gnutls_assert();
1478                         goto cleanup;
1479                 }
1480
1481                 break;
1482         case GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST:
1483                 ret =
1484                     recv_hello_verify_request(session,
1485                                               hsk.data.data,
1486                                               hsk.data.length);
1487                 if (ret < 0) {
1488                         gnutls_assert();
1489                         goto cleanup;
1490                 } else {
1491                         /* Signal our caller we have received a verification cookie
1492                            and ClientHello needs to be sent again. */
1493                         ret = 1;
1494                 }
1495
1496                 break;
1497         case GNUTLS_HANDSHAKE_SERVER_HELLO_DONE:
1498                 if (hsk.data.length == 0)
1499                         ret = 0;
1500                 else {
1501                         gnutls_assert();
1502                         ret = GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1503                         goto cleanup;
1504                 }
1505                 break;
1506         case GNUTLS_HANDSHAKE_CERTIFICATE_PKT:
1507         case GNUTLS_HANDSHAKE_CERTIFICATE_STATUS:
1508         case GNUTLS_HANDSHAKE_FINISHED:
1509         case GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE:
1510         case GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE:
1511         case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST:
1512         case GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY:
1513         case GNUTLS_HANDSHAKE_SUPPLEMENTAL:
1514         case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET:
1515                 ret = hsk.data.length;
1516                 break;
1517         default:
1518                 gnutls_assert();
1519                 /* we shouldn't actually arrive here in any case .
1520                  * unexpected messages should be catched after _gnutls_handshake_io_recv_int()
1521                  */
1522                 ret = GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
1523                 goto cleanup;
1524         }
1525
1526         ret2 = call_hook_func(session, hsk.htype, GNUTLS_HOOK_POST, 1, hsk.data.data, hsk.data.length);
1527         if (ret2 < 0) {
1528                 ret = ret2;
1529                 gnutls_assert();
1530                 goto cleanup;
1531         }
1532
1533         if (buf) {
1534                 *buf = hsk.data;
1535                 return ret;
1536         }
1537
1538       cleanup:
1539         _gnutls_handshake_buffer_clear(&hsk);
1540         return ret;
1541 }
1542
1543 /* This function checks if the given cipher suite is supported, and sets it
1544  * to the session;
1545  */
1546 static int
1547 set_client_ciphersuite(gnutls_session_t session, uint8_t suite[2])
1548 {
1549         uint8_t z;
1550         uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];
1551         int cipher_suite_size;
1552         int i;
1553
1554         z = 1;
1555         cipher_suite_size =
1556             _gnutls_supported_ciphersuites(session, cipher_suites,
1557                                            sizeof(cipher_suites));
1558         if (cipher_suite_size < 0) {
1559                 gnutls_assert();
1560                 return cipher_suite_size;
1561         }
1562
1563         for (i = 0; i < cipher_suite_size; i += 2) {
1564                 if (memcmp(&cipher_suites[i], suite, 2) == 0) {
1565                         z = 0;
1566                         break;
1567                 }
1568         }
1569
1570         if (z != 0) {
1571                 gnutls_assert();
1572                 _gnutls_handshake_log
1573                     ("HSK[%p]: unsupported cipher suite %.2X.%.2X\n",
1574                      session, (unsigned int) suite[0],
1575                      (unsigned int) suite[1]);
1576                 return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
1577         }
1578
1579         memcpy(session->security_parameters.cipher_suite, suite, 2);
1580         _gnutls_epoch_set_cipher_suite(session, EPOCH_NEXT,
1581                                        session->security_parameters.
1582                                        cipher_suite);
1583
1584         _gnutls_handshake_log("HSK[%p]: Selected cipher suite: %s\n",
1585                               session,
1586                               _gnutls_cipher_suite_get_name
1587                               (session->security_parameters.cipher_suite));
1588
1589
1590         /* check if the credentials (username, public key etc.) are ok.
1591          * Actually checks if they exist.
1592          */
1593         if (!session->internals.premaster_set &&
1594             _gnutls_get_kx_cred
1595             (session,
1596              _gnutls_cipher_suite_get_kx_algo
1597              (session->security_parameters.cipher_suite)) == NULL) {
1598                 gnutls_assert();
1599                 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1600         }
1601
1602
1603         /* set the mod_auth_st to the appropriate struct
1604          * according to the KX algorithm. This is needed since all the
1605          * handshake functions are read from there;
1606          */
1607         session->internals.auth_struct =
1608             _gnutls_kx_auth_struct(_gnutls_cipher_suite_get_kx_algo
1609                                    (session->security_parameters.
1610                                     cipher_suite));
1611
1612         if (session->internals.auth_struct == NULL) {
1613
1614                 _gnutls_handshake_log
1615                     ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
1616                      session);
1617                 gnutls_assert();
1618                 return GNUTLS_E_INTERNAL_ERROR;
1619         }
1620
1621
1622         return 0;
1623 }
1624
1625 /* This function sets the given comp method to the session.
1626  */
1627 static int
1628 set_client_comp_method(gnutls_session_t session,
1629                                uint8_t comp_method)
1630 {
1631         int comp_methods_num;
1632         uint8_t compression_methods[MAX_ALGOS];
1633         int id = _gnutls_compression_get_id(comp_method);
1634         int i;
1635
1636         _gnutls_handshake_log
1637             ("HSK[%p]: Selected compression method: %s (%d)\n", session,
1638              gnutls_compression_get_name(id), (int) comp_method);
1639
1640         comp_methods_num = _gnutls_supported_compression_methods(session,
1641                                                                  compression_methods,
1642                                                                  MAX_ALGOS);
1643         if (comp_methods_num < 0) {
1644                 gnutls_assert();
1645                 return comp_methods_num;
1646         }
1647
1648         for (i = 0; i < comp_methods_num; i++) {
1649                 if (compression_methods[i] == comp_method) {
1650                         comp_methods_num = 0;
1651                         break;
1652                 }
1653         }
1654
1655         if (comp_methods_num != 0) {
1656                 gnutls_assert();
1657                 return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1658         }
1659
1660         session->security_parameters.compression_method = id;
1661         _gnutls_epoch_set_compression(session, EPOCH_NEXT, id);
1662
1663         return 0;
1664 }
1665
1666 /* This function returns 0 if we are resuming a session or -1 otherwise.
1667  * This also sets the variables in the session. Used only while reading a server
1668  * hello.
1669  */
1670 static int
1671 client_check_if_resuming(gnutls_session_t session,
1672                                  uint8_t * session_id, int session_id_len)
1673 {
1674         char buf[2 * GNUTLS_MAX_SESSION_ID_SIZE + 1];
1675
1676         _gnutls_handshake_log("HSK[%p]: SessionID length: %d\n", session,
1677                               session_id_len);
1678         _gnutls_handshake_log("HSK[%p]: SessionID: %s\n", session,
1679                               _gnutls_bin2hex(session_id, session_id_len,
1680                                               buf, sizeof(buf), NULL));
1681
1682         if ((session->internals.resumption_requested != 0 ||
1683              session->internals.premaster_set != 0) &&
1684             session_id_len > 0 &&
1685             session->internals.resumed_security_parameters.
1686             session_id_size == session_id_len
1687             && memcmp(session_id,
1688                       session->internals.resumed_security_parameters.
1689                       session_id, session_id_len) == 0) {
1690                 /* resume session */
1691                 memcpy(session->internals.resumed_security_parameters.
1692                        server_random,
1693                        session->security_parameters.server_random,
1694                        GNUTLS_RANDOM_SIZE);
1695                 memcpy(session->internals.resumed_security_parameters.
1696                        client_random,
1697                        session->security_parameters.client_random,
1698                        GNUTLS_RANDOM_SIZE);
1699
1700                 memcpy(session->security_parameters.cipher_suite,
1701                         session->internals.resumed_security_parameters.cipher_suite, 2);
1702                 session->security_parameters.compression_method =
1703                         session->internals.resumed_security_parameters.compression_method;
1704
1705                 _gnutls_epoch_set_cipher_suite
1706                     (session, EPOCH_NEXT,
1707                      session->internals.resumed_security_parameters.
1708                      cipher_suite);
1709                 _gnutls_epoch_set_compression(session, EPOCH_NEXT,
1710                                               session->internals.
1711                                               resumed_security_parameters.
1712                                               compression_method);
1713
1714                 session->internals.resumed = RESUME_TRUE;       /* we are resuming */
1715
1716                 return 0;
1717         } else {
1718                 /* keep the new session id */
1719                 session->internals.resumed = RESUME_FALSE;      /* we are not resuming */
1720                 session->security_parameters.session_id_size =
1721                     session_id_len;
1722                 if (session_id_len > 0) {
1723                         memcpy(session->security_parameters.session_id, session_id,
1724                                session_id_len);
1725                 }
1726
1727                 return -1;
1728         }
1729 }
1730
1731
1732 /* This function reads and parses the server hello handshake message.
1733  * This function also restores resumed parameters if we are resuming a
1734  * session.
1735  */
1736 static int
1737 read_server_hello(gnutls_session_t session,
1738                           uint8_t * data, int datalen)
1739 {
1740         uint8_t session_id_len = 0;
1741         int pos = 0;
1742         int ret = 0;
1743         gnutls_protocol_t version;
1744         int len = datalen;
1745
1746         if (datalen < 38) {
1747                 gnutls_assert();
1748                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1749         }
1750
1751         _gnutls_handshake_log("HSK[%p]: Server's version: %d.%d\n",
1752                               session, data[pos], data[pos + 1]);
1753
1754         DECR_LEN(len, 2);
1755         version = _gnutls_version_get(data[pos], data[pos + 1]);
1756         if (_gnutls_version_is_supported(session, version) == 0) {
1757                 gnutls_assert();
1758                 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
1759         }
1760
1761         if (_gnutls_set_current_version(session, version) < 0)
1762                 return gnutls_assert_val(GNUTLS_E_UNSUPPORTED_VERSION_PACKET);
1763
1764         pos += 2;
1765
1766         DECR_LEN(len, GNUTLS_RANDOM_SIZE);
1767         ret = _gnutls_set_server_random(session, &data[pos]);
1768         if (ret < 0)
1769                 return gnutls_assert_val(ret);
1770
1771         pos += GNUTLS_RANDOM_SIZE;
1772
1773
1774         /* Read session ID
1775          */
1776         DECR_LEN(len, 1);
1777         session_id_len = data[pos++];
1778
1779         if (len < session_id_len || session_id_len > GNUTLS_MAX_SESSION_ID_SIZE) {
1780                 gnutls_assert();
1781                 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
1782         }
1783         DECR_LEN(len, session_id_len);
1784
1785         /* check if we are resuming and set the appropriate
1786          * values;
1787          */
1788         if (client_check_if_resuming
1789             (session, &data[pos], session_id_len) == 0) {
1790                 pos += session_id_len + 2 + 1;
1791                 DECR_LEN(len, 2 + 1);
1792
1793                 ret =
1794                     _gnutls_parse_extensions(session, GNUTLS_EXT_MANDATORY,
1795                                              &data[pos], len);
1796                 if (ret < 0) {
1797                         gnutls_assert();
1798                         return ret;
1799                 }
1800                 return 0;
1801         }
1802
1803         pos += session_id_len;
1804
1805         /* Check if the given cipher suite is supported and copy
1806          * it to the session.
1807          */
1808
1809         DECR_LEN(len, 2);
1810         ret = set_client_ciphersuite(session, &data[pos]);
1811         if (ret < 0) {
1812                 gnutls_assert();
1813                 return ret;
1814         }
1815         pos += 2;
1816
1817         /* move to compression 
1818          */
1819         DECR_LEN(len, 1);
1820
1821         ret = set_client_comp_method(session, data[pos++]);
1822         if (ret < 0) {
1823                 gnutls_assert();
1824                 return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1825         }
1826
1827         /* Parse extensions.
1828          */
1829         ret =
1830             _gnutls_parse_extensions(session, GNUTLS_EXT_ANY, &data[pos],
1831                                      len);
1832         if (ret < 0) {
1833                 gnutls_assert();
1834                 return ret;
1835         }
1836
1837         return ret;
1838 }
1839
1840
1841 /* This function copies the appropriate ciphersuites to a locally allocated buffer
1842  * Needed in client hello messages. Returns the new data length. If add_scsv is
1843  * true, add the special safe renegotiation CS.
1844  */
1845 static int
1846 copy_ciphersuites(gnutls_session_t session,
1847                   gnutls_buffer_st * cdata, int add_scsv)
1848 {
1849         int ret;
1850         uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE + 2]; /* allow space for SCSV */
1851         int cipher_suites_size;
1852         size_t init_length = cdata->length;
1853
1854         ret =
1855             _gnutls_supported_ciphersuites(session, cipher_suites,
1856                                            sizeof(cipher_suites) - 2);
1857         if (ret < 0)
1858                 return gnutls_assert_val(ret);
1859
1860         /* Here we remove any ciphersuite that does not conform
1861          * the certificate requested, or to the
1862          * authentication requested (eg SRP).
1863          */
1864         ret =
1865             _gnutls_remove_unwanted_ciphersuites(session, cipher_suites,
1866                                                  ret, NULL, 0);
1867         if (ret < 0)
1868                 return gnutls_assert_val(ret);
1869
1870         /* If no cipher suites were enabled.
1871          */
1872         if (ret == 0)
1873                 return
1874                     gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1875
1876         cipher_suites_size = ret;
1877         if (add_scsv) {
1878                 cipher_suites[cipher_suites_size] = 0x00;
1879                 cipher_suites[cipher_suites_size + 1] = 0xff;
1880                 cipher_suites_size += 2;
1881
1882                 ret = _gnutls_ext_sr_send_cs(session);
1883                 if (ret < 0)
1884                         return gnutls_assert_val(ret);
1885         }
1886
1887         ret =
1888             _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites,
1889                                               cipher_suites_size);
1890         if (ret < 0)
1891                 return gnutls_assert_val(ret);
1892
1893         ret = cdata->length - init_length;
1894
1895         return ret;
1896 }
1897
1898
1899 /* This function copies the appropriate compression methods, to a locally allocated buffer 
1900  * Needed in hello messages. Returns the new data length.
1901  */
1902 static int
1903 copy_comp_methods(gnutls_session_t session,
1904                           gnutls_buffer_st * cdata)
1905 {
1906         int ret;
1907         uint8_t compression_methods[MAX_ALGOS], comp_num;
1908         size_t init_length = cdata->length;
1909
1910         ret =
1911             _gnutls_supported_compression_methods(session,
1912                                                   compression_methods,
1913                                                   MAX_ALGOS);
1914         if (ret < 0)
1915                 return gnutls_assert_val(ret);
1916
1917         comp_num = ret;
1918
1919         /* put the number of compression methods */
1920         ret = _gnutls_buffer_append_prefix(cdata, 8, comp_num);
1921         if (ret < 0)
1922                 return gnutls_assert_val(ret);
1923
1924         ret =
1925             _gnutls_buffer_append_data(cdata, compression_methods,
1926                                        comp_num);
1927         if (ret < 0)
1928                 return gnutls_assert_val(ret);
1929
1930         ret = cdata->length - init_length;
1931
1932         return ret;
1933 }
1934
1935 /* This function sends the client hello handshake message.
1936  */
1937 static int send_client_hello(gnutls_session_t session, int again)
1938 {
1939         mbuffer_st *bufel = NULL;
1940         int type;
1941         int ret = 0;
1942         const version_entry_st *hver;
1943         uint8_t tver[2];
1944         gnutls_buffer_st extdata;
1945         int rehandshake = 0;
1946         uint8_t session_id_len =
1947             session->internals.resumed_security_parameters.session_id_size;
1948
1949         _gnutls_buffer_init(&extdata);
1950
1951         /* note that rehandshake is different than resuming
1952          */
1953         if (session->security_parameters.session_id_size)
1954                 rehandshake = 1;
1955
1956         if (again == 0) {
1957                 /* if we are resuming a session then we set the
1958                  * version number to the previously established.
1959                  */
1960                 if (session->internals.resumption_requested == 0 &&
1961                     session->internals.premaster_set == 0) {
1962                         if (rehandshake)        /* already negotiated version thus version_max == negotiated version */
1963                                 hver = get_version(session);
1964                         else    /* new handshake. just get the max */
1965                                 hver =
1966                                     version_to_entry(_gnutls_version_max
1967                                                      (session));
1968                 } else {
1969                         /* we are resuming a session */
1970                         hver =
1971                             session->internals.resumed_security_parameters.
1972                             pversion;
1973                 }
1974
1975                 if (hver == NULL) {
1976                         gnutls_assert();
1977                         return GNUTLS_E_INTERNAL_ERROR;
1978                 }
1979
1980                 if (unlikely(session->internals.default_hello_version[0] != 0)) {
1981                         tver[0] = session->internals.default_hello_version[0];
1982                         tver[1] = session->internals.default_hello_version[1];
1983                 } else {
1984                         tver[0] = hver->major;
1985                         tver[1] = hver->minor;
1986                 }
1987                 ret = _gnutls_buffer_append_data(&extdata, tver, 2);
1988                 if (ret < 0) {
1989                         gnutls_assert();
1990                         goto cleanup;
1991                 }
1992
1993                 /* Set the version we advertized as maximum 
1994                  * (RSA uses it).
1995                  */
1996                 set_adv_version(session, hver->major, hver->minor);
1997                 if (_gnutls_set_current_version(session, hver->id) < 0)
1998                         return gnutls_assert_val(GNUTLS_E_UNSUPPORTED_VERSION_PACKET);
1999
2000                 if (session->internals.priorities.min_record_version != 0) {
2001                         /* Advertize the SSL 3.0 record packet version in
2002                          * record packets during the handshake.
2003                          * That is to avoid confusing implementations
2004                          * that do not support TLS 1.2 and don't know
2005                          * how 3,3 version of record packets look like.
2006                          */
2007                         const version_entry_st *v = _gnutls_version_lowest(session);
2008
2009                         if (v == NULL) {
2010                                 gnutls_assert();
2011                                 return GNUTLS_E_INTERNAL_ERROR;
2012                         } else {
2013                                 _gnutls_record_set_default_version(session,
2014                                                                    v->major, v->minor);
2015                         }
2016                 }
2017
2018                 /* In order to know when this session was initiated.
2019                  */
2020                 session->security_parameters.timestamp = gnutls_time(NULL);
2021
2022                 /* Generate random data 
2023                  */
2024                 if (!IS_DTLS(session)
2025                     || session->internals.dtls.hsk_hello_verify_requests ==
2026                     0) {
2027                         ret = _gnutls_set_client_random(session, NULL);
2028                         if (ret < 0)
2029                                 return gnutls_assert_val(ret);
2030
2031                 }
2032
2033                 ret = _gnutls_buffer_append_data(&extdata,
2034                                         session->security_parameters.client_random,
2035                                         GNUTLS_RANDOM_SIZE);
2036                 if (ret < 0) {
2037                         gnutls_assert();
2038                         goto cleanup;
2039                 }
2040
2041                 /* Copy the Session ID 
2042                  */
2043                 ret = _gnutls_buffer_append_data_prefix(&extdata, 8, 
2044                                                 session->internals.resumed_security_parameters.session_id,
2045                                                 session_id_len);
2046                 if (ret < 0) {
2047                         gnutls_assert();
2048                         goto cleanup;
2049                 }
2050
2051                 /* Copy the DTLS cookie
2052                  */
2053                 if (IS_DTLS(session)) {
2054                         ret = _gnutls_buffer_append_data_prefix(&extdata, 8, session->internals.dtls.cookie,
2055                                 session->internals.dtls.cookie_len);
2056                         if (ret < 0) {
2057                                 gnutls_assert();
2058                                 goto cleanup;
2059                         }
2060                 }
2061
2062                 /* Copy the ciphersuites.
2063                  *
2064                  * If using SSLv3 Send TLS_RENEGO_PROTECTION_REQUEST SCSV for MITM
2065                  * prevention on initial negotiation (but not renegotiation; that's
2066                  * handled with the RI extension below).
2067                  */
2068                 if (!session->internals.initial_negotiation_completed &&
2069                     session->security_parameters.entity == GNUTLS_CLIENT &&
2070                     (hver->id == GNUTLS_SSL3 &&
2071                      session->internals.priorities.no_extensions != 0)) {
2072                         ret =
2073                             copy_ciphersuites(session, &extdata,
2074                                               TRUE);
2075                         _gnutls_extension_list_add(session,
2076                                                    GNUTLS_EXTENSION_SAFE_RENEGOTIATION);
2077                 } else
2078                         ret =
2079                             copy_ciphersuites(session, &extdata,
2080                                               FALSE);
2081
2082                 if (ret < 0) {
2083                         gnutls_assert();
2084                         goto cleanup;
2085                 }
2086
2087                 /* Copy the compression methods.
2088                  */
2089                 ret = copy_comp_methods(session, &extdata);
2090                 if (ret < 0) {
2091                         gnutls_assert();
2092                         goto cleanup;
2093                 }
2094
2095                 /* Generate and copy TLS extensions.
2096                  */
2097                 if (session->internals.priorities.no_extensions == 0) {
2098                         if (_gnutls_version_has_extensions(hver)) {
2099                                 type = GNUTLS_EXT_ANY;
2100                         } else {
2101                                 type = GNUTLS_EXT_MANDATORY;
2102                         }
2103
2104                         ret =
2105                             _gnutls_gen_extensions(session, &extdata,
2106                                                    type);
2107                         if (ret < 0) {
2108                                 gnutls_assert();
2109                                 goto cleanup;
2110                         }
2111                 }
2112
2113                 bufel =
2114                     _gnutls_handshake_alloc(session, extdata.length);
2115                 if (bufel == NULL) {
2116                         gnutls_assert();
2117                         ret = GNUTLS_E_MEMORY_ERROR;
2118                         goto cleanup; 
2119                 }
2120                 _mbuffer_set_udata_size(bufel, 0);
2121
2122                 ret =
2123                     _mbuffer_append_data(bufel, extdata.data,
2124                                          extdata.length);
2125                 if (ret < 0) {
2126                         gnutls_assert();
2127                         goto cleanup;
2128                 }
2129         }
2130
2131         _gnutls_buffer_clear(&extdata);
2132
2133         return
2134             _gnutls_send_handshake(session, bufel,
2135                                    GNUTLS_HANDSHAKE_CLIENT_HELLO);
2136
2137       cleanup:
2138         _mbuffer_xfree(&bufel);
2139         _gnutls_buffer_clear(&extdata);
2140         return ret;
2141 }
2142
2143 static int send_server_hello(gnutls_session_t session, int again)
2144 {
2145         mbuffer_st *bufel = NULL;
2146         uint8_t *data = NULL;
2147         gnutls_buffer_st extdata;
2148         int pos = 0;
2149         int datalen, ret = 0;
2150         uint8_t comp;
2151         uint8_t session_id_len =
2152             session->security_parameters.session_id_size;
2153         char buf[2 * GNUTLS_MAX_SESSION_ID_SIZE + 1];
2154         const version_entry_st *vers;
2155
2156         _gnutls_buffer_init(&extdata);
2157
2158         if (again == 0) {
2159                 datalen = 2 + session_id_len + 1 + GNUTLS_RANDOM_SIZE + 3;
2160                 ret =
2161                     _gnutls_gen_extensions(session, &extdata,
2162                                            (session->internals.resumed ==
2163                                             RESUME_TRUE) ?
2164                                            GNUTLS_EXT_MANDATORY :
2165                                            GNUTLS_EXT_ANY);
2166                 if (ret < 0) {
2167                         gnutls_assert();
2168                         goto fail;
2169                 }
2170
2171                 bufel =
2172                     _gnutls_handshake_alloc(session,
2173                                             datalen + extdata.length);
2174                 if (bufel == NULL) {
2175                         gnutls_assert();
2176                         ret = GNUTLS_E_MEMORY_ERROR;
2177                         goto fail;
2178                 }
2179                 data = _mbuffer_get_udata_ptr(bufel);
2180
2181                 vers = get_version(session);
2182                 if (unlikely(vers == NULL))
2183                         return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
2184
2185                 data[pos++] = vers->major;
2186                 data[pos++] = vers->minor;
2187
2188                 memcpy(&data[pos],
2189                        session->security_parameters.server_random,
2190                        GNUTLS_RANDOM_SIZE);
2191                 pos += GNUTLS_RANDOM_SIZE;
2192
2193                 data[pos++] = session_id_len;
2194                 if (session_id_len > 0) {
2195                         memcpy(&data[pos],
2196                                session->security_parameters.session_id,
2197                                session_id_len);
2198                 }
2199                 pos += session_id_len;
2200
2201                 _gnutls_handshake_log("HSK[%p]: SessionID: %s\n", session,
2202                                       _gnutls_bin2hex(session->
2203                                                       security_parameters.session_id,
2204                                                       session_id_len, buf,
2205                                                       sizeof(buf), NULL));
2206
2207                 memcpy(&data[pos],
2208                        session->security_parameters.cipher_suite, 2);
2209                 pos += 2;
2210
2211                 comp =
2212                     _gnutls_compression_get_num(session->
2213                                                 security_parameters.
2214                                                 compression_method);
2215                 data[pos++] = comp;
2216
2217                 if (extdata.length > 0) {
2218                         memcpy(&data[pos], extdata.data, extdata.length);
2219                 }
2220         }
2221
2222         ret =
2223             _gnutls_send_handshake(session, bufel,
2224                                    GNUTLS_HANDSHAKE_SERVER_HELLO);
2225
2226       fail:
2227         _gnutls_buffer_clear(&extdata);
2228         return ret;
2229 }
2230
2231 static int send_hello(gnutls_session_t session, int again)
2232 {
2233         int ret;
2234
2235         if (session->security_parameters.entity == GNUTLS_CLIENT) {
2236                 ret = send_client_hello(session, again);
2237
2238         } else {                /* SERVER */
2239                 ret = send_server_hello(session, again);
2240         }
2241
2242         return ret;
2243 }
2244
2245 /* RECEIVE A HELLO MESSAGE. This should be called from gnutls_recv_handshake_int only if a
2246  * hello message is expected. It uses the security_parameters.cipher_suite
2247  * and internals.compression_method.
2248  */
2249 static int
2250 recv_hello(gnutls_session_t session, uint8_t * data, int datalen)
2251 {
2252         int ret;
2253
2254         if (session->security_parameters.entity == GNUTLS_CLIENT) {
2255                 ret = read_server_hello(session, data, datalen);
2256                 if (ret < 0) {
2257                         gnutls_assert();
2258                         return ret;
2259                 }
2260         } else {                /* Server side reading a client hello */
2261
2262                 ret = read_client_hello(session, data, datalen);
2263                 if (ret < 0) {
2264                         gnutls_assert();
2265                         return ret;
2266                 }
2267         }
2268
2269         return 0;
2270 }
2271
2272 static int
2273 recv_hello_verify_request(gnutls_session_t session,
2274                                   uint8_t * data, int datalen)
2275 {
2276         ssize_t len = datalen;
2277         size_t pos = 0;
2278         uint8_t cookie_len;
2279         unsigned int nb_verifs;
2280
2281         if (!IS_DTLS(session)
2282             || session->security_parameters.entity == GNUTLS_SERVER) {
2283                 gnutls_assert();
2284                 return GNUTLS_E_INTERNAL_ERROR;
2285         }
2286
2287         nb_verifs = ++session->internals.dtls.hsk_hello_verify_requests;
2288         if (nb_verifs >= MAX_HANDSHAKE_HELLO_VERIFY_REQUESTS) {
2289                 /* The server is either buggy, malicious or changing cookie
2290                    secrets _way_ too fast. */
2291                 gnutls_assert();
2292                 return GNUTLS_E_UNEXPECTED_PACKET;
2293         }
2294
2295         /* TODO: determine if we need to do anything with the server version field */
2296         DECR_LEN(len, 2);
2297         pos += 2;
2298
2299         DECR_LEN(len, 1);
2300         cookie_len = data[pos];
2301         pos++;
2302
2303         if (cookie_len > DTLS_MAX_COOKIE_SIZE) {
2304                 gnutls_assert();
2305                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
2306         }
2307
2308         DECR_LEN(len, cookie_len);
2309
2310         session->internals.dtls.cookie_len = cookie_len;
2311         memcpy(session->internals.dtls.cookie, &data[pos], cookie_len);
2312
2313         if (len != 0) {
2314                 gnutls_assert();
2315                 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
2316         }
2317
2318         /* reset handshake hash buffers */
2319         handshake_hash_buffer_empty(session);
2320
2321         return 0;
2322 }
2323
2324 /* The packets in gnutls_handshake (it's more broad than original TLS handshake)
2325  *
2326  *     Client                                               Server
2327  *
2328  *     ClientHello                  -------->
2329  *                                  <--------         ServerHello
2330  *
2331  *                                                    Certificate*
2332  *                                              ServerKeyExchange*
2333  *                                  <--------   CertificateRequest*
2334  *
2335  *                                  <--------      ServerHelloDone
2336  *     Certificate*
2337  *     ClientKeyExchange
2338  *     CertificateVerify*
2339  *     [ChangeCipherSpec]
2340  *     Finished                     -------->
2341  *                                                NewSessionTicket
2342  *                                              [ChangeCipherSpec]
2343  *                                  <--------             Finished
2344  *
2345  * (*): means optional packet.
2346  */
2347
2348 /* Handshake when resumming session:
2349  *      Client                                                Server
2350  *
2351  *      ClientHello                   -------->
2352  *                                                      ServerHello
2353  *                                               [ChangeCipherSpec]
2354  *                                   <--------             Finished
2355  *     [ChangeCipherSpec]
2356  *     Finished                      -------->
2357  * 
2358  */
2359
2360 /**
2361  * gnutls_rehandshake:
2362  * @session: is a #gnutls_session_t structure.
2363  *
2364  * This function will renegotiate security parameters with the
2365  * client.  This should only be called in case of a server.
2366  *
2367  * This message informs the peer that we want to renegotiate
2368  * parameters (perform a handshake).
2369  *
2370  * If this function succeeds (returns 0), you must call the
2371  * gnutls_handshake() function in order to negotiate the new
2372  * parameters.
2373  *
2374  * Since TLS is full duplex some application data might have been
2375  * sent during peer's processing of this message. In that case
2376  * one should call gnutls_record_recv() until GNUTLS_E_REHANDSHAKE
2377  * is returned to clear any pending data. Care must be taken, if
2378  * rehandshake is mandatory, to terminate if it does not start after
2379  * some threshold.
2380  *
2381  * If the client does not wish to renegotiate parameters he 
2382  * should reply with an alert message, thus the return code will be
2383  * %GNUTLS_E_WARNING_ALERT_RECEIVED and the alert will be
2384  * %GNUTLS_A_NO_RENEGOTIATION.  A client may also choose to ignore
2385  * this message.
2386  *
2387  * Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code.
2388  **/
2389 int gnutls_rehandshake(gnutls_session_t session)
2390 {
2391         int ret;
2392
2393         /* only server sends that handshake packet */
2394         if (session->security_parameters.entity == GNUTLS_CLIENT)
2395                 return GNUTLS_E_INVALID_REQUEST;
2396
2397         _dtls_async_timer_delete(session);
2398
2399         ret =
2400             _gnutls_send_empty_handshake(session,
2401                                          GNUTLS_HANDSHAKE_HELLO_REQUEST,
2402                                          AGAIN(STATE50));
2403         STATE = STATE50;
2404
2405         if (ret < 0) {
2406                 gnutls_assert();
2407                 return ret;
2408         }
2409         STATE = STATE0;
2410
2411         return 0;
2412 }
2413
2414 inline static int
2415 _gnutls_abort_handshake(gnutls_session_t session, int ret)
2416 {
2417         if (((ret == GNUTLS_E_WARNING_ALERT_RECEIVED) &&
2418              (gnutls_alert_get(session) == GNUTLS_A_NO_RENEGOTIATION))
2419             || ret == GNUTLS_E_GOT_APPLICATION_DATA)
2420                 return 0;
2421
2422         /* this doesn't matter */
2423         return GNUTLS_E_INTERNAL_ERROR;
2424 }
2425
2426
2427
2428 static int _gnutls_send_supplemental(gnutls_session_t session, int again)
2429 {
2430         mbuffer_st *bufel;
2431         int ret = 0;
2432
2433         _gnutls_debug_log("EXT[%p]: Sending supplemental data\n", session);
2434
2435         if (again)
2436                 ret =
2437                     _gnutls_send_handshake(session, NULL,
2438                                            GNUTLS_HANDSHAKE_SUPPLEMENTAL);
2439         else {
2440                 gnutls_buffer_st buf;
2441                 _gnutls_buffer_init(&buf);
2442
2443                 ret = _gnutls_gen_supplemental(session, &buf);
2444                 if (ret < 0) {
2445                         gnutls_assert();
2446                         return ret;
2447                 }
2448
2449                 bufel =
2450                     _gnutls_handshake_alloc(session, 
2451                                             buf.length);
2452                 if (bufel == NULL) {
2453                         gnutls_assert();
2454                         return GNUTLS_E_MEMORY_ERROR;
2455                 }
2456
2457                 _mbuffer_set_udata(bufel, buf.data, buf.length);
2458                 _gnutls_buffer_clear(&buf);
2459
2460                 ret = _gnutls_send_handshake(session, bufel,
2461                                              GNUTLS_HANDSHAKE_SUPPLEMENTAL);
2462         }
2463
2464         return ret;
2465 }
2466
2467 static int _gnutls_recv_supplemental(gnutls_session_t session)
2468 {
2469         gnutls_buffer_st buf;
2470         int ret;
2471
2472         _gnutls_debug_log("EXT[%p]: Expecting supplemental data\n",
2473                           session);
2474
2475         ret =
2476             _gnutls_recv_handshake(session, GNUTLS_HANDSHAKE_SUPPLEMENTAL,
2477                                    1, &buf);
2478         if (ret < 0) {
2479                 gnutls_assert();
2480                 return ret;
2481         }
2482
2483         ret = _gnutls_parse_supplemental(session, buf.data, buf.length);
2484         if (ret < 0) {
2485                 gnutls_assert();
2486                 goto cleanup;
2487         }
2488
2489       cleanup:
2490         _gnutls_buffer_clear(&buf);
2491
2492         return ret;
2493 }
2494
2495 /**
2496  * gnutls_handshake:
2497  * @session: is a #gnutls_session_t structure.
2498  *
2499  * This function does the handshake of the TLS/SSL protocol, and
2500  * initializes the TLS connection.
2501  *
2502  * This function will fail if any problem is encountered, and will
2503  * return a negative error code. In case of a client, if the client
2504  * has asked to resume a session, but the server couldn't, then a
2505  * full handshake will be performed.
2506  *
2507  * The non-fatal errors expected by this function are:
2508  * %GNUTLS_E_INTERRUPTED, %GNUTLS_E_AGAIN, 
2509  * %GNUTLS_E_WARNING_ALERT_RECEIVED, and %GNUTLS_GOT_APPLICATION_DATA,
2510  * the latter only in a case of rehandshake.
2511  *
2512  * The former two interrupt the handshake procedure due to the lower
2513  * layer being interrupted, and the latter because of an alert that
2514  * may be sent by a server (it is always a good idea to check any
2515  * received alerts). On these errors call this function again, until it
2516  * returns 0; cf.  gnutls_record_get_direction() and
2517  * gnutls_error_is_fatal(). In DTLS sessions the non-fatal error
2518  * %GNUTLS_E_LARGE_PACKET is also possible, and indicates that
2519  * the MTU should be adjusted.
2520  *
2521  * If this function is called by a server after a rehandshake request
2522  * then %GNUTLS_E_GOT_APPLICATION_DATA or
2523  * %GNUTLS_E_WARNING_ALERT_RECEIVED may be returned.  Note that these
2524  * are non fatal errors, only in the specific case of a rehandshake.
2525  * Their meaning is that the client rejected the rehandshake request or
2526  * in the case of %GNUTLS_E_GOT_APPLICATION_DATA it could also mean that
2527  * some data were pending. A client may receive that error code if
2528  * it initiates the handshake and the server doesn't agreed.
2529  *
2530  * Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code.
2531  **/
2532 int gnutls_handshake(gnutls_session_t session)
2533 {
2534         int ret;
2535         record_parameters_st *params;
2536
2537         /* sanity check. Verify that there are priorities setup.
2538          */
2539
2540         if (STATE == STATE0) {
2541                 /* first call */
2542                 if (session->internals.priorities.protocol.algorithms == 0)
2543                         return gnutls_assert_val(GNUTLS_E_NO_PRIORITIES_WERE_SET);
2544
2545                 /* if no pull timeout has not been set, and a handshake timeout
2546                  * is set, disable it */
2547                 if (unlikely((session->internals.pull_timeout_func == NULL || 
2548                     (session->internals.pull_timeout_func == gnutls_system_recv_timeout && 
2549                      session->internals.pull_func != system_read)) && 
2550                      session->internals.handshake_timeout_ms != 0)) {
2551                         _gnutls_debug_log("Cannot enforce the handshake timeout; there is no pull_timeout function set.\n");
2552             session->internals.handshake_timeout_ms = 0;
2553                 }
2554
2555                 session->internals.handshake_in_progress = 1;
2556                 gettime(&session->internals.dtls.handshake_start_time);
2557                 if (session->internals.handshake_timeout_ms &&
2558                     session->internals.handshake_endtime == 0)
2559                             session->internals.handshake_endtime = session->internals.dtls.handshake_start_time.tv_sec +
2560                                 session->internals.handshake_timeout_ms / 1000;
2561         }
2562
2563         ret =
2564             _gnutls_epoch_get(session,
2565                               session->security_parameters.epoch_next,
2566                               &params);
2567         if (ret < 0) {
2568                 /* We assume the epoch is not allocated if _gnutls_epoch_get fails. */
2569                 ret =
2570                     _gnutls_epoch_alloc(session,
2571                                         session->security_parameters.
2572                                         epoch_next, NULL);
2573                 if (ret < 0)
2574                         return gnutls_assert_val(ret);
2575         }
2576
2577         if (session->security_parameters.entity == GNUTLS_CLIENT) {
2578                 do {
2579                         ret = handshake_client(session);
2580                 } while (ret == 1);
2581         } else {
2582                 ret = handshake_server(session);
2583         }
2584         if (ret < 0) {
2585                 /* In the case of a rehandshake abort
2586                  * we should reset the handshake's internal state.
2587                  */
2588                 if (_gnutls_abort_handshake(session, ret) == 0)
2589                         STATE = STATE0;
2590
2591                 return ret;
2592         }
2593
2594         /* clear handshake buffer */
2595         _gnutls_handshake_hash_buffers_clear(session);
2596
2597         if (IS_DTLS(session) == 0) {
2598                 _gnutls_handshake_io_buffer_clear(session);
2599         } else {
2600                 _dtls_async_timer_init(session);
2601         }
2602
2603         _gnutls_handshake_internal_state_clear(session);
2604
2605         session->security_parameters.epoch_next++;
2606
2607         return 0;
2608 }
2609
2610 /**
2611  * gnutls_handshake_set_timeout:
2612  * @session: is a #gnutls_session_t structure.
2613  * @ms: is a timeout value in milliseconds
2614  *
2615  * This function sets the timeout for the TLS handshake process
2616  * to the provided value. Use an @ms value of zero to disable
2617  * timeout, or %GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT for a reasonable
2618  * default value. For the DTLS protocol, the more detailed
2619  * gnutls_dtls_set_timeouts() is provided.
2620  *
2621  * The TLS handshake process always has the default timeout value since 
2622  * GnuTLS 3.4.0. To unset call this function with zero value.
2623  *
2624  * Since: 3.1.0
2625  **/
2626 void
2627 gnutls_handshake_set_timeout(gnutls_session_t session, unsigned int ms)
2628 {
2629         if (ms == GNUTLS_DEFAULT_HANDSHAKE_TIMEOUT)
2630                 ms = DEFAULT_HANDSHAKE_TIMEOUT_MS;
2631         session->internals.handshake_timeout_ms = ms;
2632 }
2633
2634
2635 #define IMED_RET( str, ret, allow_alert) do { \
2636         if (ret < 0) { \
2637                 /* EAGAIN and INTERRUPTED are always non-fatal */ \
2638                 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) \
2639                         return ret; \
2640                 if (ret == GNUTLS_E_GOT_APPLICATION_DATA && session->internals.initial_negotiation_completed != 0) \
2641                         return ret; \
2642                 if (ret == GNUTLS_E_LARGE_PACKET && session->internals.handshake_large_loops < 16) { \
2643                         session->internals.handshake_large_loops++; \
2644                         return ret; \
2645                 } \
2646                 /* a warning alert might interrupt handshake */ \
2647                 if (allow_alert != 0 && ret==GNUTLS_E_WARNING_ALERT_RECEIVED) return ret; \
2648                 gnutls_assert(); \
2649                 ERR( str, ret); \
2650                 /* do not allow non-fatal errors at this point */ \
2651                 if (gnutls_error_is_fatal(ret) == 0) ret = gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR); \
2652                 session_invalidate(session); \
2653                 _gnutls_handshake_hash_buffers_clear(session); \
2654                 return ret; \
2655         } } while (0)
2656
2657
2658 /* Runs the certificate verification callback.
2659  * side is either GNUTLS_CLIENT or GNUTLS_SERVER.
2660  */
2661 static int run_verify_callback(gnutls_session_t session, unsigned int side)
2662 {
2663         gnutls_certificate_credentials_t cred;
2664         int ret, type;
2665
2666         cred =
2667             (gnutls_certificate_credentials_t) _gnutls_get_cred(session,
2668                                                                 GNUTLS_CRD_CERTIFICATE);
2669
2670         if (side == GNUTLS_CLIENT)
2671                 type = gnutls_auth_server_get_type(session);
2672         else
2673                 type = gnutls_auth_client_get_type(session);
2674
2675         if (type != GNUTLS_CRD_CERTIFICATE)
2676                 return 0;
2677
2678         if (cred != NULL && cred->verify_callback != NULL &&
2679             (session->security_parameters.entity == GNUTLS_CLIENT ||
2680              session->internals.send_cert_req != GNUTLS_CERT_IGNORE)) {
2681                 ret = cred->verify_callback(session);
2682                 if (ret < -1)
2683                         return ret;
2684                 else if (ret != 0)
2685                         return GNUTLS_E_CERTIFICATE_ERROR;
2686         }
2687
2688         return 0;
2689 }
2690
2691 /*
2692  * handshake_client 
2693  * This function performs the client side of the handshake of the TLS/SSL protocol.
2694  */
2695 static int handshake_client(gnutls_session_t session)
2696 {
2697         int ret = 0;
2698
2699 #ifdef HANDSHAKE_DEBUG
2700         char buf[64];
2701
2702         if (session->internals.resumed_security_parameters.
2703             session_id_size > 0)
2704                 _gnutls_handshake_log("HSK[%p]: Ask to resume: %s\n",
2705                                       session,
2706                                       _gnutls_bin2hex(session->internals.
2707                                                       resumed_security_parameters.
2708                                                 &