updated licenses
[gnutls.git] / lib / gnutls_handshake.c
blob3761b17353757e145d0733c1f81e16871ae32ae8
1 /*
2 * Copyright (C) 2000-2012 Free Software Foundation, Inc.
4 * Author: Nikos Mavrogiannopoulos
6 * This file is part of GnuTLS.
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 3 of
11 * the License, or (at your option) any later version.
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.
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/>
23 /* Functions that relate to the TLS handshake procedure.
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/safe_renegotiation.h>
51 #include <gnutls_rsa_export.h> /* for gnutls_get_rsa_params() */
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>
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
63 #define TRUE 1
64 #define FALSE 0
66 static int _gnutls_server_select_comp_method (gnutls_session_t session,
67 uint8_t * data, int datalen);
68 static int
69 _gnutls_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);
75 /* Empties but does not free the buffer
77 static inline void
78 _gnutls_handshake_hash_buffer_empty (gnutls_session_t session)
81 _gnutls_buffers_log ("BUF[HSK]: Emptied buffer\n");
83 session->internals.handshake_hash_buffer_prev_len = 0;
84 session->internals.handshake_hash_buffer.length = 0;
85 return;
88 static int
89 _gnutls_handshake_hash_add_recvd (gnutls_session_t session,
90 gnutls_handshake_description_t recv_type,
91 uint8_t * header, uint16_t header_size,
92 uint8_t * dataptr, uint32_t datalen);
94 static int
95 _gnutls_handshake_hash_add_sent (gnutls_session_t session,
96 gnutls_handshake_description_t type,
97 uint8_t * dataptr, uint32_t datalen);
99 static int
100 _gnutls_recv_hello_verify_request (gnutls_session_t session,
101 uint8_t * data, int datalen);
104 /* Clears the handshake hash buffers and handles.
106 void
107 _gnutls_handshake_hash_buffers_clear (gnutls_session_t session)
109 session->internals.handshake_hash_buffer_prev_len = 0;
110 _gnutls_buffer_clear(&session->internals.handshake_hash_buffer);
113 /* this will copy the required values for resuming to
114 * internals, and to security_parameters.
115 * this will keep as less data to security_parameters.
117 static void
118 resume_copy_required_values (gnutls_session_t session)
120 /* get the new random values */
121 memcpy (session->internals.resumed_security_parameters.server_random,
122 session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
123 memcpy (session->internals.resumed_security_parameters.client_random,
124 session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);
126 /* keep the ciphersuite and compression
127 * That is because the client must see these in our
128 * hello message.
130 memcpy (session->security_parameters.cipher_suite,
131 session->internals.resumed_security_parameters.cipher_suite, 2);
132 session->security_parameters.compression_method = session->internals.resumed_security_parameters.compression_method;
134 _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
135 session->
136 internals.resumed_security_parameters.cipher_suite);
137 _gnutls_epoch_set_compression (session, EPOCH_NEXT,
138 session->
139 internals.resumed_security_parameters.compression_method);
141 /* or write_compression_algorithm
142 * they are the same
145 session->security_parameters.entity =
146 session->internals.resumed_security_parameters.entity;
148 _gnutls_set_current_version (session,
149 session->internals.resumed_security_parameters.
150 version);
152 session->security_parameters.cert_type =
153 session->internals.resumed_security_parameters.cert_type;
155 memcpy (session->security_parameters.session_id,
156 session->internals.resumed_security_parameters.session_id,
157 sizeof (session->security_parameters.session_id));
158 session->security_parameters.session_id_size =
159 session->internals.resumed_security_parameters.session_id_size;
163 void
164 _gnutls_set_server_random (gnutls_session_t session, uint8_t * rnd)
166 memcpy (session->security_parameters.server_random, rnd,
167 GNUTLS_RANDOM_SIZE);
170 void
171 _gnutls_set_client_random (gnutls_session_t session, uint8_t * rnd)
173 memcpy (session->security_parameters.client_random, rnd,
174 GNUTLS_RANDOM_SIZE);
177 /* Calculate The SSL3 Finished message
179 #define SSL3_CLIENT_MSG "CLNT"
180 #define SSL3_SERVER_MSG "SRVR"
181 #define SSL_MSG_LEN 4
182 static int
183 _gnutls_ssl3_finished (gnutls_session_t session, int type, uint8_t * ret, int sending)
185 digest_hd_st td_md5;
186 digest_hd_st td_sha;
187 const char *mesg;
188 int rc, len;
190 if (sending)
191 len = session->internals.handshake_hash_buffer.length;
192 else
193 len = session->internals.handshake_hash_buffer_prev_len;
195 rc = _gnutls_hash_init (&td_sha, GNUTLS_DIG_SHA1);
196 if (rc < 0)
197 return gnutls_assert_val(rc);
199 rc = _gnutls_hash_init (&td_md5, GNUTLS_DIG_MD5);
200 if (rc < 0)
202 _gnutls_hash_deinit (&td_sha, NULL);
203 return gnutls_assert_val(rc);
206 _gnutls_hash(&td_sha, session->internals.handshake_hash_buffer.data, len);
207 _gnutls_hash(&td_md5, session->internals.handshake_hash_buffer.data, len);
209 if (type == GNUTLS_SERVER)
210 mesg = SSL3_SERVER_MSG;
211 else
212 mesg = SSL3_CLIENT_MSG;
214 _gnutls_hash (&td_md5, mesg, SSL_MSG_LEN);
215 _gnutls_hash (&td_sha, mesg, SSL_MSG_LEN);
217 rc = _gnutls_mac_deinit_ssl3_handshake (&td_md5, ret,
218 session->
219 security_parameters.master_secret,
220 GNUTLS_MASTER_SIZE);
221 if (rc < 0)
223 _gnutls_hash_deinit (&td_md5, NULL);
224 _gnutls_hash_deinit (&td_sha, NULL);
225 return gnutls_assert_val(rc);
228 rc = _gnutls_mac_deinit_ssl3_handshake (&td_sha, &ret[16],
229 session->
230 security_parameters.master_secret,
231 GNUTLS_MASTER_SIZE);
232 if (rc < 0)
234 _gnutls_hash_deinit (&td_sha, NULL);
235 return gnutls_assert_val(rc);
238 return 0;
241 /* Hash the handshake messages as required by TLS 1.0
243 #define SERVER_MSG "server finished"
244 #define CLIENT_MSG "client finished"
245 #define TLS_MSG_LEN 15
246 static int
247 _gnutls_finished (gnutls_session_t session, int type, void *ret, int sending)
249 const int siz = TLS_MSG_LEN;
250 uint8_t concat[MAX_HASH_SIZE + 16 /*MD5 */ ];
251 size_t hash_len;
252 const char *mesg;
253 int rc, len;
255 if (sending)
256 len = session->internals.handshake_hash_buffer.length;
257 else
258 len = session->internals.handshake_hash_buffer_prev_len;
260 if (!_gnutls_version_has_selectable_prf (gnutls_protocol_get_version(session)))
262 rc = _gnutls_hash_fast( GNUTLS_DIG_SHA1, session->internals.handshake_hash_buffer.data, len, &concat[16]);
263 if (rc < 0)
264 return gnutls_assert_val(rc);
266 rc = _gnutls_hash_fast( GNUTLS_DIG_MD5, session->internals.handshake_hash_buffer.data, len, concat);
267 if (rc < 0)
268 return gnutls_assert_val(rc);
270 hash_len = 20 + 16;
272 else
274 int algorithm = _gnutls_cipher_suite_get_prf(session->security_parameters.cipher_suite);
276 rc = _gnutls_hash_fast( algorithm, session->internals.handshake_hash_buffer.data, len, concat);
277 if (rc < 0)
278 return gnutls_assert_val(rc);
280 hash_len = _gnutls_hash_get_algo_len (algorithm);
283 if (type == GNUTLS_SERVER)
285 mesg = SERVER_MSG;
287 else
289 mesg = CLIENT_MSG;
292 return _gnutls_PRF (session, session->security_parameters.master_secret,
293 GNUTLS_MASTER_SIZE, mesg, siz, concat, hash_len, 12, ret);
296 /* this function will produce GNUTLS_RANDOM_SIZE==32 bytes of random data
297 * and put it to dst.
300 _gnutls_tls_create_random (uint8_t * dst)
302 uint32_t tim;
303 int ret;
305 /* Use weak random numbers for the most of the
306 * buffer except for the first 4 that are the
307 * system's time.
310 tim = gnutls_time (NULL);
311 /* generate server random value */
312 _gnutls_write_uint32 (tim, dst);
314 ret = _gnutls_rnd (GNUTLS_RND_NONCE, &dst[4], GNUTLS_RANDOM_SIZE - 4);
315 if (ret < 0)
317 gnutls_assert ();
318 return ret;
321 return 0;
324 /* returns the 0 on success or a negative error code.
327 _gnutls_negotiate_version (gnutls_session_t session,
328 gnutls_protocol_t adv_version)
330 int ret;
332 /* if we do not support that version */
333 if (_gnutls_version_is_supported (session, adv_version) == 0)
335 /* If he requested something we do not support
336 * then we send him the highest we support.
338 ret = _gnutls_version_max (session);
339 if (ret == GNUTLS_VERSION_UNKNOWN)
341 /* this check is not really needed.
343 gnutls_assert ();
344 return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
347 else
349 ret = adv_version;
352 _gnutls_set_current_version (session, ret);
354 return ret;
358 _gnutls_user_hello_func (gnutls_session_t session,
359 gnutls_protocol_t adv_version)
361 int ret;
363 if (session->internals.user_hello_func != NULL)
365 ret = session->internals.user_hello_func (session);
366 if (ret < 0)
368 gnutls_assert ();
369 return ret;
371 /* Here we need to renegotiate the version since the callee might
372 * have disabled some TLS versions.
374 ret = _gnutls_negotiate_version (session, adv_version);
375 if (ret < 0)
377 gnutls_assert ();
378 return ret;
381 return 0;
384 /* Read a client hello packet.
385 * A client hello must be a known version client hello
386 * or version 2.0 client hello (only for compatibility
387 * since SSL version 2.0 is not supported).
389 static int
390 _gnutls_read_client_hello (gnutls_session_t session, uint8_t * data,
391 int datalen)
393 uint8_t session_id_len;
394 int pos = 0, ret;
395 uint16_t suite_size, comp_size;
396 gnutls_protocol_t adv_version;
397 int neg_version;
398 int len = datalen;
399 uint8_t rnd[GNUTLS_RANDOM_SIZE], *suite_ptr, *comp_ptr, *session_id;
401 DECR_LEN (len, 2);
403 _gnutls_handshake_log ("HSK[%p]: Client's version: %d.%d\n", session,
404 data[pos], data[pos + 1]);
406 adv_version = _gnutls_version_get (data[pos], data[pos + 1]);
407 set_adv_version (session, data[pos], data[pos + 1]);
408 pos += 2;
410 neg_version = _gnutls_negotiate_version (session, adv_version);
411 if (neg_version < 0)
413 gnutls_assert ();
414 return neg_version;
417 /* Read client random value.
419 DECR_LEN (len, GNUTLS_RANDOM_SIZE);
420 _gnutls_set_client_random (session, &data[pos]);
421 pos += GNUTLS_RANDOM_SIZE;
423 _gnutls_tls_create_random (rnd);
424 _gnutls_set_server_random (session, rnd);
426 session->security_parameters.timestamp = gnutls_time (NULL);
428 DECR_LEN (len, 1);
429 session_id_len = data[pos++];
431 /* RESUME SESSION
433 if (session_id_len > TLS_MAX_SESSION_ID_SIZE)
435 gnutls_assert ();
436 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
438 DECR_LEN (len, session_id_len);
439 session_id = &data[pos];
440 pos += session_id_len;
442 if (IS_DTLS(session))
444 int cookie_size;
446 DECR_LEN (len, 1);
447 cookie_size = data[pos++];
448 DECR_LEN (len, cookie_size);
449 pos+=cookie_size;
452 ret = _gnutls_server_restore_session (session, session_id, session_id_len);
454 if (session_id_len > 0) session->internals.resumption_requested = 1;
456 if (ret == 0)
457 { /* resumed using default TLS resumption! */
458 /* Parse only the safe renegotiation extension
459 * We don't want to parse any other extensions since
460 * we don't want new extension values to overwrite the
461 * resumed ones.
464 /* move forward to extensions */
465 DECR_LEN (len, 2);
466 suite_size = _gnutls_read_uint16 (&data[pos]);
467 pos += 2;
469 DECR_LEN (len, suite_size);
470 pos += suite_size;
472 DECR_LEN (len, 1);
473 comp_size = data[pos++]; /* z is the number of compression methods */
474 DECR_LEN (len, comp_size);
475 pos += comp_size;
477 ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
478 &data[pos], len);
479 if (ret < 0)
481 gnutls_assert ();
482 return ret;
485 resume_copy_required_values (session);
486 session->internals.resumed = RESUME_TRUE;
488 return _gnutls_user_hello_func (session, adv_version);
490 else
492 _gnutls_generate_session_id (session->security_parameters.session_id,
493 &session->
494 security_parameters.session_id_size);
496 session->internals.resumed = RESUME_FALSE;
499 /* Remember ciphersuites for later
501 DECR_LEN (len, 2);
502 suite_size = _gnutls_read_uint16 (&data[pos]);
503 pos += 2;
505 DECR_LEN (len, suite_size);
506 suite_ptr = &data[pos];
507 pos += suite_size;
509 /* Point to the compression methods
511 DECR_LEN (len, 1);
512 comp_size = data[pos++]; /* z is the number of compression methods */
514 DECR_LEN (len, comp_size);
515 comp_ptr = &data[pos];
516 pos += comp_size;
518 /* Parse the extensions (if any)
520 * Unconditionally try to parse extensions; safe renegotiation uses them in
521 * sslv3 and higher, even though sslv3 doesn't officially support them.
523 ret = _gnutls_parse_extensions (session, GNUTLS_EXT_APPLICATION,
524 &data[pos], len);
525 /* len is the rest of the parsed length */
526 if (ret < 0)
528 gnutls_assert ();
529 return ret;
532 ret = _gnutls_user_hello_func (session, adv_version);
533 if (ret < 0)
535 gnutls_assert ();
536 return ret;
539 ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
540 &data[pos], len);
541 if (ret < 0)
543 gnutls_assert ();
544 return ret;
547 ret = _gnutls_parse_extensions (session, GNUTLS_EXT_TLS, &data[pos], len);
548 if (ret < 0)
550 gnutls_assert ();
551 return ret;
554 /* resumed by session_ticket extension */
555 if (session->internals.resumed != RESUME_FALSE)
557 /* to indicate the client that the current session is resumed */
558 memcpy (session->internals.resumed_security_parameters.session_id,
559 session_id, session_id_len);
560 session->internals.resumed_security_parameters.session_id_size =
561 session_id_len;
563 session->internals.resumed_security_parameters.max_record_recv_size =
564 session->security_parameters.max_record_recv_size;
565 session->internals.resumed_security_parameters.max_record_send_size =
566 session->security_parameters.max_record_send_size;
568 resume_copy_required_values (session);
570 return _gnutls_user_hello_func (session, adv_version);
573 /* select an appropriate cipher suite
575 ret = _gnutls_server_select_suite (session, suite_ptr, suite_size);
576 if (ret < 0)
578 gnutls_assert ();
579 return ret;
582 /* select appropriate compression method */
583 ret = _gnutls_server_select_comp_method (session, comp_ptr, comp_size);
584 if (ret < 0)
586 gnutls_assert ();
587 return ret;
590 return 0;
593 /* This is to be called after sending CHANGE CIPHER SPEC packet
594 * and initializing encryption. This is the first encrypted message
595 * we send.
597 static int
598 _gnutls_send_finished (gnutls_session_t session, int again)
600 mbuffer_st *bufel;
601 uint8_t *data;
602 int ret;
603 size_t vdata_size = 0;
605 if (again == 0)
607 bufel = _gnutls_handshake_alloc (session, MAX_VERIFY_DATA_SIZE, MAX_VERIFY_DATA_SIZE);
608 if (bufel == NULL)
610 gnutls_assert ();
611 return GNUTLS_E_MEMORY_ERROR;
613 data = _mbuffer_get_udata_ptr (bufel);
615 if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
617 ret =
618 _gnutls_ssl3_finished (session,
619 session->security_parameters.entity, data, 1);
620 _mbuffer_set_udata_size (bufel, 36);
622 else
623 { /* TLS 1.0+ */
624 ret = _gnutls_finished (session,
625 session->security_parameters.entity, data, 1);
626 _mbuffer_set_udata_size (bufel, 12);
629 if (ret < 0)
631 gnutls_assert ();
632 return ret;
635 vdata_size = _mbuffer_get_udata_size (bufel);
637 ret = _gnutls_ext_sr_finished (session, data, vdata_size, 0);
638 if (ret < 0)
640 gnutls_assert ();
641 return ret;
644 if ((session->internals.resumed == RESUME_FALSE
645 && session->security_parameters.entity == GNUTLS_CLIENT)
646 || (session->internals.resumed != RESUME_FALSE
647 && session->security_parameters.entity == GNUTLS_SERVER))
649 /* if we are a client not resuming - or we are a server resuming */
650 _gnutls_handshake_log ("HSK[%p]: recording tls-unique CB (send)\n",
651 session);
652 memcpy (session->internals.cb_tls_unique, data, vdata_size);
653 session->internals.cb_tls_unique_len = vdata_size;
656 ret =
657 _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_FINISHED);
659 else
661 ret = _gnutls_send_handshake (session, NULL, GNUTLS_HANDSHAKE_FINISHED);
664 return ret;
667 /* This is to be called after sending our finished message. If everything
668 * went fine we have negotiated a secure connection
670 static int
671 _gnutls_recv_finished (gnutls_session_t session)
673 uint8_t data[MAX_VERIFY_DATA_SIZE], *vrfy;
674 gnutls_buffer_st buf;
675 int data_size;
676 int ret;
677 int vrfy_size;
679 ret =
680 _gnutls_recv_handshake (session, GNUTLS_HANDSHAKE_FINISHED,
681 0, &buf);
682 if (ret < 0)
684 ERR ("recv finished int", ret);
685 gnutls_assert ();
686 return ret;
689 vrfy = buf.data;
690 vrfy_size = buf.length;
692 if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
694 data_size = 36;
696 else
698 data_size = 12;
701 if (vrfy_size != data_size)
703 gnutls_assert ();
704 ret = GNUTLS_E_ERROR_IN_FINISHED_PACKET;
705 goto cleanup;
708 if (gnutls_protocol_get_version (session) == GNUTLS_SSL3)
710 ret =
711 _gnutls_ssl3_finished (session,
712 (session->security_parameters.entity + 1) % 2,
713 data, 0);
715 else
716 { /* TLS 1.0 */
717 ret =
718 _gnutls_finished (session,
719 (session->security_parameters.entity +
720 1) % 2, data, 0);
723 if (ret < 0)
725 gnutls_assert ();
726 goto cleanup;
729 if (memcmp (vrfy, data, data_size) != 0)
731 gnutls_assert ();
732 ret = GNUTLS_E_ERROR_IN_FINISHED_PACKET;
733 goto cleanup;
736 ret = _gnutls_ext_sr_finished (session, data, data_size, 1);
737 if (ret < 0)
739 gnutls_assert ();
740 goto cleanup;
743 if ((session->internals.resumed != RESUME_FALSE
744 && session->security_parameters.entity == GNUTLS_CLIENT)
745 || (session->internals.resumed == RESUME_FALSE
746 && session->security_parameters.entity == GNUTLS_SERVER))
748 /* if we are a client resuming - or we are a server not resuming */
749 _gnutls_handshake_log ("HSK[%p]: recording tls-unique CB (recv)\n",
750 session);
751 memcpy (session->internals.cb_tls_unique, data, data_size);
752 session->internals.cb_tls_unique_len = data_size;
756 session->internals.initial_negotiation_completed = 1;
758 cleanup:
759 _gnutls_buffer_clear(&buf);
761 return ret;
764 /* returns PK_RSA if the given cipher suite list only supports,
765 * RSA algorithms, PK_DSA if DSS, and PK_ANY for both or PK_NONE for none.
767 static int
768 server_find_pk_algos_in_ciphersuites (const uint8_t *
769 data, unsigned int datalen,
770 gnutls_pk_algorithm_t * algos,
771 size_t* algos_size)
773 unsigned int j;
774 gnutls_kx_algorithm_t kx;
775 unsigned int max = *algos_size;
777 if (datalen % 2 != 0)
779 gnutls_assert ();
780 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
783 *algos_size = 0;
784 for (j = 0; j < datalen; j += 2)
786 kx = _gnutls_cipher_suite_get_kx_algo (&data[j]);
787 if (_gnutls_map_kx_get_cred (kx, 1) == GNUTLS_CRD_CERTIFICATE)
789 algos[(*algos_size)++] = _gnutls_map_pk_get_pk (kx);
791 if ((*algos_size) >= max)
792 return 0;
796 return 0;
799 /* This selects the best supported ciphersuite from the given ones. Then
800 * it adds the suite to the session and performs some checks.
803 _gnutls_server_select_suite (gnutls_session_t session, uint8_t * data,
804 unsigned int datalen)
806 int ret;
807 unsigned int i, j, cipher_suites_size;
808 size_t pk_algos_size;
809 uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];
810 int retval, err;
811 gnutls_pk_algorithm_t pk_algos[MAX_ALGOS]; /* will hold the pk algorithms
812 * supported by the peer.
815 /* First, check for safe renegotiation SCSV.
817 if (session->internals.priorities.sr != SR_DISABLED)
819 unsigned int offset;
821 for (offset = 0; offset < datalen; offset += 2)
823 /* TLS_RENEGO_PROTECTION_REQUEST = { 0x00, 0xff } */
824 if (data[offset] == GNUTLS_RENEGO_PROTECTION_REQUEST_MAJOR &&
825 data[offset + 1] == GNUTLS_RENEGO_PROTECTION_REQUEST_MINOR)
827 _gnutls_handshake_log
828 ("HSK[%p]: Received safe renegotiation CS\n", session);
829 retval = _gnutls_ext_sr_recv_cs (session);
830 if (retval < 0)
832 gnutls_assert ();
833 return retval;
835 break;
840 pk_algos_size = MAX_ALGOS;
841 ret = server_find_pk_algos_in_ciphersuites (data, datalen, pk_algos, &pk_algos_size);
842 if (ret < 0)
843 return gnutls_assert_val(ret);
845 ret = _gnutls_supported_ciphersuites (session, cipher_suites, sizeof(cipher_suites));
846 if (ret < 0)
847 return gnutls_assert_val(ret);
849 cipher_suites_size = ret;
851 /* Here we remove any ciphersuite that does not conform
852 * the certificate requested, or to the
853 * authentication requested (e.g. SRP).
855 ret = _gnutls_remove_unwanted_ciphersuites (session, cipher_suites, cipher_suites_size, pk_algos, pk_algos_size);
856 if (ret <= 0)
858 gnutls_assert ();
859 if (ret < 0)
860 return ret;
861 else
862 return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
865 cipher_suites_size = ret;
867 /* Data length should be zero mod 2 since
868 * every ciphersuite is 2 bytes. (this check is needed
869 * see below).
871 if (datalen % 2 != 0)
873 gnutls_assert ();
874 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
877 memset (session->security_parameters.cipher_suite, 0, 2);
879 retval = GNUTLS_E_UNKNOWN_CIPHER_SUITE;
881 _gnutls_handshake_log ("HSK[%p]: Requested cipher suites[size: %d]: \n", session, (int)datalen);
883 if (session->internals.priorities.server_precedence == 0)
885 for (j = 0; j < datalen; j += 2)
887 _gnutls_handshake_log ("\t0x%.2x, 0x%.2x %s\n", data[j], data[j+1], _gnutls_cipher_suite_get_name (&data[j]));
888 for (i = 0; i < cipher_suites_size; i+=2)
890 if (memcmp (&cipher_suites[i], &data[j], 2) == 0)
892 _gnutls_handshake_log
893 ("HSK[%p]: Selected cipher suite: %s\n", session,
894 _gnutls_cipher_suite_get_name (&data[j]));
895 memcpy (session->security_parameters.cipher_suite,
896 &cipher_suites[i], 2);
897 _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
898 session->
899 security_parameters.cipher_suite);
902 retval = 0;
903 goto finish;
908 else /* server selects */
910 for (i = 0; i < cipher_suites_size; i+=2)
912 for (j = 0; j < datalen; j += 2)
914 if (memcmp (&cipher_suites[i], &data[j], 2) == 0)
916 _gnutls_handshake_log
917 ("HSK[%p]: Selected cipher suite: %s\n", session,
918 _gnutls_cipher_suite_get_name (&data[j]));
919 memcpy (session->security_parameters.cipher_suite,
920 &cipher_suites[i], 2);
921 _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
922 session->
923 security_parameters.cipher_suite);
926 retval = 0;
927 goto finish;
932 finish:
934 if (retval != 0)
936 gnutls_assert ();
937 return retval;
940 /* check if the credentials (username, public key etc.) are ok
942 if (_gnutls_get_kx_cred
943 (session,
944 _gnutls_cipher_suite_get_kx_algo (session->
945 security_parameters.cipher_suite),
946 &err) == NULL && err != 0)
948 gnutls_assert ();
949 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
953 /* set the mod_auth_st to the appropriate struct
954 * according to the KX algorithm. This is needed since all the
955 * handshake functions are read from there;
957 session->internals.auth_struct =
958 _gnutls_kx_auth_struct (_gnutls_cipher_suite_get_kx_algo
959 (session->
960 security_parameters.cipher_suite));
961 if (session->internals.auth_struct == NULL)
964 _gnutls_handshake_log
965 ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
966 session);
967 gnutls_assert ();
968 return GNUTLS_E_INTERNAL_ERROR;
971 return 0;
976 /* This selects the best supported compression method from the ones provided
978 static int
979 _gnutls_server_select_comp_method (gnutls_session_t session,
980 uint8_t * data, int datalen)
982 int x, i, j;
983 uint8_t comps[MAX_ALGOS];
985 x = _gnutls_supported_compression_methods (session, comps, MAX_ALGOS);
986 if (x < 0)
988 gnutls_assert ();
989 return x;
992 if (session->internals.priorities.server_precedence == 0)
994 for (j = 0; j < datalen; j++)
996 for (i = 0; i < x; i++)
998 if (comps[i] == data[j])
1000 gnutls_compression_method_t method =
1001 _gnutls_compression_get_id (comps[i]);
1003 _gnutls_epoch_set_compression (session, EPOCH_NEXT, method);
1004 session->security_parameters.compression_method = method;
1006 _gnutls_handshake_log
1007 ("HSK[%p]: Selected Compression Method: %s\n", session,
1008 gnutls_compression_get_name (method));
1009 return 0;
1014 else
1016 for (i = 0; i < x; i++)
1018 for (j = 0; j < datalen; j++)
1020 if (comps[i] == data[j])
1022 gnutls_compression_method_t method =
1023 _gnutls_compression_get_id (comps[i]);
1025 _gnutls_epoch_set_compression (session, EPOCH_NEXT, method);
1026 session->security_parameters.compression_method = method;
1028 _gnutls_handshake_log
1029 ("HSK[%p]: Selected Compression Method: %s\n", session,
1030 gnutls_compression_get_name (method));
1031 return 0;
1037 /* we were not able to find a compatible compression
1038 * algorithm
1040 gnutls_assert ();
1041 return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1045 /* This function sends an empty handshake packet. (like hello request).
1046 * If the previous _gnutls_send_empty_handshake() returned
1047 * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED, then it must be called again
1048 * (until it returns ok), with NULL parameters.
1050 static int
1051 _gnutls_send_empty_handshake (gnutls_session_t session,
1052 gnutls_handshake_description_t type, int again)
1054 mbuffer_st *bufel;
1056 if (again == 0)
1058 bufel = _gnutls_handshake_alloc (session, 0, 0);
1059 if (bufel == NULL)
1061 gnutls_assert ();
1062 return GNUTLS_E_MEMORY_ERROR;
1065 else
1066 bufel = NULL;
1068 return _gnutls_send_handshake (session, bufel, type);
1074 /* This function sends a handshake message of type 'type' containing the
1075 * data specified here. If the previous _gnutls_send_handshake() returned
1076 * GNUTLS_E_AGAIN or GNUTLS_E_INTERRUPTED, then it must be called again
1077 * (until it returns ok), with NULL parameters.
1080 _gnutls_send_handshake (gnutls_session_t session, mbuffer_st * bufel,
1081 gnutls_handshake_description_t type)
1083 int ret;
1084 uint8_t *data;
1085 uint32_t datasize, i_datasize;
1086 int pos = 0;
1088 if (bufel == NULL)
1090 /* we are resuming a previously interrupted
1091 * send.
1093 ret = _gnutls_handshake_io_write_flush (session);
1094 return ret;
1098 /* first run */
1099 data = _mbuffer_get_uhead_ptr (bufel);
1100 i_datasize = _mbuffer_get_udata_size(bufel);
1101 datasize = i_datasize + _mbuffer_get_uhead_size (bufel);
1103 data[pos++] = (uint8_t) type;
1104 _gnutls_write_uint24 (_mbuffer_get_udata_size (bufel), &data[pos]);
1105 pos += 3;
1107 /* Add DTLS handshake fragment headers. The message will be
1108 * fragmented later by the fragmentation sub-layer. All fields must
1109 * be set properly for HMAC. The HMAC requires we pretend that the
1110 * message was sent in a single fragment. */
1111 if (IS_DTLS(session))
1113 _gnutls_write_uint16 (session->internals.dtls.hsk_write_seq++, &data[pos]);
1114 pos += 2;
1116 /* Fragment offset */
1117 _gnutls_write_uint24 (0, &data[pos]);
1118 pos += 3;
1120 /* Fragment length */
1121 _gnutls_write_uint24 (i_datasize, &data[pos]);
1122 pos += 3;
1125 _gnutls_handshake_log ("HSK[%p]: %s was queued [%ld bytes]\n",
1126 session, _gnutls_handshake2str (type),
1127 (long) datasize);
1129 /* Here we keep the handshake messages in order to hash them...
1131 if (type != GNUTLS_HANDSHAKE_HELLO_REQUEST)
1132 if ((ret =
1133 _gnutls_handshake_hash_add_sent (session, type, data, datasize)) < 0)
1135 gnutls_assert ();
1136 _mbuffer_xfree(&bufel);
1137 return ret;
1140 session->internals.last_handshake_out = type;
1142 ret = _gnutls_handshake_io_cache_int (session, type, bufel);
1143 if (ret < 0)
1145 _mbuffer_xfree(&bufel);
1146 gnutls_assert();
1147 return ret;
1150 switch (type)
1152 case GNUTLS_HANDSHAKE_CERTIFICATE_PKT: /* this one is followed by ServerHelloDone
1153 * or ClientKeyExchange always.
1155 case GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE: /* as above */
1156 case GNUTLS_HANDSHAKE_SERVER_HELLO: /* as above */
1157 case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST: /* as above */
1158 case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET: /* followed by ChangeCipherSpec */
1160 /* now for client Certificate, ClientKeyExchange and
1161 * CertificateVerify are always followed by ChangeCipherSpec
1163 case GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY:
1164 case GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE:
1165 ret = 0;
1166 break;
1167 default:
1168 /* send cached messages */
1169 ret = _gnutls_handshake_io_write_flush (session);
1170 break;
1173 return ret;
1176 #define CHECK_SIZE(ll) \
1177 if ((session->internals.max_handshake_data_buffer_size > 0) && \
1178 (((ll) + session->internals.handshake_hash_buffer.length) > \
1179 session->internals.max_handshake_data_buffer_size)) \
1180 return gnutls_assert_val(GNUTLS_E_HANDSHAKE_TOO_LARGE)
1182 /* This function add the handshake headers and the
1183 * handshake data to the handshake hash buffers. Needed
1184 * for the finished messages calculations.
1186 static int
1187 _gnutls_handshake_hash_add_recvd (gnutls_session_t session,
1188 gnutls_handshake_description_t recv_type,
1189 uint8_t * header, uint16_t header_size,
1190 uint8_t * dataptr, uint32_t datalen)
1192 int ret;
1194 if (recv_type == GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST ||
1195 recv_type == GNUTLS_HANDSHAKE_HELLO_REQUEST)
1196 return 0;
1198 CHECK_SIZE(header_size + datalen);
1200 session->internals.handshake_hash_buffer_prev_len = session->internals.handshake_hash_buffer.length;
1202 ret = _gnutls_buffer_append_data(&session->internals.handshake_hash_buffer,
1203 header, header_size);
1204 if (ret < 0)
1205 return gnutls_assert_val(ret);
1207 if (datalen > 0)
1209 ret = _gnutls_buffer_append_data(&session->internals.handshake_hash_buffer,
1210 dataptr, datalen);
1211 if (ret < 0)
1212 return gnutls_assert_val(ret);
1215 return 0;
1218 /* This function will store the handshake message we sent.
1220 static int
1221 _gnutls_handshake_hash_add_sent (gnutls_session_t session,
1222 gnutls_handshake_description_t type,
1223 uint8_t * dataptr, uint32_t datalen)
1225 int ret;
1227 /* We don't check for GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST because it
1228 * is not sent via that channel.
1230 if (type != GNUTLS_HANDSHAKE_HELLO_REQUEST)
1232 CHECK_SIZE(datalen);
1234 ret = _gnutls_buffer_append_data(&session->internals.handshake_hash_buffer,
1235 dataptr, datalen);
1236 if (ret < 0)
1237 return gnutls_assert_val(ret);
1239 return 0;
1242 return 0;
1246 /* This function will receive handshake messages of the given types,
1247 * and will pass the message to the right place in order to be processed.
1248 * E.g. for the SERVER_HELLO message (if it is expected), it will be
1249 * passed to _gnutls_recv_hello().
1252 _gnutls_recv_handshake (gnutls_session_t session,
1253 gnutls_handshake_description_t type,
1254 unsigned int optional, gnutls_buffer_st* buf)
1256 int ret;
1257 handshake_buffer_st hsk;
1259 ret =
1260 _gnutls_handshake_io_recv_int (session, type, &hsk, optional);
1261 if (ret < 0)
1263 if (optional != 0 && ret == GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET)
1265 if (buf) _gnutls_buffer_init(buf);
1266 return 0;
1269 return gnutls_assert_val_fatal(ret);
1272 ret = _gnutls_handshake_hash_add_recvd (session, hsk.htype,
1273 hsk.header, hsk.header_size,
1274 hsk.data.data, hsk.data.length);
1275 if (ret < 0)
1277 gnutls_assert ();
1278 goto cleanup;
1281 switch (hsk.htype)
1283 case GNUTLS_HANDSHAKE_CLIENT_HELLO_V2:
1284 case GNUTLS_HANDSHAKE_CLIENT_HELLO:
1285 case GNUTLS_HANDSHAKE_SERVER_HELLO:
1286 if (hsk.htype == GNUTLS_HANDSHAKE_CLIENT_HELLO_V2)
1287 ret = _gnutls_read_client_hello_v2 (session, hsk.data.data, hsk.data.length);
1288 else
1289 ret = _gnutls_recv_hello (session, hsk.data.data, hsk.data.length);
1291 if (ret < 0)
1293 gnutls_assert();
1294 goto cleanup;
1297 goto cleanup; /* caller doesn't need dataptr */
1299 break;
1300 case GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST:
1301 ret = _gnutls_recv_hello_verify_request (session, hsk.data.data, hsk.data.length);
1302 if (ret < 0)
1304 gnutls_assert();
1305 goto cleanup;
1307 else
1308 /* Signal our caller we have received a verification cookie
1309 and ClientHello needs to be sent again. */
1310 ret = 1;
1312 goto cleanup; /* caller doesn't need dataptr */
1314 break;
1315 case GNUTLS_HANDSHAKE_SERVER_HELLO_DONE:
1316 if (hsk.data.length == 0)
1317 ret = 0;
1318 else
1320 gnutls_assert();
1321 ret = GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1322 goto cleanup;
1324 break;
1325 case GNUTLS_HANDSHAKE_CERTIFICATE_PKT:
1326 case GNUTLS_HANDSHAKE_FINISHED:
1327 case GNUTLS_HANDSHAKE_SERVER_KEY_EXCHANGE:
1328 case GNUTLS_HANDSHAKE_CLIENT_KEY_EXCHANGE:
1329 case GNUTLS_HANDSHAKE_CERTIFICATE_REQUEST:
1330 case GNUTLS_HANDSHAKE_CERTIFICATE_VERIFY:
1331 case GNUTLS_HANDSHAKE_SUPPLEMENTAL:
1332 case GNUTLS_HANDSHAKE_NEW_SESSION_TICKET:
1333 ret = hsk.data.length;
1334 break;
1335 default:
1336 gnutls_assert ();
1337 /* we shouldn't actually arrive here in any case .
1338 * unexpected messages should be catched after _gnutls_handshake_io_recv_int()
1340 ret = GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET;
1341 goto cleanup;
1344 if (buf)
1346 *buf = hsk.data;
1347 return ret;
1350 cleanup:
1351 _gnutls_handshake_buffer_clear (&hsk);
1352 return ret;
1355 /* This function checks if the given cipher suite is supported, and sets it
1356 * to the session;
1358 static int
1359 _gnutls_client_set_ciphersuite (gnutls_session_t session, uint8_t suite[2])
1361 uint8_t z;
1362 uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE];
1363 int cipher_suite_size;
1364 int i, err;
1366 z = 1;
1367 cipher_suite_size = _gnutls_supported_ciphersuites (session, cipher_suites, sizeof(cipher_suites));
1368 if (cipher_suite_size < 0)
1370 gnutls_assert ();
1371 return cipher_suite_size;
1374 for (i = 0; i < cipher_suite_size; i+=2)
1376 if (memcmp (&cipher_suites[i], suite, 2) == 0)
1378 z = 0;
1379 break;
1383 if (z != 0)
1385 gnutls_assert ();
1386 return GNUTLS_E_UNKNOWN_CIPHER_SUITE;
1389 memcpy (session->security_parameters.cipher_suite, suite, 2);
1390 _gnutls_epoch_set_cipher_suite (session, EPOCH_NEXT,
1391 session->
1392 security_parameters.cipher_suite);
1394 _gnutls_handshake_log ("HSK[%p]: Selected cipher suite: %s\n", session,
1395 _gnutls_cipher_suite_get_name
1396 (session->
1397 security_parameters.cipher_suite));
1400 /* check if the credentials (username, public key etc.) are ok.
1401 * Actually checks if they exist.
1403 if (_gnutls_get_kx_cred
1404 (session,
1405 _gnutls_cipher_suite_get_kx_algo
1406 (session->security_parameters.cipher_suite), &err) == NULL
1407 && err != 0)
1409 gnutls_assert ();
1410 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
1414 /* set the mod_auth_st to the appropriate struct
1415 * according to the KX algorithm. This is needed since all the
1416 * handshake functions are read from there;
1418 session->internals.auth_struct =
1419 _gnutls_kx_auth_struct (_gnutls_cipher_suite_get_kx_algo
1420 (session->
1421 security_parameters.cipher_suite));
1423 if (session->internals.auth_struct == NULL)
1426 _gnutls_handshake_log
1427 ("HSK[%p]: Cannot find the appropriate handler for the KX algorithm\n",
1428 session);
1429 gnutls_assert ();
1430 return GNUTLS_E_INTERNAL_ERROR;
1434 return 0;
1437 /* This function sets the given comp method to the session.
1439 static int
1440 _gnutls_client_set_comp_method (gnutls_session_t session, uint8_t comp_method)
1442 int comp_methods_num;
1443 uint8_t compression_methods[MAX_ALGOS];
1444 int id = _gnutls_compression_get_id(comp_method);
1445 int i;
1447 _gnutls_handshake_log ("HSK[%p]: Selected compression method: %s (%d)\n", session,
1448 gnutls_compression_get_name(id), (int)comp_method);
1450 comp_methods_num = _gnutls_supported_compression_methods (session,
1451 compression_methods, MAX_ALGOS);
1452 if (comp_methods_num < 0)
1454 gnutls_assert ();
1455 return comp_methods_num;
1458 for (i = 0; i < comp_methods_num; i++)
1460 if (compression_methods[i] == comp_method)
1462 comp_methods_num = 0;
1463 break;
1467 if (comp_methods_num != 0)
1469 gnutls_assert ();
1470 return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1473 session->security_parameters.compression_method = id;
1474 _gnutls_epoch_set_compression (session, EPOCH_NEXT, id);
1476 return 0;
1479 /* This function returns 0 if we are resuming a session or -1 otherwise.
1480 * This also sets the variables in the session. Used only while reading a server
1481 * hello.
1483 static int
1484 _gnutls_client_check_if_resuming (gnutls_session_t session,
1485 uint8_t * session_id, int session_id_len)
1487 char buf[2 * TLS_MAX_SESSION_ID_SIZE + 1];
1489 _gnutls_handshake_log ("HSK[%p]: SessionID length: %d\n", session,
1490 session_id_len);
1491 _gnutls_handshake_log ("HSK[%p]: SessionID: %s\n", session,
1492 _gnutls_bin2hex (session_id, session_id_len, buf,
1493 sizeof (buf), NULL));
1495 if (session_id_len > 0 &&
1496 session->internals.resumed_security_parameters.session_id_size ==
1497 session_id_len
1498 && memcmp (session_id,
1499 session->internals.resumed_security_parameters.session_id,
1500 session_id_len) == 0)
1502 /* resume session */
1503 memcpy (session->internals.resumed_security_parameters.server_random,
1504 session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
1505 memcpy (session->internals.resumed_security_parameters.client_random,
1506 session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);
1508 _gnutls_epoch_set_cipher_suite
1509 (session, EPOCH_NEXT,
1510 session->internals.
1511 resumed_security_parameters.cipher_suite);
1512 _gnutls_epoch_set_compression (session, EPOCH_NEXT,
1513 session->
1514 internals.resumed_security_parameters.compression_method);
1516 session->internals.resumed = RESUME_TRUE; /* we are resuming */
1518 return 0;
1520 else
1522 /* keep the new session id */
1523 session->internals.resumed = RESUME_FALSE; /* we are not resuming */
1524 session->security_parameters.session_id_size = session_id_len;
1525 memcpy (session->security_parameters.session_id,
1526 session_id, session_id_len);
1528 return -1;
1533 /* This function reads and parses the server hello handshake message.
1534 * This function also restores resumed parameters if we are resuming a
1535 * session.
1537 static int
1538 _gnutls_read_server_hello (gnutls_session_t session,
1539 uint8_t * data, int datalen)
1541 uint8_t session_id_len = 0;
1542 int pos = 0;
1543 int ret = 0;
1544 gnutls_protocol_t version;
1545 int len = datalen;
1547 if (datalen < 38)
1549 gnutls_assert ();
1550 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1553 _gnutls_handshake_log ("HSK[%p]: Server's version: %d.%d\n",
1554 session, data[pos], data[pos + 1]);
1556 DECR_LEN (len, 2);
1557 version = _gnutls_version_get (data[pos], data[pos + 1]);
1558 if (_gnutls_version_is_supported (session, version) == 0)
1560 gnutls_assert ();
1561 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
1563 else
1565 _gnutls_set_current_version (session, version);
1568 pos += 2;
1570 DECR_LEN (len, GNUTLS_RANDOM_SIZE);
1571 _gnutls_set_server_random (session, &data[pos]);
1572 pos += GNUTLS_RANDOM_SIZE;
1575 /* Read session ID
1577 DECR_LEN (len, 1);
1578 session_id_len = data[pos++];
1580 if (len < session_id_len)
1582 gnutls_assert ();
1583 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
1585 DECR_LEN (len, session_id_len);
1587 /* check if we are resuming and set the appropriate
1588 * values;
1590 if (_gnutls_client_check_if_resuming
1591 (session, &data[pos], session_id_len) == 0)
1593 pos += session_id_len + 2 + 1;
1594 DECR_LEN (len, 2 + 1);
1596 ret = _gnutls_parse_extensions (session, GNUTLS_EXT_MANDATORY,
1597 &data[pos], len);
1598 if (ret < 0)
1600 gnutls_assert ();
1601 return ret;
1603 return 0;
1606 pos += session_id_len;
1608 /* Check if the given cipher suite is supported and copy
1609 * it to the session.
1612 DECR_LEN (len, 2);
1613 ret = _gnutls_client_set_ciphersuite (session, &data[pos]);
1614 if (ret < 0)
1616 gnutls_assert ();
1617 return ret;
1619 pos += 2;
1621 /* move to compression
1623 DECR_LEN (len, 1);
1625 ret = _gnutls_client_set_comp_method (session, data[pos++]);
1626 if (ret < 0)
1628 gnutls_assert ();
1629 return GNUTLS_E_UNKNOWN_COMPRESSION_ALGORITHM;
1632 /* Parse extensions.
1634 ret = _gnutls_parse_extensions (session, GNUTLS_EXT_ANY, &data[pos], len);
1635 if (ret < 0)
1637 gnutls_assert ();
1638 return ret;
1641 return ret;
1645 /* This function copies the appropriate ciphersuites to a locally allocated buffer
1646 * Needed in client hello messages. Returns the new data length. If add_scsv is
1647 * true, add the special safe renegotiation CS.
1649 static int
1650 _gnutls_copy_ciphersuites (gnutls_session_t session,
1651 gnutls_buffer_st * cdata,
1652 int add_scsv)
1654 int ret;
1655 uint8_t cipher_suites[MAX_CIPHERSUITE_SIZE+2];
1656 int cipher_suites_size;
1657 size_t init_length = cdata->length;
1659 ret = _gnutls_supported_ciphersuites (session, cipher_suites, sizeof(cipher_suites)-2);
1660 if (ret < 0)
1661 return gnutls_assert_val(ret);
1663 /* Here we remove any ciphersuite that does not conform
1664 * the certificate requested, or to the
1665 * authentication requested (eg SRP).
1667 ret =
1668 _gnutls_remove_unwanted_ciphersuites (session, cipher_suites, ret, NULL, 0);
1669 if (ret < 0)
1670 return gnutls_assert_val(ret);
1672 /* If no cipher suites were enabled.
1674 if (ret == 0)
1675 return gnutls_assert_val(GNUTLS_E_INSUFFICIENT_CREDENTIALS);
1677 cipher_suites_size = ret;
1678 if (add_scsv)
1680 cipher_suites[cipher_suites_size] = 0x00;
1681 cipher_suites[cipher_suites_size+1] = 0xff;
1682 cipher_suites_size += 2;
1684 ret = _gnutls_ext_sr_send_cs (session);
1685 if (ret < 0)
1686 return gnutls_assert_val(ret);
1689 ret = _gnutls_buffer_append_data_prefix(cdata, 16, cipher_suites, cipher_suites_size);
1690 if (ret < 0)
1691 return gnutls_assert_val(ret);
1693 ret = cdata->length - init_length;
1695 return ret;
1699 /* This function copies the appropriate compression methods, to a locally allocated buffer
1700 * Needed in hello messages. Returns the new data length.
1702 static int
1703 _gnutls_copy_comp_methods (gnutls_session_t session,
1704 gnutls_buffer_st * cdata)
1706 int ret;
1707 uint8_t compression_methods[MAX_ALGOS], comp_num;
1708 size_t init_length = cdata->length;
1710 ret = _gnutls_supported_compression_methods (session, compression_methods, MAX_ALGOS);
1711 if (ret < 0)
1712 return gnutls_assert_val(ret);
1714 comp_num = ret;
1716 /* put the number of compression methods */
1717 ret = _gnutls_buffer_append_prefix(cdata, 8, comp_num);
1718 if (ret < 0)
1719 return gnutls_assert_val(ret);
1721 ret = _gnutls_buffer_append_data(cdata, compression_methods, comp_num);
1722 if (ret < 0)
1723 return gnutls_assert_val(ret);
1725 ret = cdata->length - init_length;
1727 return ret;
1730 /* This should be sufficient by now. It should hold all the extensions
1731 * plus the headers in a hello message.
1733 #define MAX_EXT_DATA_LENGTH 32*1024
1735 /* This function sends the client hello handshake message.
1737 static int
1738 _gnutls_send_client_hello (gnutls_session_t session, int again)
1740 mbuffer_st *bufel = NULL;
1741 uint8_t *data = NULL;
1742 int pos = 0, type;
1743 int datalen = 0, ret = 0;
1744 uint8_t rnd[GNUTLS_RANDOM_SIZE];
1745 gnutls_protocol_t hver;
1746 gnutls_buffer_st extdata;
1747 int rehandshake = 0;
1748 uint8_t session_id_len =
1749 session->internals.resumed_security_parameters.session_id_size;
1750 uint8_t cookie_len;
1752 _gnutls_buffer_init(&extdata);
1754 /* note that rehandshake is different than resuming
1756 if (session->security_parameters.session_id_size)
1757 rehandshake = 1;
1759 if (again == 0)
1761 if(IS_DTLS(session))
1763 cookie_len = session->internals.dtls.cookie_len + 1;
1765 else
1767 cookie_len = 0;
1770 datalen = 2 + (session_id_len + 1) + GNUTLS_RANDOM_SIZE + cookie_len;
1771 /* 2 for version, (4 for unix time + 28 for random bytes==GNUTLS_RANDOM_SIZE)
1774 bufel = _gnutls_handshake_alloc (session, datalen, datalen+MAX_EXT_DATA_LENGTH);
1775 if (bufel == NULL)
1777 gnutls_assert ();
1778 return GNUTLS_E_MEMORY_ERROR;
1780 data = _mbuffer_get_udata_ptr (bufel);
1782 /* if we are resuming a session then we set the
1783 * version number to the previously established.
1785 if (session_id_len == 0)
1787 if (rehandshake) /* already negotiated version thus version_max == negotiated version */
1788 hver = session->security_parameters.version;
1789 else /* new handshake. just get the max */
1790 hver = _gnutls_version_max (session);
1792 else
1794 /* we are resuming a session */
1795 hver = session->internals.resumed_security_parameters.version;
1798 if (hver == GNUTLS_VERSION_UNKNOWN || hver == 0)
1800 gnutls_assert ();
1801 gnutls_free (bufel);
1802 return GNUTLS_E_INTERNAL_ERROR;
1805 data[pos++] = _gnutls_version_get_major (hver);
1806 data[pos++] = _gnutls_version_get_minor (hver);
1808 /* Set the version we advertized as maximum
1809 * (RSA uses it).
1811 _gnutls_set_adv_version (session, hver);
1812 _gnutls_set_current_version (session, hver);
1814 if (session->internals.priorities.ssl3_record_version != 0)
1816 /* Advertize the SSL 3.0 record packet version in
1817 * record packets during the handshake.
1818 * That is to avoid confusing implementations
1819 * that do not support TLS 1.2 and don't know
1820 * how 3,3 version of record packets look like.
1822 if (!IS_DTLS(session))
1823 _gnutls_record_set_default_version (session, 3, 0);
1824 else
1825 _gnutls_record_set_default_version (session, 254, 255);
1828 /* In order to know when this session was initiated.
1830 session->security_parameters.timestamp = gnutls_time (NULL);
1832 /* Generate random data
1834 if (!IS_DTLS (session)
1835 || session->internals.dtls.hsk_hello_verify_requests == 0)
1837 _gnutls_tls_create_random (rnd);
1838 _gnutls_set_client_random (session, rnd);
1840 memcpy (&data[pos], rnd, GNUTLS_RANDOM_SIZE);
1842 else
1843 memcpy (&data[pos], session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);
1845 pos += GNUTLS_RANDOM_SIZE;
1847 /* Copy the Session ID
1849 data[pos++] = session_id_len;
1851 if (session_id_len > 0)
1853 memcpy (&data[pos],
1854 session->internals.resumed_security_parameters.session_id,
1855 session_id_len);
1856 pos += session_id_len;
1859 /* Copy the DTLS cookie
1861 if (IS_DTLS(session))
1863 data[pos++] = session->internals.dtls.cookie_len;
1864 memcpy(&data[pos], &session->internals.dtls.cookie, session->internals.dtls.cookie_len);
1865 pos += session->internals.dtls.cookie_len;
1868 /* Copy the ciphersuites.
1870 * If using SSLv3 Send TLS_RENEGO_PROTECTION_REQUEST SCSV for MITM
1871 * prevention on initial negotiation (but not renegotiation; that's
1872 * handled with the RI extension below).
1874 if (!session->internals.initial_negotiation_completed &&
1875 session->security_parameters.entity == GNUTLS_CLIENT &&
1876 (gnutls_protocol_get_version (session) == GNUTLS_SSL3 ||
1877 session->internals.priorities.no_extensions != 0))
1879 ret =
1880 _gnutls_copy_ciphersuites (session, &extdata, TRUE);
1881 _gnutls_extension_list_add (session,
1882 GNUTLS_EXTENSION_SAFE_RENEGOTIATION);
1884 else
1885 ret = _gnutls_copy_ciphersuites (session, &extdata, FALSE);
1887 if (ret < 0)
1889 gnutls_assert();
1890 goto cleanup;
1893 /* Copy the compression methods.
1895 ret = _gnutls_copy_comp_methods (session, &extdata);
1896 if (ret < 0)
1898 gnutls_assert();
1899 goto cleanup;
1902 /* Generate and copy TLS extensions.
1904 if (session->internals.priorities.no_extensions == 0)
1906 if (_gnutls_version_has_extensions (hver))
1907 type = GNUTLS_EXT_ANY;
1908 else
1910 if (session->internals.initial_negotiation_completed != 0)
1911 type = GNUTLS_EXT_MANDATORY;
1912 else
1913 type = GNUTLS_EXT_NONE;
1916 ret = _gnutls_gen_extensions (session, &extdata, type);
1917 if (ret < 0)
1919 gnutls_assert();
1920 goto cleanup;
1925 ret = _mbuffer_append_data (bufel, extdata.data, extdata.length);
1926 if (ret < 0)
1928 gnutls_assert ();
1929 goto cleanup;
1933 _gnutls_buffer_clear(&extdata);
1935 return
1936 _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_CLIENT_HELLO);
1938 cleanup:
1939 _mbuffer_xfree(&bufel);
1940 _gnutls_buffer_clear(&extdata);
1941 return ret;
1944 static int
1945 _gnutls_send_server_hello (gnutls_session_t session, int again)
1947 mbuffer_st *bufel = NULL;
1948 uint8_t *data = NULL;
1949 gnutls_buffer_st extdata;
1950 int pos = 0;
1951 int datalen, ret = 0;
1952 uint8_t comp;
1953 uint8_t session_id_len = session->security_parameters.session_id_size;
1954 char buf[2 * TLS_MAX_SESSION_ID_SIZE + 1];
1956 datalen = 0;
1958 _gnutls_buffer_init(&extdata);
1960 if (again == 0)
1962 datalen = 2 + session_id_len + 1 + GNUTLS_RANDOM_SIZE + 3;
1963 ret =
1964 _gnutls_gen_extensions (session, &extdata, GNUTLS_EXT_ANY);
1965 if (ret < 0)
1967 gnutls_assert ();
1968 goto fail;
1971 bufel = _gnutls_handshake_alloc (session, datalen + extdata.length, datalen + extdata.length);
1972 if (bufel == NULL)
1974 gnutls_assert ();
1975 ret = GNUTLS_E_MEMORY_ERROR;
1976 goto fail;
1978 data = _mbuffer_get_udata_ptr (bufel);
1980 data[pos++] =
1981 _gnutls_version_get_major (session->security_parameters.version);
1982 data[pos++] =
1983 _gnutls_version_get_minor (session->security_parameters.version);
1985 memcpy (&data[pos],
1986 session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
1987 pos += GNUTLS_RANDOM_SIZE;
1989 data[pos++] = session_id_len;
1990 if (session_id_len > 0)
1992 memcpy (&data[pos], session->security_parameters.session_id,
1993 session_id_len);
1995 pos += session_id_len;
1997 _gnutls_handshake_log ("HSK[%p]: SessionID: %s\n", session,
1998 _gnutls_bin2hex (session->security_parameters.
1999 session_id, session_id_len, buf,
2000 sizeof (buf), NULL));
2002 memcpy (&data[pos],
2003 session->security_parameters.cipher_suite, 2);
2004 pos += 2;
2006 comp = _gnutls_compression_get_num ( session->security_parameters.compression_method);
2007 data[pos++] = comp;
2009 if (extdata.length > 0)
2011 datalen += extdata.length;
2012 memcpy (&data[pos], extdata.data, extdata.length);
2016 ret =
2017 _gnutls_send_handshake (session, bufel, GNUTLS_HANDSHAKE_SERVER_HELLO);
2019 fail:
2020 _gnutls_buffer_clear(&extdata);
2021 return ret;
2025 _gnutls_send_hello (gnutls_session_t session, int again)
2027 int ret;
2029 if (session->security_parameters.entity == GNUTLS_CLIENT)
2031 ret = _gnutls_send_client_hello (session, again);
2034 else
2035 { /* SERVER */
2036 ret = _gnutls_send_server_hello (session, again);
2039 return ret;
2042 /* RECEIVE A HELLO MESSAGE. This should be called from gnutls_recv_handshake_int only if a
2043 * hello message is expected. It uses the security_parameters.cipher_suite
2044 * and internals.compression_method.
2047 _gnutls_recv_hello (gnutls_session_t session, uint8_t * data, int datalen)
2049 int ret;
2051 if (session->security_parameters.entity == GNUTLS_CLIENT)
2053 ret = _gnutls_read_server_hello (session, data, datalen);
2054 if (ret < 0)
2056 gnutls_assert ();
2057 return ret;
2060 else
2061 { /* Server side reading a client hello */
2063 ret = _gnutls_read_client_hello (session, data, datalen);
2064 if (ret < 0)
2066 gnutls_assert ();
2067 return ret;
2071 ret = _gnutls_ext_sr_verify (session);
2072 if (ret < 0)
2074 gnutls_assert ();
2075 return ret;
2078 return 0;
2081 static int
2082 _gnutls_recv_hello_verify_request (gnutls_session_t session,
2083 uint8_t * data, int datalen)
2085 ssize_t len = datalen;
2086 size_t pos = 0;
2087 uint8_t cookie_len;
2088 unsigned int nb_verifs;
2090 if (!IS_DTLS (session)
2091 || session->security_parameters.entity == GNUTLS_SERVER)
2093 gnutls_assert ();
2094 return GNUTLS_E_INTERNAL_ERROR;
2097 nb_verifs = ++session->internals.dtls.hsk_hello_verify_requests;
2098 if (nb_verifs >= MAX_HANDSHAKE_HELLO_VERIFY_REQUESTS)
2100 /* The server is either buggy, malicious or changing cookie
2101 secrets _way_ too fast. */
2102 gnutls_assert ();
2103 return GNUTLS_E_UNEXPECTED_PACKET;
2106 /* TODO: determine if we need to do anything with the server version field */
2107 DECR_LEN (len, 2);
2108 pos += 2;
2110 DECR_LEN (len, 1);
2111 cookie_len = data[pos];
2112 pos++;
2114 if (cookie_len > DTLS_MAX_COOKIE_SIZE)
2116 gnutls_assert ();
2117 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
2120 DECR_LEN (len, cookie_len);
2122 session->internals.dtls.cookie_len = cookie_len;
2123 memcpy (session->internals.dtls.cookie, &data[pos], cookie_len);
2125 pos += cookie_len;
2127 if (len != 0)
2129 gnutls_assert ();
2130 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
2133 /* reset handshake hash buffers */
2134 _gnutls_handshake_hash_buffer_empty (session);
2136 return 0;
2139 /* The packets in gnutls_handshake (it's more broad than original TLS handshake)
2141 * Client Server
2143 * ClientHello -------->
2144 * <-------- ServerHello
2146 * Certificate*
2147 * ServerKeyExchange*
2148 * <-------- CertificateRequest*
2150 * <-------- ServerHelloDone
2151 * Certificate*
2152 * ClientKeyExchange
2153 * CertificateVerify*
2154 * [ChangeCipherSpec]
2155 * Finished -------->
2156 * NewSessionTicket
2157 * [ChangeCipherSpec]
2158 * <-------- Finished
2160 * (*): means optional packet.
2163 /* Handshake when resumming session:
2164 * Client Server
2166 * ClientHello -------->
2167 * ServerHello
2168 * [ChangeCipherSpec]
2169 * <-------- Finished
2170 * [ChangeCipherSpec]
2171 * Finished -------->
2176 * gnutls_rehandshake:
2177 * @session: is a #gnutls_session_t structure.
2179 * This function will renegotiate security parameters with the
2180 * client. This should only be called in case of a server.
2182 * This message informs the peer that we want to renegotiate
2183 * parameters (perform a handshake).
2185 * If this function succeeds (returns 0), you must call the
2186 * gnutls_handshake() function in order to negotiate the new
2187 * parameters.
2189 * Since TLS is full duplex some application data might have been
2190 * sent during peer's processing of this message. In that case
2191 * one should call gnutls_record_recv() until GNUTLS_E_REHANDSHAKE
2192 * is returned to clear any pending data. Care must be taken if
2193 * rehandshake is mandatory to terminate if it does not start after
2194 * some threshold.
2196 * If the client does not wish to renegotiate parameters he will
2197 * should with an alert message, thus the return code will be
2198 * %GNUTLS_E_WARNING_ALERT_RECEIVED and the alert will be
2199 * %GNUTLS_A_NO_RENEGOTIATION. A client may also choose to ignore
2200 * this message.
2202 * Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code.
2205 gnutls_rehandshake (gnutls_session_t session)
2207 int ret;
2209 /* only server sends that handshake packet */
2210 if (session->security_parameters.entity == GNUTLS_CLIENT)
2211 return GNUTLS_E_INVALID_REQUEST;
2213 _dtls_async_timer_delete(session);
2215 ret =
2216 _gnutls_send_empty_handshake (session, GNUTLS_HANDSHAKE_HELLO_REQUEST,
2217 AGAIN (STATE50));
2218 STATE = STATE50;
2220 if (ret < 0)
2222 gnutls_assert ();
2223 return ret;
2225 STATE = STATE0;
2227 return 0;
2230 inline static int
2231 _gnutls_abort_handshake (gnutls_session_t session, int ret)
2233 if (((ret == GNUTLS_E_WARNING_ALERT_RECEIVED) &&
2234 (gnutls_alert_get (session) == GNUTLS_A_NO_RENEGOTIATION))
2235 || ret == GNUTLS_E_GOT_APPLICATION_DATA)
2236 return 0;
2238 /* this doesn't matter */
2239 return GNUTLS_E_INTERNAL_ERROR;
2244 static int
2245 _gnutls_send_supplemental (gnutls_session_t session, int again)
2247 mbuffer_st *bufel;
2248 int ret = 0;
2250 _gnutls_debug_log ("EXT[%p]: Sending supplemental data\n", session);
2252 if (again)
2253 ret =
2254 _gnutls_send_handshake (session, NULL, GNUTLS_HANDSHAKE_SUPPLEMENTAL);
2255 else
2257 gnutls_buffer_st buf;
2258 _gnutls_buffer_init (&buf);
2260 ret = _gnutls_gen_supplemental (session, &buf);
2261 if (ret < 0)
2263 gnutls_assert ();
2264 return ret;
2267 bufel = _gnutls_handshake_alloc(session, buf.length, buf.length);
2268 if (bufel == NULL)
2270 gnutls_assert ();
2271 return GNUTLS_E_MEMORY_ERROR;
2274 _mbuffer_set_udata (bufel, buf.data, buf.length);
2275 _gnutls_buffer_clear (&buf);
2277 ret = _gnutls_send_handshake (session, bufel,
2278 GNUTLS_HANDSHAKE_SUPPLEMENTAL);
2281 return ret;
2284 static int
2285 _gnutls_recv_supplemental (gnutls_session_t session)
2287 gnutls_buffer_st buf;
2288 int ret;
2290 _gnutls_debug_log ("EXT[%p]: Expecting supplemental data\n", session);
2292 ret = _gnutls_recv_handshake (session, GNUTLS_HANDSHAKE_SUPPLEMENTAL,
2293 1, &buf);
2294 if (ret < 0)
2296 gnutls_assert ();
2297 return ret;
2300 ret = _gnutls_parse_supplemental (session, buf.data, buf.length);
2301 if (ret < 0)
2303 gnutls_assert ();
2304 goto cleanup;
2307 cleanup:
2308 _gnutls_buffer_clear(&buf);
2310 return ret;
2314 * gnutls_handshake:
2315 * @session: is a #gnutls_session_t structure.
2317 * This function does the handshake of the TLS/SSL protocol, and
2318 * initializes the TLS connection.
2320 * This function will fail if any problem is encountered, and will
2321 * return a negative error code. In case of a client, if the client
2322 * has asked to resume a session, but the server couldn't, then a
2323 * full handshake will be performed.
2325 * The non-fatal errors such as %GNUTLS_E_AGAIN and
2326 * %GNUTLS_E_INTERRUPTED interrupt the handshake procedure, which
2327 * should be resumed later. Call this function again, until it
2328 * returns 0; cf. gnutls_record_get_direction() and
2329 * gnutls_error_is_fatal().
2331 * If this function is called by a server after a rehandshake request
2332 * then %GNUTLS_E_GOT_APPLICATION_DATA or
2333 * %GNUTLS_E_WARNING_ALERT_RECEIVED may be returned. Note that these
2334 * are non fatal errors, only in the specific case of a rehandshake.
2335 * Their meaning is that the client rejected the rehandshake request or
2336 * in the case of %GNUTLS_E_GOT_APPLICATION_DATA it might also mean that
2337 * some data were pending.
2339 * Returns: %GNUTLS_E_SUCCESS on success, otherwise a negative error code.
2342 gnutls_handshake (gnutls_session_t session)
2344 int ret;
2345 record_parameters_st *params;
2347 /* sanity check. Verify that there are priorities setup.
2349 if (session->internals.priorities.protocol.algorithms == 0)
2350 return gnutls_assert_val(GNUTLS_E_NO_PRIORITIES_WERE_SET);
2352 ret = _gnutls_epoch_get (session, session->security_parameters.epoch_next,
2353 &params);
2354 if (ret < 0)
2356 /* We assume the epoch is not allocated if _gnutls_epoch_get fails. */
2357 ret =
2358 _gnutls_epoch_alloc (session, session->security_parameters.epoch_next,
2359 NULL);
2360 if (ret < 0)
2361 return gnutls_assert_val(ret);
2364 if (session->security_parameters.entity == GNUTLS_CLIENT)
2368 ret = _gnutls_handshake_client (session);
2369 } while (ret == 1);
2371 else
2373 ret = _gnutls_handshake_server (session);
2375 if (ret < 0)
2377 /* In the case of a rehandshake abort
2378 * we should reset the handshake's internal state.
2380 if (_gnutls_abort_handshake (session, ret) == 0)
2381 STATE = STATE0;
2383 return ret;
2386 ret = _gnutls_handshake_common (session);
2388 if (ret < 0)
2390 if (_gnutls_abort_handshake (session, ret) == 0)
2391 STATE = STATE0;
2393 return ret;
2396 STATE = STATE0;
2398 if (IS_DTLS(session)==0)
2400 _gnutls_handshake_io_buffer_clear (session);
2402 else
2404 _dtls_async_timer_init(session);
2407 _gnutls_handshake_internal_state_clear (session);
2409 session->security_parameters.epoch_next++;
2411 return 0;
2415 #define IMED_RET( str, ret, allow_alert) do { \
2416 if (ret < 0) { \
2417 /* EAGAIN and INTERRUPTED are always non-fatal */ \
2418 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED) \
2419 return ret; \
2420 /* a warning alert might interrupt handshake */ \
2421 if (allow_alert != 0 && ret==GNUTLS_E_WARNING_ALERT_RECEIVED) return ret; \
2422 gnutls_assert(); \
2423 ERR( str, ret); \
2424 _gnutls_handshake_hash_buffers_clear(session); \
2425 return ret; \
2426 } } while (0)
2431 * _gnutls_handshake_client
2432 * This function performs the client side of the handshake of the TLS/SSL protocol.
2435 _gnutls_handshake_client (gnutls_session_t session)
2437 int ret = 0;
2439 #ifdef HANDSHAKE_DEBUG
2440 char buf[64];
2442 if (session->internals.resumed_security_parameters.session_id_size > 0)
2443 _gnutls_handshake_log ("HSK[%p]: Ask to resume: %s\n", session,
2444 _gnutls_bin2hex (session->
2445 internals.resumed_security_parameters.session_id,
2446 session->
2447 internals.resumed_security_parameters.session_id_size,
2448 buf, sizeof (buf), NULL));
2449 #endif
2451 switch (STATE)
2453 case STATE0:
2454 case STATE1:
2455 ret = _gnutls_send_hello (session, AGAIN (STATE1));
2456 STATE = STATE1;
2457 IMED_RET ("send hello", ret, 1);
2459 case STATE11:
2460 if (IS_DTLS (session))
2462 ret =
2463 _gnutls_recv_handshake (session,
2464 GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST,
2465 1, NULL);
2466 STATE = STATE11;
2467 IMED_RET ("recv hello verify", ret, 1);
2469 if (ret == 1)
2471 STATE = STATE0;
2472 return 1;
2475 case STATE2:
2476 /* receive the server hello */
2477 ret =
2478 _gnutls_recv_handshake (session,
2479 GNUTLS_HANDSHAKE_SERVER_HELLO,
2480 0, NULL);
2481 STATE = STATE2;
2482 IMED_RET ("recv hello", ret, 1);
2484 case STATE70:
2485 if (session->security_parameters.do_recv_supplemental)
2487 ret = _gnutls_recv_supplemental (session);
2488 STATE = STATE70;
2489 IMED_RET ("recv supplemental", ret, 1);
2492 case STATE3:
2493 /* RECV CERTIFICATE */
2494 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2495 ret = _gnutls_recv_server_certificate (session);
2496 STATE = STATE3;
2497 IMED_RET ("recv server certificate", ret, 1);
2499 case STATE4:
2500 /* receive the server key exchange */
2501 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2502 ret = _gnutls_recv_server_kx_message (session);
2503 STATE = STATE4;
2504 IMED_RET ("recv server kx message", ret, 1);
2506 case STATE5:
2507 /* receive the server certificate request - if any
2510 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2511 ret = _gnutls_recv_server_certificate_request (session);
2512 STATE = STATE5;
2513 IMED_RET ("recv server certificate request message", ret, 1);
2515 case STATE6:
2516 /* receive the server hello done */
2517 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2518 ret =
2519 _gnutls_recv_handshake (session,
2520 GNUTLS_HANDSHAKE_SERVER_HELLO_DONE,
2521 0, NULL);
2522 STATE = STATE6;
2523 IMED_RET ("recv server hello done", ret, 1);
2524 case STATE71:
2525 if (session->security_parameters.do_send_supplemental)
2527 ret = _gnutls_send_supplemental (session, AGAIN (STATE71));
2528 STATE = STATE71;
2529 IMED_RET ("send supplemental", ret, 0);
2532 case STATE7:
2533 /* send our certificate - if any and if requested
2535 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2536 ret = _gnutls_send_client_certificate (session, AGAIN (STATE7));
2537 STATE = STATE7;
2538 IMED_RET ("send client certificate", ret, 0);
2540 case STATE8:
2541 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2542 ret = _gnutls_send_client_kx_message (session, AGAIN (STATE8));
2543 STATE = STATE8;
2544 IMED_RET ("send client kx", ret, 0);
2546 case STATE9:
2547 /* send client certificate verify */
2548 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2549 ret =
2550 _gnutls_send_client_certificate_verify (session, AGAIN (STATE9));
2551 STATE = STATE9;
2552 IMED_RET ("send client certificate verify", ret, 1);
2554 STATE = STATE0;
2555 default:
2556 break;
2560 return 0;
2565 /* This function is to be called if the handshake was successfully
2566 * completed. This sends a Change Cipher Spec packet to the peer.
2568 static ssize_t
2569 send_change_cipher_spec (gnutls_session_t session, int again)
2571 uint8_t* data;
2572 mbuffer_st * bufel;
2573 int ret;
2575 if (again == 0)
2577 bufel = _gnutls_handshake_alloc (session, 1, 1);
2578 if (bufel == NULL)
2579 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
2581 _mbuffer_set_uhead_size(bufel, 1);
2582 _mbuffer_set_udata_size(bufel, 0);
2584 data = _mbuffer_get_uhead_ptr (bufel);
2586 data[0] = 1;
2588 ret = _gnutls_handshake_io_cache_int (session, GNUTLS_HANDSHAKE_CHANGE_CIPHER_SPEC, bufel);
2589 if (ret < 0)
2591 _mbuffer_xfree(&bufel);
2592 return gnutls_assert_val(ret);
2595 _gnutls_handshake_log ("REC[%p]: Sent ChangeCipherSpec\n", session);
2598 return 0;
2601 /* This function sends the final handshake packets and initializes connection
2603 static int
2604 _gnutls_send_handshake_final (gnutls_session_t session, int init)
2606 int ret = 0;
2608 /* Send the CHANGE CIPHER SPEC PACKET */
2610 switch (STATE)
2612 case STATE0:
2613 case STATE20:
2614 ret = send_change_cipher_spec (session, AGAIN (STATE20));
2615 STATE = STATE0;
2617 if (ret < 0)
2619 ERR ("send ChangeCipherSpec", ret);
2620 gnutls_assert ();
2621 return ret;
2623 /* Initialize the connection session (start encryption) - in case of client
2625 if (init == TRUE)
2627 ret = _gnutls_connection_state_init (session);
2628 if (ret < 0)
2630 gnutls_assert ();
2631 return ret;
2635 ret = _gnutls_write_connection_state_init (session);
2636 if (ret < 0)
2638 gnutls_assert ();
2639 return ret;
2642 case STATE21:
2643 /* send the finished message */
2644 ret = _gnutls_send_finished (session, AGAIN (STATE21));
2645 STATE = STATE21;
2646 if (ret < 0)
2648 ERR ("send Finished", ret);
2649 gnutls_assert ();
2650 return ret;
2653 STATE = STATE0;
2654 default:
2655 break;
2658 return 0;
2661 /* This function receives the final handshake packets
2662 * And executes the appropriate function to initialize the
2663 * read session.
2665 static int
2666 _gnutls_recv_handshake_final (gnutls_session_t session, int init)
2668 int ret = 0;
2669 uint8_t ch;
2672 switch (STATE)
2674 case STATE0:
2675 case STATE30:
2676 STATE = STATE30;
2678 /* This is the last flight and peer cannot be sure
2679 * we have received it unless we notify him. So we
2680 * wait for a message and retransmit if needed. */
2681 if (IS_DTLS(session) && !_dtls_is_async(session) &&
2682 gnutls_record_check_pending (session) == 0)
2684 ret = _dtls_wait_and_retransmit(session);
2685 if (ret < 0)
2686 return gnutls_assert_val(ret);
2689 ret = _gnutls_recv_int (session, GNUTLS_CHANGE_CIPHER_SPEC, -1, &ch, 1, NULL);
2690 if (ret <= 0)
2692 ERR ("recv ChangeCipherSpec", ret);
2693 gnutls_assert ();
2694 return (ret < 0) ? ret : GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
2697 /* Initialize the connection session (start encryption) - in case of server */
2698 if (init == TRUE)
2700 ret = _gnutls_connection_state_init (session);
2701 if (ret < 0)
2703 gnutls_assert ();
2704 return ret;
2708 ret = _gnutls_read_connection_state_init (session);
2709 if (ret < 0)
2711 gnutls_assert ();
2712 return ret;
2715 case STATE31:
2716 STATE = STATE31;
2718 if (IS_DTLS(session) && !_dtls_is_async(session) &&
2719 gnutls_record_check_pending( session) == 0)
2721 ret = _dtls_wait_and_retransmit(session);
2722 if (ret < 0)
2723 return gnutls_assert_val(ret);
2726 ret = _gnutls_recv_finished (session);
2727 if (ret < 0)
2729 ERR ("recv finished", ret);
2730 gnutls_assert ();
2731 return ret;
2733 STATE = STATE0;
2734 default:
2735 break;
2739 return 0;
2743 * _gnutls_handshake_server
2744 * This function does the server stuff of the handshake protocol.
2747 _gnutls_handshake_server (gnutls_session_t session)
2749 int ret = 0;
2751 switch (STATE)
2753 case STATE0:
2754 case STATE1:
2755 ret =
2756 _gnutls_recv_handshake (session,
2757 GNUTLS_HANDSHAKE_CLIENT_HELLO,
2758 0, NULL);
2759 STATE = STATE1;
2760 IMED_RET ("recv hello", ret, 1);
2762 case STATE2:
2763 ret = _gnutls_send_hello (session, AGAIN (STATE2));
2764 STATE = STATE2;
2765 IMED_RET ("send hello", ret, 1);
2767 case STATE70:
2768 if (session->security_parameters.do_send_supplemental)
2770 ret = _gnutls_send_supplemental (session, AGAIN (STATE70));
2771 STATE = STATE70;
2772 IMED_RET ("send supplemental data", ret, 0);
2775 /* SEND CERTIFICATE + KEYEXCHANGE + CERTIFICATE_REQUEST */
2776 case STATE3:
2777 /* NOTE: these should not be send if we are resuming */
2779 if (session->internals.resumed == RESUME_FALSE)
2780 ret = _gnutls_send_server_certificate (session, AGAIN (STATE3));
2781 STATE = STATE3;
2782 IMED_RET ("send server certificate", ret, 0);
2784 case STATE4:
2785 /* send server key exchange (A) */
2786 if (session->internals.resumed == RESUME_FALSE)
2787 ret = _gnutls_send_server_kx_message (session, AGAIN (STATE4));
2788 STATE = STATE4;
2789 IMED_RET ("send server kx", ret, 0);
2791 case STATE5:
2792 /* Send certificate request - if requested to */
2793 if (session->internals.resumed == RESUME_FALSE)
2794 ret =
2795 _gnutls_send_server_certificate_request (session, AGAIN (STATE5));
2796 STATE = STATE5;
2797 IMED_RET ("send server cert request", ret, 0);
2799 case STATE6:
2800 /* send the server hello done */
2801 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2802 ret =
2803 _gnutls_send_empty_handshake (session,
2804 GNUTLS_HANDSHAKE_SERVER_HELLO_DONE,
2805 AGAIN (STATE6));
2806 STATE = STATE6;
2807 IMED_RET ("send server hello done", ret, 1);
2809 case STATE71:
2810 if (session->security_parameters.do_recv_supplemental)
2812 ret = _gnutls_recv_supplemental (session);
2813 STATE = STATE71;
2814 IMED_RET ("recv client supplemental", ret, 1);
2817 /* RECV CERTIFICATE + KEYEXCHANGE + CERTIFICATE_VERIFY */
2818 case STATE7:
2819 /* receive the client certificate message */
2820 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2821 ret = _gnutls_recv_client_certificate (session);
2822 STATE = STATE7;
2823 IMED_RET ("recv client certificate", ret, 1);
2825 case STATE8:
2826 /* receive the client key exchange message */
2827 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2828 ret = _gnutls_recv_client_kx_message (session);
2829 STATE = STATE8;
2830 IMED_RET ("recv client kx", ret, 1);
2832 case STATE9:
2833 /* receive the client certificate verify message */
2834 if (session->internals.resumed == RESUME_FALSE) /* if we are not resuming */
2835 ret = _gnutls_recv_client_certificate_verify_message (session);
2836 STATE = STATE9;
2837 IMED_RET ("recv client certificate verify", ret, 1);
2839 STATE = STATE0; /* finished thus clear session */
2840 default:
2841 break;
2844 return 0;
2848 _gnutls_handshake_common (gnutls_session_t session)
2850 int ret = 0;
2852 /* send and recv the change cipher spec and finished messages */
2853 if ((session->internals.resumed != RESUME_FALSE
2854 && session->security_parameters.entity == GNUTLS_CLIENT)
2855 || (session->internals.resumed == RESUME_FALSE
2856 && session->security_parameters.entity == GNUTLS_SERVER))
2858 /* if we are a client resuming - or we are a server not resuming */
2859 ret = _gnutls_recv_handshake_final (session, TRUE);
2860 IMED_RET ("recv handshake final", ret, 1);
2862 switch (STATE)
2864 case STATE0:
2865 case STATE40:
2866 ret = _gnutls_send_new_session_ticket (session, AGAIN (STATE40));
2867 STATE = STATE40;
2868 IMED_RET ("send handshake new session ticket", ret, 0);
2869 STATE = STATE0;
2870 default:
2871 break;
2874 ret = _gnutls_send_handshake_final (session, FALSE);
2875 IMED_RET ("send handshake final", ret, 1);
2877 /* only store if we are not resuming a session and we didn't previously send a ticket
2879 if (session->security_parameters.entity == GNUTLS_SERVER && session->internals.ticket_sent == 0)
2881 /* in order to support session resuming */
2882 _gnutls_server_register_current_session (session);
2885 else
2886 { /* if we are a client not resuming - or we are a server resuming */
2888 ret = _gnutls_send_handshake_final (session, TRUE);
2889 IMED_RET ("send handshake final 2", ret, 1);
2891 switch (STATE)
2893 case STATE0:
2894 case STATE41:
2895 ret = _gnutls_recv_new_session_ticket (session);
2896 STATE = STATE41;
2897 IMED_RET ("recv handshake new session ticket", ret, 1);
2898 STATE = STATE0;
2899 default:
2900 break;
2903 ret = _gnutls_recv_handshake_final (session, FALSE);
2904 IMED_RET ("recv handshake final 2", ret, 1);
2909 /* clear handshake buffer */
2910 _gnutls_handshake_hash_buffers_clear (session);
2911 return ret;
2916 _gnutls_generate_session_id (uint8_t * session_id, uint8_t * len)
2918 int ret;
2920 *len = TLS_MAX_SESSION_ID_SIZE;
2922 ret = _gnutls_rnd (GNUTLS_RND_NONCE, session_id, *len);
2923 if (ret < 0)
2925 gnutls_assert ();
2926 return ret;
2929 return 0;
2933 _gnutls_recv_hello_request (gnutls_session_t session, void *data,
2934 uint32_t data_size)
2936 uint8_t type;
2938 if (session->security_parameters.entity == GNUTLS_SERVER)
2940 gnutls_assert ();
2941 return GNUTLS_E_UNEXPECTED_PACKET;
2943 if (data_size < 1)
2945 gnutls_assert ();
2946 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
2948 type = ((uint8_t *) data)[0];
2949 if (type == GNUTLS_HANDSHAKE_HELLO_REQUEST)
2951 if (IS_DTLS(session))
2952 session->internals.dtls.hsk_read_seq++;
2953 return GNUTLS_E_REHANDSHAKE;
2955 else
2957 gnutls_assert ();
2958 return GNUTLS_E_UNEXPECTED_PACKET;
2962 /* Returns 1 if the given KX has not the corresponding parameters
2963 * (DH or RSA) set up. Otherwise returns 0.
2965 inline static int
2966 check_server_params (gnutls_session_t session,
2967 gnutls_kx_algorithm_t kx,
2968 gnutls_kx_algorithm_t * alg, int alg_size)
2970 int cred_type;
2971 gnutls_dh_params_t dh_params = NULL;
2972 gnutls_rsa_params_t rsa_params = NULL;
2973 int j;
2975 cred_type = _gnutls_map_kx_get_cred (kx, 1);
2977 /* Read the Diffie-Hellman parameters, if any.
2979 if (cred_type == GNUTLS_CRD_CERTIFICATE)
2981 int delete;
2982 gnutls_certificate_credentials_t x509_cred =
2983 (gnutls_certificate_credentials_t) _gnutls_get_cred (session->key,
2984 cred_type, NULL);
2986 if (x509_cred != NULL)
2988 dh_params =
2989 _gnutls_get_dh_params (x509_cred->dh_params,
2990 x509_cred->params_func, session);
2991 rsa_params =
2992 _gnutls_certificate_get_rsa_params (x509_cred->rsa_params,
2993 x509_cred->params_func,
2994 session);
2997 /* Check also if the certificate supports the
2998 * KX method.
3000 delete = 1;
3001 for (j = 0; j < alg_size; j++)
3003 if (alg[j] == kx)
3005 delete = 0;
3006 break;
3010 if (delete == 1)
3011 return 1;
3013 #ifdef ENABLE_ANON
3015 else if (cred_type == GNUTLS_CRD_ANON)
3017 gnutls_anon_server_credentials_t anon_cred =
3018 (gnutls_anon_server_credentials_t) _gnutls_get_cred (session->key,
3019 cred_type, NULL);
3021 if (anon_cred != NULL)
3023 dh_params =
3024 _gnutls_get_dh_params (anon_cred->dh_params,
3025 anon_cred->params_func, session);
3027 #endif
3028 #ifdef ENABLE_PSK
3030 else if (cred_type == GNUTLS_CRD_PSK)
3032 gnutls_psk_server_credentials_t psk_cred =
3033 (gnutls_psk_server_credentials_t) _gnutls_get_cred (session->key,
3034 cred_type, NULL);
3036 if (psk_cred != NULL)
3038 dh_params =
3039 _gnutls_get_dh_params (psk_cred->dh_params, psk_cred->params_func,
3040 session);
3042 #endif
3044 else
3045 return 0; /* no need for params */
3048 /* If the key exchange method needs RSA or DH params,
3049 * but they are not set then remove it.
3051 if (_gnutls_kx_needs_rsa_params (kx) != 0)
3053 /* needs rsa params. */
3054 if (_gnutls_rsa_params_to_mpi (rsa_params) == NULL)
3056 gnutls_assert ();
3057 return 1;
3061 if (_gnutls_kx_needs_dh_params (kx) != 0)
3063 /* needs DH params. */
3064 if (_gnutls_dh_params_to_mpi (dh_params) == NULL)
3066 gnutls_assert ();
3067 return 1;
3071 return 0;
3074 /* This function will remove algorithms that are not supported by
3075 * the requested authentication method. We remove an algorithm if
3076 * we have a certificate with keyUsage bits set.
3078 * This does a more high level check than gnutls_supported_ciphersuites(),
3079 * by checking certificates etc.
3081 static int
3082 _gnutls_remove_unwanted_ciphersuites (gnutls_session_t session,
3083 uint8_t * cipher_suites,
3084 int cipher_suites_size,
3085 gnutls_pk_algorithm_t *pk_algos,
3086 size_t pk_algos_size)
3089 int ret = 0;
3090 int i, new_suites_size;
3091 gnutls_certificate_credentials_t cert_cred;
3092 gnutls_kx_algorithm_t kx;
3093 int server = session->security_parameters.entity == GNUTLS_SERVER ? 1 : 0;
3094 gnutls_kx_algorithm_t alg[MAX_ALGOS];
3095 int alg_size = MAX_ALGOS;
3097 /* if we should use a specific certificate,
3098 * we should remove all algorithms that are not supported
3099 * by that certificate and are on the same authentication
3100 * method (CERTIFICATE).
3103 cert_cred =
3104 (gnutls_certificate_credentials_t) _gnutls_get_cred (session->key,
3105 GNUTLS_CRD_CERTIFICATE,
3106 NULL);
3108 /* If there are certificate credentials, find an appropriate certificate
3109 * or disable them;
3111 if (session->security_parameters.entity == GNUTLS_SERVER
3112 && cert_cred != NULL && pk_algos_size > 0)
3114 ret = _gnutls_server_select_cert (session, pk_algos, pk_algos_size);
3115 if (ret < 0)
3117 gnutls_assert ();
3118 _gnutls_debug_log ("Could not find an appropriate certificate: %s\n",
3119 gnutls_strerror (ret));
3123 /* get all the key exchange algorithms that are
3124 * supported by the X509 certificate parameters.
3126 if ((ret =
3127 _gnutls_selected_cert_supported_kx (session, alg, &alg_size)) < 0)
3129 gnutls_assert ();
3130 return ret;
3133 new_suites_size = 0;
3135 /* now removes ciphersuites based on the KX algorithm
3137 for (i = 0; i < cipher_suites_size; i+=2)
3139 int delete = 0;
3141 /* finds the key exchange algorithm in
3142 * the ciphersuite
3144 kx = _gnutls_cipher_suite_get_kx_algo (&cipher_suites[i]);
3146 /* if it is defined but had no credentials
3148 if (_gnutls_get_kx_cred (session, kx, NULL) == NULL)
3150 delete = 1;
3152 else
3154 delete = 0;
3156 if (server)
3157 delete = check_server_params (session, kx, alg, alg_size);
3160 /* If we have not agreed to a common curve with the peer don't bother
3161 * negotiating ECDH.
3163 if (server != 0 && _gnutls_kx_is_ecc(kx))
3165 if (_gnutls_session_ecc_curve_get(session) == GNUTLS_ECC_CURVE_INVALID)
3167 delete = 1;
3171 /* These two SRP kx's are marked to require a CRD_CERTIFICATE,
3172 (see cred_mappings in gnutls_algorithms.c), but it also
3173 requires a SRP credential. Don't use SRP kx unless we have a
3174 SRP credential too. */
3175 if (kx == GNUTLS_KX_SRP_RSA || kx == GNUTLS_KX_SRP_DSS)
3177 if (!_gnutls_get_cred (session->key, GNUTLS_CRD_SRP, NULL))
3179 delete = 1;
3183 if (delete == 0)
3186 _gnutls_handshake_log ("HSK[%p]: Keeping ciphersuite: %s\n",
3187 session,
3188 _gnutls_cipher_suite_get_name (&cipher_suites[i]));
3190 if (i != new_suites_size)
3191 memmove( &cipher_suites[new_suites_size], &cipher_suites[i], 2);
3192 new_suites_size+=2;
3194 else
3196 _gnutls_handshake_log ("HSK[%p]: Removing ciphersuite: %s\n",
3197 session,
3198 _gnutls_cipher_suite_get_name (&cipher_suites[i]));
3203 ret = new_suites_size;
3205 return ret;
3210 * gnutls_handshake_set_max_packet_length:
3211 * @session: is a #gnutls_session_t structure.
3212 * @max: is the maximum number.
3214 * This function will set the maximum size of all handshake messages.
3215 * Handshakes over this size are rejected with
3216 * %GNUTLS_E_HANDSHAKE_TOO_LARGE error code. The default value is
3217 * 48kb which is typically large enough. Set this to 0 if you do not
3218 * want to set an upper limit.
3220 * The reason for restricting the handshake message sizes are to
3221 * limit Denial of Service attacks.
3223 void
3224 gnutls_handshake_set_max_packet_length (gnutls_session_t session, size_t max)
3226 session->internals.max_handshake_data_buffer_size = max;
3229 void
3230 _gnutls_set_adv_version (gnutls_session_t session, gnutls_protocol_t ver)
3232 set_adv_version (session, _gnutls_version_get_major (ver),
3233 _gnutls_version_get_minor (ver));
3236 gnutls_protocol_t
3237 _gnutls_get_adv_version (gnutls_session_t session)
3239 return _gnutls_version_get (_gnutls_get_adv_version_major (session),
3240 _gnutls_get_adv_version_minor (session));
3244 * gnutls_handshake_get_last_in:
3245 * @session: is a #gnutls_session_t structure.
3247 * This function is only useful to check where the last performed
3248 * handshake failed. If the previous handshake succeed or was not
3249 * performed at all then no meaningful value will be returned.
3251 * Check %gnutls_handshake_description_t in gnutls.h for the
3252 * available handshake descriptions.
3254 * Returns: the last handshake message type received, a
3255 * %gnutls_handshake_description_t.
3257 gnutls_handshake_description_t
3258 gnutls_handshake_get_last_in (gnutls_session_t session)
3260 return session->internals.last_handshake_in;
3264 * gnutls_handshake_get_last_out:
3265 * @session: is a #gnutls_session_t structure.
3267 * This function is only useful to check where the last performed
3268 * handshake failed. If the previous handshake succeed or was not
3269 * performed at all then no meaningful value will be returned.
3271 * Check %gnutls_handshake_description_t in gnutls.h for the
3272 * available handshake descriptions.
3274 * Returns: the last handshake message type sent, a
3275 * %gnutls_handshake_description_t.
3277 gnutls_handshake_description_t
3278 gnutls_handshake_get_last_out (gnutls_session_t session)
3280 return session->internals.last_handshake_out;