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