Merge branch 'upstream' into tizen
[platform/upstream/gnutls.git] / lib / gnutls_state.c
1 /*
2  * Copyright (C) 2002-2015 Free Software Foundation, Inc.
3  * Copyright (C) 2014-2015 Nikos Mavrogiannopoulos
4  *
5  * Author: Nikos Mavrogiannopoulos
6  *
7  * This file is part of GnuTLS.
8  *
9  * The GnuTLS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1 of
12  * the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>
21  *
22  */
23
24 /* Functions to manipulate the session (gnutls_int.h), and some other stuff
25  * are included here. The file's name is traditionally gnutls_state even if the
26  * state has been renamed to session.
27  */
28
29 #include <gnutls_int.h>
30 #include <gnutls_errors.h>
31 #include <gnutls_auth.h>
32 #include <gnutls_num.h>
33 #include <gnutls_datum.h>
34 #include <gnutls_db.h>
35 #include <gnutls_record.h>
36 #include <gnutls_handshake.h>
37 #include <gnutls_dh.h>
38 #include <gnutls_buffers.h>
39 #include <gnutls_mbuffers.h>
40 #include <gnutls_state.h>
41 #include <gnutls_constate.h>
42 #include <auth/cert.h>
43 #include <auth/anon.h>
44 #include <auth/psk.h>
45 #include <algorithms.h>
46 #include <gnutls_extensions.h>
47 #include <system.h>
48 #include <random.h>
49 #include <fips.h>
50 #include <intprops.h>
51 #include <gnutls/dtls.h>
52 #include "gnutls_dtls.h"
53
54 /* These should really be static, but src/tests.c calls them.  Make
55    them public functions?  */
56 void
57 _gnutls_rsa_pms_set_version(gnutls_session_t session,
58                             unsigned char major, unsigned char minor);
59
60 void
61 _gnutls_session_cert_type_set(gnutls_session_t session,
62                               gnutls_certificate_type_t ct)
63 {
64         _gnutls_handshake_log
65             ("HSK[%p]: Selected certificate type %s (%d)\n", session,
66              gnutls_certificate_type_get_name(ct), ct);
67         session->security_parameters.cert_type = ct;
68 }
69
70 void
71 _gnutls_session_ecc_curve_set(gnutls_session_t session,
72                               gnutls_ecc_curve_t c)
73 {
74         _gnutls_handshake_log("HSK[%p]: Selected ECC curve %s (%d)\n",
75                               session, gnutls_ecc_curve_get_name(c), c);
76         session->security_parameters.ecc_curve = c;
77 }
78
79 /**
80  * gnutls_cipher_get:
81  * @session: is a #gnutls_session_t type.
82  *
83  * Get currently used cipher.
84  *
85  * Returns: the currently used cipher, a #gnutls_cipher_algorithm_t
86  *   type.
87  **/
88 gnutls_cipher_algorithm_t gnutls_cipher_get(gnutls_session_t session)
89 {
90         record_parameters_st *record_params;
91         int ret;
92
93         ret =
94             _gnutls_epoch_get(session, EPOCH_READ_CURRENT, &record_params);
95         if (ret < 0)
96                 return gnutls_assert_val(GNUTLS_CIPHER_NULL);
97
98         return record_params->cipher->id;
99 }
100
101 /**
102  * gnutls_certificate_type_get:
103  * @session: is a #gnutls_session_t type.
104  *
105  * The certificate type is by default X.509, unless it is negotiated
106  * as a TLS extension.
107  *
108  * Returns: the currently used #gnutls_certificate_type_t certificate
109  *   type.
110  **/
111 gnutls_certificate_type_t
112 gnutls_certificate_type_get(gnutls_session_t session)
113 {
114         return session->security_parameters.cert_type;
115 }
116
117 /**
118  * gnutls_kx_get:
119  * @session: is a #gnutls_session_t type.
120  *
121  * Get currently used key exchange algorithm.
122  *
123  * Returns: the key exchange algorithm used in the last handshake, a
124  *   #gnutls_kx_algorithm_t value.
125  **/
126 gnutls_kx_algorithm_t gnutls_kx_get(gnutls_session_t session)
127 {
128         return session->security_parameters.kx_algorithm;
129 }
130
131 /**
132  * gnutls_mac_get:
133  * @session: is a #gnutls_session_t type.
134  *
135  * Get currently used MAC algorithm.
136  *
137  * Returns: the currently used mac algorithm, a
138  *   #gnutls_mac_algorithm_t value.
139  **/
140 gnutls_mac_algorithm_t gnutls_mac_get(gnutls_session_t session)
141 {
142         record_parameters_st *record_params;
143         int ret;
144
145         ret =
146             _gnutls_epoch_get(session, EPOCH_READ_CURRENT, &record_params);
147         if (ret < 0)
148                 return gnutls_assert_val(GNUTLS_MAC_NULL);
149
150         return record_params->mac->id;
151 }
152
153 /**
154  * gnutls_compression_get:
155  * @session: is a #gnutls_session_t type.
156  *
157  * Get currently used compression algorithm.
158  *
159  * Returns: the currently used compression method, a
160  *   #gnutls_compression_method_t value.
161  **/
162 gnutls_compression_method_t
163 gnutls_compression_get(gnutls_session_t session)
164 {
165         record_parameters_st *record_params;
166         int ret;
167
168         ret =
169             _gnutls_epoch_get(session, EPOCH_READ_CURRENT, &record_params);
170         if (ret < 0)
171                 return gnutls_assert_val(GNUTLS_COMP_NULL);
172
173         return record_params->compression_algorithm;
174 }
175
176 /* Check if the given certificate type is supported.
177  * This means that it is enabled by the priority functions,
178  * and a matching certificate exists.
179  */
180 int
181 _gnutls_session_cert_type_supported(gnutls_session_t session,
182                                     gnutls_certificate_type_t cert_type)
183 {
184         unsigned i;
185         unsigned cert_found = 0;
186         gnutls_certificate_credentials_t cred;
187
188         if (session->security_parameters.entity == GNUTLS_SERVER) {
189                 cred = (gnutls_certificate_credentials_t)
190                     _gnutls_get_cred(session, GNUTLS_CRD_CERTIFICATE);
191
192                 if (cred == NULL)
193                         return GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE;
194
195                 if (cred->get_cert_callback == NULL && cred->get_cert_callback2 == NULL) {
196                         for (i = 0; i < cred->ncerts; i++) {
197                                 if (cred->certs[i].cert_list[0].type ==
198                                     cert_type) {
199                                         cert_found = 1;
200                                         break;
201                                 }
202                         }
203
204                         if (cert_found == 0)
205                                 /* no certificate is of that type.
206                                  */
207                                 return
208                                     GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE;
209                 }
210         }
211
212         if (session->internals.priorities.cert_type.algorithms == 0
213             && cert_type == DEFAULT_CERT_TYPE)
214                 return 0;
215
216         for (i = 0; i < session->internals.priorities.cert_type.algorithms;
217              i++) {
218                 if (session->internals.priorities.cert_type.priority[i] ==
219                     cert_type) {
220                         return 0;       /* ok */
221                 }
222         }
223
224         return GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE;
225 }
226
227
228 /* this function deinitializes all the internal parameters stored
229  * in a session struct.
230  */
231 inline static void deinit_internal_params(gnutls_session_t session)
232 {
233 #if defined(ENABLE_DHE) || defined(ENABLE_ANON)
234         if (session->internals.params.free_dh_params)
235                 gnutls_dh_params_deinit(session->internals.params.
236                                         dh_params);
237 #endif
238
239         _gnutls_handshake_hash_buffers_clear(session);
240
241         memset(&session->internals.params, 0,
242                sizeof(session->internals.params));
243 }
244
245 /* This function will clear all the variables in internals
246  * structure within the session, which depend on the current handshake.
247  * This is used to allow further handshakes.
248  */
249 static void _gnutls_handshake_internal_state_init(gnutls_session_t session)
250 {
251         session->internals.extensions_sent_size = 0;
252
253         /* by default no selected certificate */
254         session->internals.adv_version_major = 0;
255         session->internals.adv_version_minor = 0;
256         session->internals.direction = 0;
257
258         /* use out of band data for the last
259          * handshake messages received.
260          */
261         session->internals.last_handshake_in = -1;
262         session->internals.last_handshake_out = -1;
263
264         session->internals.resumable = RESUME_TRUE;
265
266         session->internals.handshake_large_loops = 0;
267         session->internals.dtls.hsk_read_seq = 0;
268         session->internals.dtls.hsk_write_seq = 0;
269 }
270
271 void _gnutls_handshake_internal_state_clear(gnutls_session_t session)
272 {
273         _gnutls_handshake_internal_state_init(session);
274
275         deinit_internal_params(session);
276
277         _gnutls_epoch_gc(session);
278
279         session->internals.handshake_endtime = 0;
280         session->internals.handshake_in_progress = 0;
281 }
282
283 /**
284  * gnutls_init:
285  * @session: is a pointer to a #gnutls_session_t type.
286  * @flags: indicate if this session is to be used for server or client.
287  *
288  * This function initializes the current session to null. Every
289  * session must be initialized before use, so internal structures can
290  * be allocated.  This function allocates structures which can only
291  * be free'd by calling gnutls_deinit().  Returns %GNUTLS_E_SUCCESS (0) on success.
292  *
293  * @flags can be one of %GNUTLS_CLIENT, %GNUTLS_SERVER, %GNUTLS_DATAGRAM,
294  * %GNUTLS_NONBLOCK or %GNUTLS_NOSIGNAL (since 3.4.2).
295  *
296  * The flag %GNUTLS_NO_REPLAY_PROTECTION will disable any 
297  * replay protection in DTLS mode. That must only used when 
298  * replay protection is achieved using other means.
299  *
300  * Note that since version 3.1.2 this function enables some common
301  * TLS extensions such as session tickets and OCSP certificate status
302  * request in client side by default. To prevent that use the %GNUTLS_NO_EXTENSIONS
303  * flag.
304  *
305  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
306  **/
307 int gnutls_init(gnutls_session_t * session, unsigned int flags)
308 {
309         int ret;
310         record_parameters_st *epoch;
311         
312         FAIL_IF_LIB_ERROR;
313
314         *session = gnutls_calloc(1, sizeof(struct gnutls_session_int));
315         if (*session == NULL)
316                 return GNUTLS_E_MEMORY_ERROR;
317
318         ret = _gnutls_epoch_alloc(*session, 0, &epoch);
319         if (ret < 0) {
320                 gnutls_assert();
321                 return GNUTLS_E_MEMORY_ERROR;
322         }
323
324         /* Set all NULL algos on epoch 0 */
325         _gnutls_epoch_set_null_algos(*session, epoch);
326
327         (*session)->security_parameters.epoch_next = 1;
328
329         (*session)->security_parameters.entity =
330             (flags & GNUTLS_SERVER ? GNUTLS_SERVER : GNUTLS_CLIENT);
331
332         /* the default certificate type for TLS */
333         (*session)->security_parameters.cert_type = DEFAULT_CERT_TYPE;
334
335         /* Initialize buffers */
336         _gnutls_buffer_init(&(*session)->internals.handshake_hash_buffer);
337         _gnutls_buffer_init(&(*session)->internals.hb_remote_data);
338         _gnutls_buffer_init(&(*session)->internals.hb_local_data);
339         _gnutls_buffer_init(&(*session)->internals.record_presend_buffer);
340
341         _mbuffer_head_init(&(*session)->internals.record_buffer);
342         _mbuffer_head_init(&(*session)->internals.record_send_buffer);
343         _mbuffer_head_init(&(*session)->internals.record_recv_buffer);
344
345         _mbuffer_head_init(&(*session)->internals.handshake_send_buffer);
346         _gnutls_handshake_recv_buffer_init(*session);
347
348         (*session)->internals.expire_time = DEFAULT_EXPIRE_TIME;        /* one hour default */
349
350         gnutls_handshake_set_max_packet_length((*session),
351                                                MAX_HANDSHAKE_PACKET_SIZE);
352
353         /* set the socket pointers to -1;
354          */
355         (*session)->internals.transport_recv_ptr =
356             (gnutls_transport_ptr_t) - 1;
357         (*session)->internals.transport_send_ptr =
358             (gnutls_transport_ptr_t) - 1;
359
360         /* set the default maximum record size for TLS
361          */
362         (*session)->security_parameters.max_record_recv_size =
363             DEFAULT_MAX_RECORD_SIZE;
364         (*session)->security_parameters.max_record_send_size =
365             DEFAULT_MAX_RECORD_SIZE;
366
367         /* everything else not initialized here is initialized
368          * as NULL or 0. This is why calloc is used.
369          */
370
371         _gnutls_handshake_internal_state_init(*session);
372
373         /* emulate old gnutls behavior for old applications that do not use the priority_*
374          * functions.
375          */
376         (*session)->internals.priorities.sr = SR_PARTIAL;
377
378 #ifdef HAVE_WRITEV
379 #ifdef MSG_NOSIGNAL
380         if (flags & GNUTLS_NO_SIGNAL)
381                 gnutls_transport_set_vec_push_function(*session, system_writev_nosignal);
382         else
383 #endif
384                 gnutls_transport_set_vec_push_function(*session, system_writev);
385 #else
386         gnutls_transport_set_push_function(*session, system_write);
387 #endif
388         (*session)->internals.pull_timeout_func = gnutls_system_recv_timeout;
389         (*session)->internals.pull_func = system_read;
390         (*session)->internals.errno_func = system_errno;
391
392         /* heartbeat timeouts */
393         (*session)->internals.hb_retrans_timeout_ms = 1000;
394         (*session)->internals.hb_total_timeout_ms = 60000;
395
396         if (flags & GNUTLS_DATAGRAM) {
397                 (*session)->internals.dtls.mtu = DTLS_DEFAULT_MTU;
398                 (*session)->internals.transport = GNUTLS_DGRAM;
399
400                 gnutls_dtls_set_timeouts(*session, DTLS_RETRANS_TIMEOUT, 60000);
401         } else {
402                 (*session)->internals.transport = GNUTLS_STREAM;
403         }
404
405         if (flags & GNUTLS_NONBLOCK)
406                 (*session)->internals.blocking = 0;
407         else
408                 (*session)->internals.blocking = 1;
409
410         /* Enable useful extensions */
411         if ((flags & GNUTLS_CLIENT) && !(flags & GNUTLS_NO_EXTENSIONS)) {
412 #ifdef ENABLE_SESSION_TICKETS
413                 gnutls_session_ticket_enable_client(*session);
414 #endif
415 #ifdef ENABLE_OCSP
416                 gnutls_ocsp_status_request_enable_client(*session, NULL, 0,
417                                                          NULL);
418 #endif
419         }
420
421         if (!(flags & GNUTLS_NO_EXTENSIONS))
422                 (*session)->internals.try_ext_master_secret = 1;
423
424         if (flags & GNUTLS_NO_REPLAY_PROTECTION)
425                 (*session)->internals.no_replay_protection = 1;
426
427         return 0;
428 }
429
430 /* returns RESUME_FALSE or RESUME_TRUE.
431  */
432 int _gnutls_session_is_resumable(gnutls_session_t session)
433 {
434         return session->internals.resumable;
435 }
436
437
438 /**
439  * gnutls_deinit:
440  * @session: is a #gnutls_session_t type.
441  *
442  * This function clears all buffers associated with the @session.
443  * This function will also remove session data from the session
444  * database if the session was terminated abnormally.
445  **/
446 void gnutls_deinit(gnutls_session_t session)
447 {
448         unsigned int i;
449
450         if (session == NULL)
451                 return;
452
453         /* remove auth info firstly */
454         _gnutls_free_auth_info(session);
455
456         _gnutls_handshake_internal_state_clear(session);
457         _gnutls_handshake_io_buffer_clear(session);
458         _gnutls_ext_free_session_data(session);
459
460         for (i = 0; i < MAX_EPOCH_INDEX; i++)
461                 if (session->record_parameters[i] != NULL) {
462                         _gnutls_epoch_free(session,
463                                            session->record_parameters[i]);
464                         session->record_parameters[i] = NULL;
465                 }
466
467         _gnutls_buffer_clear(&session->internals.handshake_hash_buffer);
468         _gnutls_buffer_clear(&session->internals.hb_remote_data);
469         _gnutls_buffer_clear(&session->internals.hb_local_data);
470         _gnutls_buffer_clear(&session->internals.record_presend_buffer);
471
472         _mbuffer_head_clear(&session->internals.record_buffer);
473         _mbuffer_head_clear(&session->internals.record_recv_buffer);
474         _mbuffer_head_clear(&session->internals.record_send_buffer);
475
476         gnutls_credentials_clear(session);
477         _gnutls_selected_certs_deinit(session);
478
479         gnutls_pk_params_release(&session->key.ecdh_params);
480         gnutls_pk_params_release(&session->key.dh_params);
481         zrelease_temp_mpi_key(&session->key.ecdh_x);
482         zrelease_temp_mpi_key(&session->key.ecdh_y);
483
484         zrelease_temp_mpi_key(&session->key.client_Y);
485
486         zrelease_temp_mpi_key(&session->key.srp_p);
487         zrelease_temp_mpi_key(&session->key.srp_g);
488         zrelease_temp_mpi_key(&session->key.srp_key);
489
490         zrelease_temp_mpi_key(&session->key.u);
491         zrelease_temp_mpi_key(&session->key.a);
492         zrelease_temp_mpi_key(&session->key.x);
493         zrelease_temp_mpi_key(&session->key.A);
494         zrelease_temp_mpi_key(&session->key.B);
495         zrelease_temp_mpi_key(&session->key.b);
496
497         /* RSA */
498         zrelease_temp_mpi_key(&session->key.rsa[0]);
499         zrelease_temp_mpi_key(&session->key.rsa[1]);
500
501         _gnutls_free_temp_key_datum(&session->key.key);
502
503         gnutls_free(session);
504 }
505
506 /* Returns the minimum prime bits that are acceptable.
507  */
508 int _gnutls_dh_set_peer_public(gnutls_session_t session, bigint_t public)
509 {
510         dh_info_st *dh;
511         int ret;
512
513         switch (gnutls_auth_get_type(session)) {
514         case GNUTLS_CRD_ANON:
515                 {
516                         anon_auth_info_t info;
517                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_ANON);
518                         if (info == NULL)
519                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
520
521                         dh = &info->dh;
522                         break;
523                 }
524         case GNUTLS_CRD_PSK:
525                 {
526                         psk_auth_info_t info;
527                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_PSK);
528                         if (info == NULL)
529                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
530
531                         dh = &info->dh;
532                         break;
533                 }
534         case GNUTLS_CRD_CERTIFICATE:
535                 {
536                         cert_auth_info_t info;
537
538                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_CERTIFICATE);
539                         if (info == NULL)
540                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
541
542                         dh = &info->dh;
543                         break;
544                 }
545         default:
546                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
547         }
548
549         if (dh->public_key.data)
550                 _gnutls_free_datum(&dh->public_key);
551
552         ret = _gnutls_mpi_dprint_lz(public, &dh->public_key);
553         if (ret < 0) {
554                 gnutls_assert();
555                 return ret;
556         }
557
558         return 0;
559 }
560
561 int _gnutls_dh_set_secret_bits(gnutls_session_t session, unsigned bits)
562 {
563         switch (gnutls_auth_get_type(session)) {
564         case GNUTLS_CRD_ANON:
565                 {
566                         anon_auth_info_t info;
567                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_ANON);
568                         if (info == NULL)
569                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
570                         info->dh.secret_bits = bits;
571                         break;
572                 }
573         case GNUTLS_CRD_PSK:
574                 {
575                         psk_auth_info_t info;
576                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_PSK);
577                         if (info == NULL)
578                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
579                         info->dh.secret_bits = bits;
580                         break;
581                 }
582         case GNUTLS_CRD_CERTIFICATE:
583                 {
584                         cert_auth_info_t info;
585
586                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_CERTIFICATE);
587                         if (info == NULL)
588                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
589
590                         info->dh.secret_bits = bits;
591                         break;
592         default:
593                         return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
594                 }
595         }
596
597         return 0;
598 }
599
600 /* Sets the prime and the generator in the auth info structure.
601  */
602 int
603 _gnutls_dh_set_group(gnutls_session_t session, bigint_t gen,
604                      bigint_t prime)
605 {
606         dh_info_st *dh;
607         int ret;
608
609         switch (gnutls_auth_get_type(session)) {
610         case GNUTLS_CRD_ANON:
611                 {
612                         anon_auth_info_t info;
613                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_ANON);
614                         if (info == NULL)
615                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
616
617                         dh = &info->dh;
618                         break;
619                 }
620         case GNUTLS_CRD_PSK:
621                 {
622                         psk_auth_info_t info;
623                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_PSK);
624                         if (info == NULL)
625                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
626
627                         dh = &info->dh;
628                         break;
629                 }
630         case GNUTLS_CRD_CERTIFICATE:
631                 {
632                         cert_auth_info_t info;
633
634                         info = _gnutls_get_auth_info(session, GNUTLS_CRD_CERTIFICATE);
635                         if (info == NULL)
636                                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
637
638                         dh = &info->dh;
639                         break;
640                 }
641         default:
642                 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
643         }
644
645         if (dh->prime.data)
646                 _gnutls_free_datum(&dh->prime);
647
648         if (dh->generator.data)
649                 _gnutls_free_datum(&dh->generator);
650
651         /* prime
652          */
653         ret = _gnutls_mpi_dprint_lz(prime, &dh->prime);
654         if (ret < 0) {
655                 gnutls_assert();
656                 return ret;
657         }
658
659         /* generator
660          */
661         ret = _gnutls_mpi_dprint_lz(gen, &dh->generator);
662         if (ret < 0) {
663                 gnutls_assert();
664                 _gnutls_free_datum(&dh->prime);
665                 return ret;
666         }
667
668         return 0;
669 }
670
671 #ifdef ENABLE_OPENPGP
672 /**
673  * gnutls_openpgp_send_cert:
674  * @session: a #gnutls_session_t type.
675  * @status: is one of GNUTLS_OPENPGP_CERT, or GNUTLS_OPENPGP_CERT_FINGERPRINT
676  *
677  * This function will order gnutls to send the key fingerprint
678  * instead of the key in the initial handshake procedure. This should
679  * be used with care and only when there is indication or knowledge
680  * that the server can obtain the client's key.
681  **/
682 void
683 gnutls_openpgp_send_cert(gnutls_session_t session,
684                          gnutls_openpgp_crt_status_t status)
685 {
686         session->internals.pgp_fingerprint = status;
687 }
688 #endif
689
690 /**
691  * gnutls_certificate_send_x509_rdn_sequence:
692  * @session: a #gnutls_session_t type.
693  * @status: is 0 or 1
694  *
695  * If status is non zero, this function will order gnutls not to send
696  * the rdnSequence in the certificate request message. That is the
697  * server will not advertise its trusted CAs to the peer. If status
698  * is zero then the default behaviour will take effect, which is to
699  * advertise the server's trusted CAs.
700  *
701  * This function has no effect in clients, and in authentication
702  * methods other than certificate with X.509 certificates.
703  **/
704 void
705 gnutls_certificate_send_x509_rdn_sequence(gnutls_session_t session,
706                                           int status)
707 {
708         session->internals.ignore_rdn_sequence = status;
709 }
710
711 #ifdef ENABLE_OPENPGP
712 int _gnutls_openpgp_send_fingerprint(gnutls_session_t session)
713 {
714         return session->internals.pgp_fingerprint;
715 }
716 #endif
717
718 /*-
719  * _gnutls_record_set_default_version - Used to set the default version for the first record packet
720  * @session: is a #gnutls_session_t type.
721  * @major: is a tls major version
722  * @minor: is a tls minor version
723  *
724  * This function sets the default version that we will use in the first
725  * record packet (client hello). This function is only useful to people
726  * that know TLS internals and want to debug other implementations.
727  -*/
728 void
729 _gnutls_record_set_default_version(gnutls_session_t session,
730                                    unsigned char major,
731                                    unsigned char minor)
732 {
733         session->internals.default_record_version[0] = major;
734         session->internals.default_record_version[1] = minor;
735 }
736
737 /*-
738  * _gnutls_hello_set_default_version - Used to set the default version for the first record packet
739  * @session: is a #gnutls_session_t type.
740  * @major: is a tls major version
741  * @minor: is a tls minor version
742  *
743  * This function sets the default version that we will use in the first
744  * record packet (client hello). This function is only useful to people
745  * that know TLS internals and want to debug other implementations.
746  -*/
747 void
748 _gnutls_hello_set_default_version(gnutls_session_t session,
749                                    unsigned char major,
750                                    unsigned char minor)
751 {
752         session->internals.default_hello_version[0] = major;
753         session->internals.default_hello_version[1] = minor;
754 }
755
756 /**
757  * gnutls_handshake_set_private_extensions:
758  * @session: is a #gnutls_session_t type.
759  * @allow: is an integer (0 or 1)
760  *
761  * This function will enable or disable the use of private cipher
762  * suites (the ones that start with 0xFF).  By default or if @allow
763  * is 0 then these cipher suites will not be advertised nor used.
764  *
765  * Currently GnuTLS does not include such cipher-suites or
766  * compression algorithms.
767  *
768  * Enabling the private ciphersuites when talking to other than
769  * gnutls servers and clients may cause interoperability problems.
770  **/
771 void
772 gnutls_handshake_set_private_extensions(gnutls_session_t session,
773                                         int allow)
774 {
775         session->internals.enable_private = allow;
776 }
777
778 inline static int
779 _gnutls_cal_PRF_A(const mac_entry_st * me,
780                   const void *secret, int secret_size,
781                   const void *seed, int seed_size, void *result)
782 {
783         int ret;
784
785         ret =
786             _gnutls_mac_fast(me->id, secret, secret_size, seed, seed_size,
787                              result);
788         if (ret < 0)
789                 return gnutls_assert_val(ret);
790
791         return 0;
792 }
793
794 #define MAX_SEED_SIZE 200
795
796 /* Produces "total_bytes" bytes using the hash algorithm specified.
797  * (used in the PRF function)
798  */
799 static int
800 P_hash(gnutls_mac_algorithm_t algorithm,
801        const uint8_t * secret, int secret_size,
802        const uint8_t * seed, int seed_size, int total_bytes, uint8_t * ret)
803 {
804
805         mac_hd_st td2;
806         int i, times, how, blocksize, A_size;
807         uint8_t final[MAX_HASH_SIZE], Atmp[MAX_SEED_SIZE];
808         int output_bytes, result;
809         const mac_entry_st *me = mac_to_entry(algorithm);
810
811         blocksize = _gnutls_mac_get_algo_len(me);
812
813         if (seed_size > MAX_SEED_SIZE || total_bytes <= 0 || blocksize == 0) {
814                 gnutls_assert();
815                 return GNUTLS_E_INTERNAL_ERROR;
816         }
817
818         output_bytes = 0;
819         do {
820                 output_bytes += blocksize;
821         }
822         while (output_bytes < total_bytes);
823
824         /* calculate A(0) */
825
826         memcpy(Atmp, seed, seed_size);
827         A_size = seed_size;
828
829         times = output_bytes / blocksize;
830
831         for (i = 0; i < times; i++) {
832                 result = _gnutls_mac_init(&td2, me, secret, secret_size);
833                 if (result < 0) {
834                         gnutls_assert();
835                         return result;
836                 }
837
838                 /* here we calculate A(i+1) */
839                 if ((result =
840                      _gnutls_cal_PRF_A(me, secret, secret_size, Atmp,
841                                        A_size, Atmp)) < 0) {
842                         gnutls_assert();
843                         _gnutls_mac_deinit(&td2, final);
844                         return result;
845                 }
846
847                 A_size = blocksize;
848
849                 _gnutls_mac(&td2, Atmp, A_size);
850                 _gnutls_mac(&td2, seed, seed_size);
851                 _gnutls_mac_deinit(&td2, final);
852
853                 if ((1 + i) * blocksize < total_bytes) {
854                         how = blocksize;
855                 } else {
856                         how = total_bytes - (i) * blocksize;
857                 }
858
859                 if (how > 0) {
860                         memcpy(&ret[i * blocksize], final, how);
861                 }
862         }
863
864         return 0;
865 }
866
867 #define MAX_PRF_BYTES 200
868
869 /* This function operates as _gnutls_PRF(), but does not require
870  * a pointer to the current session. It takes the @mac algorithm
871  * explicitly. For legacy TLS/SSL sessions before TLS 1.2 the MAC
872  * must be set to %GNUTLS_MAC_UNKNOWN.
873  */
874 static int
875 _gnutls_PRF_raw(gnutls_mac_algorithm_t mac,
876                 const uint8_t * secret, unsigned int secret_size,
877                 const char *label, int label_size, const uint8_t * seed,
878                 int seed_size, int total_bytes, void *ret)
879 {
880         int l_s, s_seed_size;
881         const uint8_t *s1, *s2;
882         uint8_t s_seed[MAX_SEED_SIZE];
883         uint8_t o1[MAX_PRF_BYTES], o2[MAX_PRF_BYTES];
884         int result;
885
886         if (total_bytes > MAX_PRF_BYTES) {
887                 gnutls_assert();
888                 return GNUTLS_E_INTERNAL_ERROR;
889         }
890         /* label+seed = s_seed */
891         s_seed_size = seed_size + label_size;
892
893         if (s_seed_size > MAX_SEED_SIZE) {
894                 gnutls_assert();
895                 return GNUTLS_E_INTERNAL_ERROR;
896         }
897
898         memcpy(s_seed, label, label_size);
899         memcpy(&s_seed[label_size], seed, seed_size);
900
901         if (mac != GNUTLS_MAC_UNKNOWN) {
902                 result =
903                     P_hash(mac, secret, secret_size,
904                            s_seed, s_seed_size,
905                            total_bytes, ret);
906                 if (result < 0) {
907                         gnutls_assert();
908                         return result;
909                 }
910         } else {
911                 l_s = secret_size / 2;
912
913                 s1 = &secret[0];
914                 s2 = &secret[l_s];
915
916                 if (secret_size % 2 != 0) {
917                         l_s++;
918                 }
919
920                 result =
921                     P_hash(GNUTLS_MAC_MD5, s1, l_s, s_seed, s_seed_size,
922                            total_bytes, o1);
923                 if (result < 0) {
924                         gnutls_assert();
925                         return result;
926                 }
927
928                 result =
929                     P_hash(GNUTLS_MAC_SHA1, s2, l_s, s_seed, s_seed_size,
930                            total_bytes, o2);
931                 if (result < 0) {
932                         gnutls_assert();
933                         return result;
934                 }
935
936                 memxor(o1, o2, total_bytes);
937
938                 memcpy(ret, o1, total_bytes);
939         }
940
941         return 0;               /* ok */
942 }
943
944 /* The PRF function expands a given secret 
945  * needed by the TLS specification. ret must have a least total_bytes
946  * available.
947  */
948 int
949 _gnutls_PRF(gnutls_session_t session,
950             const uint8_t * secret, unsigned int secret_size,
951             const char *label, int label_size, const uint8_t * seed,
952             int seed_size, int total_bytes, void *ret)
953 {
954         const version_entry_st *ver = get_version(session);
955
956         if (_gnutls_version_has_selectable_prf(ver)) {
957                 return _gnutls_PRF_raw(
958                         _gnutls_cipher_suite_get_prf(session->security_parameters.cipher_suite),
959                         secret, secret_size,
960                         label, label_size,
961                         seed, seed_size,
962                         total_bytes,
963                         ret);
964         } else {
965                 return _gnutls_PRF_raw(
966                         GNUTLS_MAC_UNKNOWN,
967                         secret, secret_size,
968                         label, label_size,
969                         seed, seed_size,
970                         total_bytes,
971                         ret);
972         }
973 }
974
975 #ifdef ENABLE_FIPS140
976 int
977 _gnutls_prf_raw(gnutls_mac_algorithm_t mac,
978                 size_t master_size, const void *master,
979                 size_t label_size, const char *label,
980                 size_t seed_size, const char *seed, size_t outsize,
981                 char *out);
982
983 /*-
984  * _gnutls_prf_raw:
985  * @mac: the MAC algorithm to use, set to %GNUTLS_MAC_UNKNOWN for the TLS1.0 mac
986  * @master_size: length of the @master variable.
987  * @master: the master secret used in PRF computation
988  * @label_size: length of the @label variable.
989  * @label: label used in PRF computation, typically a short string.
990  * @seed_size: length of the @seed variable.
991  * @seed: optional extra data to seed the PRF with.
992  * @outsize: size of pre-allocated output buffer to hold the output.
993  * @out: pre-allocated buffer to hold the generated data.
994  *
995  * Apply the TLS Pseudo-Random-Function (PRF) on the master secret
996  * and the provided data.
997  *
998  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
999  -*/
1000 int
1001 _gnutls_prf_raw(gnutls_mac_algorithm_t mac,
1002                 size_t master_size, const void *master,
1003                 size_t label_size, const char *label,
1004                 size_t seed_size, const char *seed, size_t outsize,
1005                 char *out)
1006 {
1007         return _gnutls_PRF_raw(mac,
1008                           master, master_size,
1009                           label, label_size,
1010                           (uint8_t *) seed, seed_size,
1011                           outsize, out);
1012
1013 }
1014 #endif
1015
1016 /**
1017  * gnutls_prf_raw:
1018  * @session: is a #gnutls_session_t type.
1019  * @label_size: length of the @label variable.
1020  * @label: label used in PRF computation, typically a short string.
1021  * @seed_size: length of the @seed variable.
1022  * @seed: optional extra data to seed the PRF with.
1023  * @outsize: size of pre-allocated output buffer to hold the output.
1024  * @out: pre-allocated buffer to hold the generated data.
1025  *
1026  * Apply the TLS Pseudo-Random-Function (PRF) on the master secret
1027  * and the provided data.
1028  *
1029  * The @label variable usually contains a string denoting the purpose
1030  * for the generated data.  The @seed usually contains data such as the
1031  * client and server random, perhaps together with some additional
1032  * data that is added to guarantee uniqueness of the output for a
1033  * particular purpose.
1034  *
1035  * Because the output is not guaranteed to be unique for a particular
1036  * session unless @seed includes the client random and server random
1037  * fields (the PRF would output the same data on another connection
1038  * resumed from the first one), it is not recommended to use this
1039  * function directly.  The gnutls_prf() function seeds the PRF with the
1040  * client and server random fields directly, and is recommended if you
1041  * want to generate pseudo random data unique for each session.
1042  *
1043  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
1044  **/
1045 int
1046 gnutls_prf_raw(gnutls_session_t session,
1047                size_t label_size,
1048                const char *label,
1049                size_t seed_size, const char *seed, size_t outsize,
1050                char *out)
1051 {
1052         int ret;
1053
1054         ret = _gnutls_PRF(session,
1055                           session->security_parameters.master_secret,
1056                           GNUTLS_MASTER_SIZE,
1057                           label,
1058                           label_size, (uint8_t *) seed, seed_size, outsize,
1059                           out);
1060
1061         return ret;
1062 }
1063
1064 /**
1065  * gnutls_prf_rfc5705:
1066  * @session: is a #gnutls_session_t type.
1067  * @label_size: length of the @label variable.
1068  * @label: label used in PRF computation, typically a short string.
1069  * @context_size: length of the @extra variable.
1070  * @context: optional extra data to seed the PRF with.
1071  * @outsize: size of pre-allocated output buffer to hold the output.
1072  * @out: pre-allocated buffer to hold the generated data.
1073  *
1074  * Applies the TLS Pseudo-Random-Function (PRF) on the master secret
1075  * and the provided data, seeded with the client and server random fields,
1076  * as specified in RFC5705.
1077  *
1078  * The @label variable usually contains a string denoting the purpose
1079  * for the generated data.  The @server_random_first indicates whether
1080  * the client random field or the server random field should be first
1081  * in the seed.  Non-zero indicates that the server random field is first,
1082  * 0 that the client random field is first.
1083  *
1084  * The @context variable can be used to add more data to the seed, after
1085  * the random variables.  It can be used to make sure the
1086  * generated output is strongly connected to some additional data
1087  * (e.g., a string used in user authentication). 
1088  *
1089  * The output is placed in @out, which must be pre-allocated.
1090  *
1091  * Note that, to provide the RFC5705 context, the @contect variable
1092  * must be non-null.
1093  *
1094  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
1095  *
1096  * Since: 3.4.4
1097  **/
1098 int
1099 gnutls_prf_rfc5705(gnutls_session_t session,
1100                    size_t label_size, const char *label,
1101                    size_t context_size, const char *context,
1102                    size_t outsize, char *out)
1103 {
1104         char *pctx = NULL;
1105         int ret;
1106
1107         if (context != NULL && context_size > 65535)  {
1108                 gnutls_assert();
1109                 return GNUTLS_E_INVALID_REQUEST;
1110         }
1111
1112         if (context != NULL) {
1113                 pctx = gnutls_malloc(context_size+2);
1114                 if (!pctx) {
1115                         gnutls_assert();
1116                         return GNUTLS_E_MEMORY_ERROR;
1117                 }
1118
1119                 memcpy(pctx+2, context, context_size);
1120                 _gnutls_write_uint16(context_size, (void*)pctx);
1121                 context_size += 2;
1122         }
1123
1124         ret = gnutls_prf(session, label_size, label, 0,
1125                          context_size, pctx, outsize, out);
1126
1127         gnutls_free(pctx);
1128         return ret;
1129 }
1130
1131 /**
1132  * gnutls_prf:
1133  * @session: is a #gnutls_session_t type.
1134  * @label_size: length of the @label variable.
1135  * @label: label used in PRF computation, typically a short string.
1136  * @server_random_first: non-zero if server random field should be first in seed
1137  * @extra_size: length of the @extra variable.
1138  * @extra: optional extra data to seed the PRF with.
1139  * @outsize: size of pre-allocated output buffer to hold the output.
1140  * @out: pre-allocated buffer to hold the generated data.
1141  *
1142  * Applies the TLS Pseudo-Random-Function (PRF) on the master secret
1143  * and the provided data, seeded with the client and server random fields.
1144  * For the key expansion specified in RFC5705 see gnutls_prf_rfc5705().
1145  *
1146  * The @label variable usually contains a string denoting the purpose
1147  * for the generated data.  The @server_random_first indicates whether
1148  * the client random field or the server random field should be first
1149  * in the seed.  Non-zero indicates that the server random field is first,
1150  * 0 that the client random field is first.
1151  *
1152  * The @extra variable can be used to add more data to the seed, after
1153  * the random variables.  It can be used to make sure the
1154  * generated output is strongly connected to some additional data
1155  * (e.g., a string used in user authentication).
1156  *
1157  * The output is placed in @out, which must be pre-allocated.
1158  *
1159  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
1160  **/
1161 int
1162 gnutls_prf(gnutls_session_t session,
1163            size_t label_size,
1164            const char *label,
1165            int server_random_first,
1166            size_t extra_size, const char *extra,
1167            size_t outsize, char *out)
1168 {
1169         int ret;
1170         uint8_t *seed;
1171         size_t seedsize = 2 * GNUTLS_RANDOM_SIZE + extra_size;
1172
1173         seed = gnutls_malloc(seedsize);
1174         if (!seed) {
1175                 gnutls_assert();
1176                 return GNUTLS_E_MEMORY_ERROR;
1177         }
1178
1179         memcpy(seed, server_random_first ?
1180                session->security_parameters.server_random :
1181                session->security_parameters.client_random,
1182                GNUTLS_RANDOM_SIZE);
1183         memcpy(seed + GNUTLS_RANDOM_SIZE,
1184                server_random_first ? session->security_parameters.
1185                client_random : session->security_parameters.server_random,
1186                GNUTLS_RANDOM_SIZE);
1187
1188         if (extra && extra_size) {
1189                 memcpy(seed + 2 * GNUTLS_RANDOM_SIZE, extra, extra_size);
1190         }
1191
1192         ret =
1193             _gnutls_PRF(session,
1194                         session->security_parameters.master_secret,
1195                         GNUTLS_MASTER_SIZE, label, label_size, seed,
1196                         seedsize, outsize, out);
1197
1198         gnutls_free(seed);
1199
1200         return ret;
1201 }
1202
1203 /**
1204  * gnutls_session_is_resumed:
1205  * @session: is a #gnutls_session_t type.
1206  *
1207  * Check whether session is resumed or not.
1208  *
1209  * Returns: non zero if this session is resumed, or a zero if this is
1210  *   a new session.
1211  **/
1212 int gnutls_session_is_resumed(gnutls_session_t session)
1213 {
1214         if (session->security_parameters.entity == GNUTLS_CLIENT) {
1215                 if (session->security_parameters.session_id_size > 0 &&
1216                     session->security_parameters.session_id_size ==
1217                     session->internals.resumed_security_parameters.
1218                     session_id_size
1219                     && memcmp(session->security_parameters.session_id,
1220                               session->
1221                               internals.resumed_security_parameters.
1222                               session_id,
1223                               session->security_parameters.
1224                               session_id_size) == 0)
1225                         return 1;
1226         } else {
1227                 if (session->internals.resumed != RESUME_FALSE)
1228                         return 1;
1229         }
1230
1231         return 0;
1232 }
1233
1234 /**
1235  * gnutls_session_resumption_requested:
1236  * @session: is a #gnutls_session_t type.
1237  *
1238  * Check whether the client has asked for session resumption.
1239  * This function is valid only on server side.
1240  *
1241  * Returns: non zero if session resumption was asked, or a zero if not.
1242  **/
1243 int gnutls_session_resumption_requested(gnutls_session_t session)
1244 {
1245         if (session->security_parameters.entity == GNUTLS_CLIENT) {
1246                 return 0;
1247         } else {
1248                 return session->internals.resumption_requested;
1249         }
1250 }
1251
1252 /*-
1253  * _gnutls_session_is_psk - Used to check whether this session uses PSK kx
1254  * @session: is a #gnutls_session_t type.
1255  *
1256  * This function will return non zero if this session uses a PSK key
1257  * exchange algorithm.
1258  -*/
1259 int _gnutls_session_is_psk(gnutls_session_t session)
1260 {
1261         gnutls_kx_algorithm_t kx;
1262
1263         kx = _gnutls_cipher_suite_get_kx_algo(session->security_parameters.
1264                                               cipher_suite);
1265         if (kx == GNUTLS_KX_PSK || kx == GNUTLS_KX_DHE_PSK
1266             || kx == GNUTLS_KX_RSA_PSK)
1267                 return 1;
1268
1269         return 0;
1270 }
1271
1272 /*-
1273  * _gnutls_session_is_ecc - Used to check whether this session uses ECC kx
1274  * @session: is a #gnutls_session_t type.
1275  *
1276  * This function will return non zero if this session uses an elliptic
1277  * curves key exchange exchange algorithm.
1278  -*/
1279 int _gnutls_session_is_ecc(gnutls_session_t session)
1280 {
1281         gnutls_kx_algorithm_t kx;
1282
1283         /* We get the key exchange algorithm through the ciphersuite because
1284          * the negotiated key exchange might not have been set yet.
1285          */
1286         kx = _gnutls_cipher_suite_get_kx_algo(session->security_parameters.
1287                                               cipher_suite);
1288
1289         return _gnutls_kx_is_ecc(kx);
1290 }
1291
1292 /**
1293  * gnutls_session_get_ptr:
1294  * @session: is a #gnutls_session_t type.
1295  *
1296  * Get user pointer for session.  Useful in callbacks.  This is the
1297  *   pointer set with gnutls_session_set_ptr().
1298  *
1299  * Returns: the user given pointer from the session structure, or
1300  *   %NULL if it was never set.
1301  **/
1302 void *gnutls_session_get_ptr(gnutls_session_t session)
1303 {
1304         return session->internals.user_ptr;
1305 }
1306
1307 /**
1308  * gnutls_session_set_ptr:
1309  * @session: is a #gnutls_session_t type.
1310  * @ptr: is the user pointer
1311  *
1312  * This function will set (associate) the user given pointer @ptr to
1313  * the session structure.  This pointer can be accessed with
1314  * gnutls_session_get_ptr().
1315  **/
1316 void gnutls_session_set_ptr(gnutls_session_t session, void *ptr)
1317 {
1318         session->internals.user_ptr = ptr;
1319 }
1320
1321 /**
1322  * gnutls_session_set_verify_function:
1323  * @session: is a #gnutls_session_t type.
1324  * @func: is the callback function
1325  *
1326  * This function sets a callback to be called when peer's certificate
1327  * has been received in order to verify it on receipt rather than
1328  * doing after the handshake is completed. This overrides any callback
1329  * set using gnutls_certificate_set_verify_function().
1330  *
1331  * The callback's function prototype is:
1332  * int (*callback)(gnutls_session_t);
1333  *
1334  * If the callback function is provided then gnutls will call it, in the
1335  * handshake, just after the certificate message has been received.
1336  * To verify or obtain the certificate the gnutls_certificate_verify_peers2(),
1337  * gnutls_certificate_type_get(), gnutls_certificate_get_peers() functions
1338  * can be used.
1339  *
1340  * The callback function should return 0 for the handshake to continue
1341  * or non-zero to terminate.
1342  *
1343  * Since: 3.4.6
1344  **/
1345 void
1346  gnutls_session_set_verify_function
1347     (gnutls_session_t session,
1348      gnutls_certificate_verify_function * func)
1349 {
1350         session->internals.verify_callback = func;
1351 }
1352
1353 /**
1354  * gnutls_record_get_direction:
1355  * @session: is a #gnutls_session_t type.
1356  *
1357  * This function provides information about the internals of the
1358  * record protocol and is only useful if a prior gnutls function call,
1359  * e.g.  gnutls_handshake(), was interrupted for some reason. That
1360  * is, if a function returned %GNUTLS_E_INTERRUPTED or
1361  * %GNUTLS_E_AGAIN. In such a case, you might want to call select()
1362  * or poll() before restoring the interrupted gnutls function.
1363  *
1364  * This function's output is unreliable if you are using the same
1365  * @session in different threads, for sending and receiving.
1366  *
1367  * Returns: 0 if interrupted while trying to read data, or 1 while trying to write data.
1368  **/
1369 int gnutls_record_get_direction(gnutls_session_t session)
1370 {
1371         return session->internals.direction;
1372 }
1373
1374 /*-
1375  * _gnutls_rsa_pms_set_version - Sets a version to be used at the RSA PMS
1376  * @session: is a #gnutls_session_t type.
1377  * @major: is the major version to use
1378  * @minor: is the minor version to use
1379  *
1380  * This function will set the given version number to be used at the
1381  * RSA PMS secret. This is only useful to clients, which want to
1382  * test server's capabilities.
1383  -*/
1384 void
1385 _gnutls_rsa_pms_set_version(gnutls_session_t session,
1386                             unsigned char major, unsigned char minor)
1387 {
1388         session->internals.rsa_pms_version[0] = major;
1389         session->internals.rsa_pms_version[1] = minor;
1390 }
1391
1392 /**
1393  * gnutls_handshake_set_post_client_hello_function:
1394  * @session: is a #gnutls_session_t type.
1395  * @func: is the function to be called
1396  *
1397  * This function will set a callback to be called after the client
1398  * hello has been received (callback valid in server side only). This
1399  * allows the server to adjust settings based on received extensions.
1400  *
1401  * Those settings could be ciphersuites, requesting certificate, or
1402  * anything else except for version negotiation (this is done before
1403  * the hello message is parsed).
1404  *
1405  * This callback must return 0 on success or a gnutls error code to
1406  * terminate the handshake.
1407  *
1408  * Since GnuTLS 3.3.5 the callback is
1409  * allowed to return %GNUTLS_E_AGAIN or %GNUTLS_E_INTERRUPTED to
1410  * put the handshake on hold. In that case gnutls_handshake()
1411  * will return %GNUTLS_E_INTERRUPTED and can be resumed when needed.
1412  *
1413  * Warning: You should not use this function to terminate the
1414  * handshake based on client input unless you know what you are
1415  * doing. Before the handshake is finished there is no way to know if
1416  * there is a man-in-the-middle attack being performed.
1417  **/
1418 void
1419 gnutls_handshake_set_post_client_hello_function(gnutls_session_t session,
1420                                                 gnutls_handshake_post_client_hello_func
1421                                                 func)
1422 {
1423         session->internals.user_hello_func = func;
1424 }
1425
1426
1427 /**
1428  * gnutls_session_enable_compatibility_mode:
1429  * @session: is a #gnutls_session_t type.
1430  *
1431  * This function can be used to disable certain (security) features in
1432  * TLS in order to maintain maximum compatibility with buggy
1433  * clients. Because several trade-offs with security are enabled,
1434  * if required they will be reported through the audit subsystem.
1435  *
1436  * Normally only servers that require maximum compatibility with
1437  * everything out there, need to call this function.
1438  *
1439  * Note that this function must be called after any call to gnutls_priority
1440  * functions.
1441  **/
1442 void gnutls_session_enable_compatibility_mode(gnutls_session_t session)
1443 {
1444         ENABLE_COMPAT(&session->internals.priorities);
1445 }
1446
1447 /**
1448  * gnutls_session_channel_binding:
1449  * @session: is a #gnutls_session_t type.
1450  * @cbtype: an #gnutls_channel_binding_t enumeration type
1451  * @cb: output buffer array with data
1452  *
1453  * Extract given channel binding data of the @cbtype (e.g.,
1454  * %GNUTLS_CB_TLS_UNIQUE) type.
1455  *
1456  * Returns: %GNUTLS_E_SUCCESS on success,
1457  * %GNUTLS_E_UNIMPLEMENTED_FEATURE if the @cbtype is unsupported,
1458  * %GNUTLS_E_CHANNEL_BINDING_NOT_AVAILABLE if the data is not
1459  * currently available, or an error code.
1460  *
1461  * Since: 2.12.0
1462  **/
1463 int
1464 gnutls_session_channel_binding(gnutls_session_t session,
1465                                gnutls_channel_binding_t cbtype,
1466                                gnutls_datum_t * cb)
1467 {
1468         if (cbtype != GNUTLS_CB_TLS_UNIQUE)
1469                 return GNUTLS_E_UNIMPLEMENTED_FEATURE;
1470
1471         if (!session->internals.initial_negotiation_completed)
1472                 return GNUTLS_E_CHANNEL_BINDING_NOT_AVAILABLE;
1473
1474         cb->size = session->internals.cb_tls_unique_len;
1475         cb->data = gnutls_malloc(cb->size);
1476         if (cb->data == NULL)
1477                 return GNUTLS_E_MEMORY_ERROR;
1478
1479         memcpy(cb->data, session->internals.cb_tls_unique, cb->size);
1480
1481         return 0;
1482 }
1483
1484 /**
1485  * gnutls_ecc_curve_get:
1486  * @session: is a #gnutls_session_t type.
1487  *
1488  * Returns the currently used elliptic curve. Only valid
1489  * when using an elliptic curve ciphersuite.
1490  *
1491  * Returns: the currently used curve, a #gnutls_ecc_curve_t
1492  *   type.
1493  *
1494  * Since: 3.0
1495  **/
1496 gnutls_ecc_curve_t gnutls_ecc_curve_get(gnutls_session_t session)
1497 {
1498         return _gnutls_session_ecc_curve_get(session);
1499 }
1500
1501 /**
1502  * gnutls_protocol_get_version:
1503  * @session: is a #gnutls_session_t type.
1504  *
1505  * Get TLS version, a #gnutls_protocol_t value.
1506  *
1507  * Returns: The version of the currently used protocol.
1508  **/
1509 gnutls_protocol_t gnutls_protocol_get_version(gnutls_session_t session)
1510 {
1511         return get_num_version(session);
1512 }
1513
1514 /**
1515  * gnutls_session_get_random:
1516  * @session: is a #gnutls_session_t type.
1517  * @client: the client part of the random
1518  * @server: the server part of the random
1519  *
1520  * This function returns pointers to the client and server
1521  * random fields used in the TLS handshake. The pointers are
1522  * not to be modified or deallocated.
1523  *
1524  * If a client random value has not yet been established, the output
1525  * will be garbage.
1526  *
1527  * Since: 3.0
1528  **/
1529 void
1530 gnutls_session_get_random(gnutls_session_t session,
1531                           gnutls_datum_t * client, gnutls_datum_t * server)
1532 {
1533         if (client) {
1534                 client->data = session->security_parameters.client_random;
1535                 client->size =
1536                     sizeof(session->security_parameters.client_random);
1537         }
1538
1539         if (server) {
1540                 server->data = session->security_parameters.server_random;
1541                 server->size =
1542                     sizeof(session->security_parameters.server_random);
1543         }
1544 }
1545
1546 unsigned int timespec_sub_ms(struct timespec *a, struct timespec *b)
1547 {
1548         time_t dsecs;
1549
1550         dsecs = a->tv_sec - b->tv_sec;
1551         if (!INT_MULTIPLY_OVERFLOW(dsecs, 1000)) {
1552                 return (dsecs*1000 + (a->tv_nsec - b->tv_nsec) / (1000 * 1000));
1553         } else {
1554                 return UINT_MAX;
1555         }
1556 }
1557
1558 /**
1559  * gnutls_handshake_set_random:
1560  * @session: is a #gnutls_session_t type.
1561  * @random: a random value of 32-bytes
1562  *
1563  * This function will explicitly set the server or client hello 
1564  * random value in the subsequent TLS handshake. The random value 
1565  * should be a 32-byte value.
1566  *
1567  * Note that this function should not normally be used as gnutls
1568  * will select automatically a random value for the handshake.
1569  *
1570  * This function should not be used when resuming a session.
1571  *
1572  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
1573  *
1574  * Since 3.1.9
1575  **/
1576 int
1577 gnutls_handshake_set_random(gnutls_session_t session,
1578                             const gnutls_datum_t * random)
1579 {
1580         if (random->size != GNUTLS_RANDOM_SIZE)
1581                 return GNUTLS_E_INVALID_REQUEST;
1582
1583         session->internals.sc_random_set = 1;
1584         if (session->security_parameters.entity == GNUTLS_CLIENT)
1585                 memcpy(session->internals.resumed_security_parameters.
1586                        client_random, random->data, random->size);
1587         else
1588                 memcpy(session->internals.resumed_security_parameters.
1589                        server_random, random->data, random->size);
1590
1591         return 0;
1592 }
1593
1594 /**
1595  * gnutls_handshake_set_hook_function:
1596  * @session: is a #gnutls_session_t type
1597  * @htype: the %gnutls_handshake_description_t of the message to hook at
1598  * @post: %GNUTLS_HOOK_* depending on when the hook function should be called
1599  * @func: is the function to be called
1600  *
1601  * This function will set a callback to be called after or before the specified
1602  * handshake message has been received or generated. This is a
1603  * generalization of gnutls_handshake_set_post_client_hello_function().
1604  *
1605  * To call the hook function prior to the message being sent/generated use
1606  * %GNUTLS_HOOK_PRE as @post parameter, %GNUTLS_HOOK_POST to call
1607  * after, and %GNUTLS_HOOK_BOTH for both cases.
1608  *
1609  * This callback must return 0 on success or a gnutls error code to
1610  * terminate the handshake.
1611  *
1612  * Note to hook at all handshake messages use an @htype of %GNUTLS_HANDSHAKE_ANY.
1613  *
1614  * Warning: You should not use this function to terminate the
1615  * handshake based on client input unless you know what you are
1616  * doing. Before the handshake is finished there is no way to know if
1617  * there is a man-in-the-middle attack being performed.
1618  **/
1619 void
1620 gnutls_handshake_set_hook_function(gnutls_session_t session,
1621                                    unsigned int htype,
1622                                    int post,
1623                                    gnutls_handshake_hook_func func)
1624 {
1625         session->internals.h_hook = func;
1626         session->internals.h_type = htype;
1627         session->internals.h_post = post;
1628 }
1629
1630 /**
1631  * gnutls_record_get_state:
1632  * @session: is a #gnutls_session_t type
1633  * @read: if non-zero the read parameters are returned, otherwise the write
1634  * @mac_key: the key used for MAC (if a MAC is used)
1635  * @IV: the initialization vector or nonce used
1636  * @cipher_key: the cipher key
1637  * @seq_number: A 64-bit sequence number
1638  *
1639  * This function will return the parameters of the current record state.
1640  * These are only useful to be provided to an external off-loading device
1641  * or subsystem.
1642  *
1643  * In that case, to sync the state you must call gnutls_record_set_state().
1644  *
1645  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
1646  *
1647  * Since 3.4.0
1648  **/
1649 int
1650 gnutls_record_get_state(gnutls_session_t session,
1651                         unsigned read,
1652                         gnutls_datum_t *mac_key,
1653                         gnutls_datum_t *IV,
1654                         gnutls_datum_t *cipher_key,
1655                         unsigned char seq_number[8])
1656 {
1657         record_parameters_st *record_params;
1658         record_state_st *record_state;
1659         unsigned int epoch;
1660         int ret;
1661
1662         if (read)
1663                 epoch = EPOCH_READ_CURRENT;
1664         else
1665                 epoch = EPOCH_WRITE_CURRENT;
1666
1667         ret = _gnutls_epoch_get(session, epoch, &record_params);
1668         if (ret < 0)
1669                 return gnutls_assert_val(ret);
1670
1671         if (!record_params->initialized)
1672                 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
1673
1674         if (read)
1675                 record_state = &record_params->read;
1676         else
1677                 record_state = &record_params->write;
1678
1679         if (mac_key)
1680                 memcpy(mac_key, &record_state->mac_secret, sizeof(gnutls_datum_t));
1681         if (IV)
1682                 memcpy(IV, &record_state->IV, sizeof(gnutls_datum_t));
1683         if (cipher_key)
1684                 memcpy(cipher_key, &record_state->key, sizeof(gnutls_datum_t));
1685         if (seq_number)
1686                 memcpy(seq_number, UINT64DATA(record_state->sequence_number), 8);
1687         return 0;
1688 }
1689
1690 /**
1691  * gnutls_record_set_state:
1692  * @session: is a #gnutls_session_t type
1693  * @read: if non-zero the read parameters are returned, otherwise the write
1694  * @seq_number: A 64-bit sequence number
1695  *
1696  * This function will set the sequence number in the current record state.
1697  * This function is useful if sending and receiving are offloaded from
1698  * gnutls. That is, if gnutls_record_get_state() was used.
1699  *
1700  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
1701  *
1702  * Since 3.4.0
1703  **/
1704 int
1705 gnutls_record_set_state(gnutls_session_t session,
1706                         unsigned read,
1707                         unsigned char seq_number[8])
1708 {
1709         record_parameters_st *record_params;
1710         record_state_st *record_state;
1711         int epoch, ret;
1712
1713         if (read)
1714                 epoch = EPOCH_READ_CURRENT;
1715         else
1716                 epoch = EPOCH_WRITE_CURRENT;
1717
1718         ret = _gnutls_epoch_get(session, epoch, &record_params);
1719         if (ret < 0)
1720                 return gnutls_assert_val(ret);
1721
1722         if (!record_params->initialized)
1723                 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
1724
1725         if (read)
1726                 record_state = &record_params->read;
1727         else
1728                 record_state = &record_params->write;
1729
1730         memcpy(UINT64DATA(record_state->sequence_number), seq_number, 8);
1731
1732         if (IS_DTLS(session)) {
1733                 _dtls_reset_window(session, seq_number);
1734         }
1735
1736         return 0;
1737 }