Tizen 2.0 Release
[external/libgnutls26.git] / lib / gnutls_state.c
1 /*
2  * Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
3  * Free Software Foundation, Inc.
4  *
5  * Author: Nikos Mavrogiannopoulos
6  *
7  * This file is part of GnuTLS.
8  *
9  * The GnuTLS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1 of
12  * the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
22  * USA
23  *
24  */
25
26 /* Functions to manipulate the session (gnutls_int.h), and some other stuff
27  * are included here. The file's name is traditionally gnutls_state even if the
28  * state has been renamed to session.
29  */
30
31 #include <gnutls_int.h>
32 #include <gnutls_errors.h>
33 #include <gnutls_auth.h>
34 #include <gnutls_num.h>
35 #include <gnutls_datum.h>
36 #include <gnutls_db.h>
37 #include <gnutls_record.h>
38 #include <gnutls_handshake.h>
39 #include <gnutls_dh.h>
40 #include <gnutls_buffers.h>
41 #include <gnutls_mbuffers.h>
42 #include <gnutls_state.h>
43 #include <gnutls_constate.h>
44 #include <auth_cert.h>
45 #include <auth_anon.h>
46 #include <auth_psk.h>
47 #include <gnutls_algorithms.h>
48 #include <gnutls_rsa_export.h>
49 #include <gnutls_extensions.h>
50 #include <system.h>
51
52 /* These should really be static, but src/tests.c calls them.  Make
53    them public functions?  */
54 void
55 _gnutls_rsa_pms_set_version (gnutls_session_t session,
56                              unsigned char major, unsigned char minor);
57
58 void
59 _gnutls_session_cert_type_set (gnutls_session_t session,
60                                gnutls_certificate_type_t ct)
61 {
62   session->security_parameters.cert_type = ct;
63 }
64
65 /**
66  * gnutls_cipher_get:
67  * @session: is a #gnutls_session_t structure.
68  *
69  * Get currently used cipher.
70  *
71  * Returns: the currently used cipher, a #gnutls_cipher_algorithm_t
72  *   type.
73  **/
74 gnutls_cipher_algorithm_t
75 gnutls_cipher_get (gnutls_session_t session)
76 {
77   record_parameters_st *record_params;
78   _gnutls_epoch_get (session, EPOCH_READ_CURRENT, &record_params);
79
80   return record_params->cipher_algorithm;
81 }
82
83 /**
84  * gnutls_certificate_type_get:
85  * @session: is a #gnutls_session_t structure.
86  *
87  * The certificate type is by default X.509, unless it is negotiated
88  * as a TLS extension.
89  *
90  * Returns: the currently used #gnutls_certificate_type_t certificate
91  *   type.
92  **/
93 gnutls_certificate_type_t
94 gnutls_certificate_type_get (gnutls_session_t session)
95 {
96   return session->security_parameters.cert_type;
97 }
98
99 /**
100  * gnutls_kx_get:
101  * @session: is a #gnutls_session_t structure.
102  *
103  * Get currently used key exchange algorithm.
104  *
105  * Returns: the key exchange algorithm used in the last handshake, a
106  *   #gnutls_kx_algorithm_t value.
107  **/
108 gnutls_kx_algorithm_t
109 gnutls_kx_get (gnutls_session_t session)
110 {
111   return session->security_parameters.kx_algorithm;
112 }
113
114 /**
115  * gnutls_mac_get:
116  * @session: is a #gnutls_session_t structure.
117  *
118  * Get currently used MAC algorithm.
119  *
120  * Returns: the currently used mac algorithm, a
121  *   #gnutls_mac_algorithm_t value.
122  **/
123 gnutls_mac_algorithm_t
124 gnutls_mac_get (gnutls_session_t session)
125 {
126   record_parameters_st *record_params;
127   _gnutls_epoch_get (session, EPOCH_READ_CURRENT, &record_params);
128
129   return record_params->mac_algorithm;
130 }
131
132 /**
133  * gnutls_compression_get:
134  * @session: is a #gnutls_session_t structure.
135  *
136  * Get currently used compression algorithm.
137  *
138  * Returns: the currently used compression method, a
139  *   #gnutls_compression_method_t value.
140  **/
141 gnutls_compression_method_t
142 gnutls_compression_get (gnutls_session_t session)
143 {
144   record_parameters_st *record_params;
145   _gnutls_epoch_get (session, EPOCH_READ_CURRENT, &record_params);
146
147   return record_params->compression_algorithm;
148 }
149
150 /* Check if the given certificate type is supported.
151  * This means that it is enabled by the priority functions,
152  * and a matching certificate exists.
153  */
154 int
155 _gnutls_session_cert_type_supported (gnutls_session_t session,
156                                      gnutls_certificate_type_t cert_type)
157 {
158   unsigned i;
159   unsigned cert_found = 0;
160   gnutls_certificate_credentials_t cred;
161
162   if (session->security_parameters.entity == GNUTLS_SERVER)
163     {
164       cred = (gnutls_certificate_credentials_t)
165         _gnutls_get_cred (session->key, GNUTLS_CRD_CERTIFICATE, NULL);
166
167       if (cred == NULL)
168         return GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE;
169
170       if (cred->server_get_cert_callback == NULL
171           && cred->get_cert_callback == NULL)
172         {
173           for (i = 0; i < cred->ncerts; i++)
174             {
175               if (cred->cert_list[i][0].cert_type == cert_type)
176                 {
177                   cert_found = 1;
178                   break;
179                 }
180             }
181
182           if (cert_found == 0)
183             /* no certificate is of that type.
184              */
185             return GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE;
186         }
187     }
188
189   if (session->internals.priorities.cert_type.algorithms == 0
190       && cert_type == DEFAULT_CERT_TYPE)
191     return 0;
192
193   for (i = 0; i < session->internals.priorities.cert_type.algorithms; i++)
194     {
195       if (session->internals.priorities.cert_type.priority[i] == cert_type)
196         {
197           return 0;             /* ok */
198         }
199     }
200
201   return GNUTLS_E_UNSUPPORTED_CERTIFICATE_TYPE;
202 }
203
204
205 /* this function deinitializes all the internal parameters stored
206  * in a session struct.
207  */
208 inline static void
209 deinit_internal_params (gnutls_session_t session)
210 {
211   if (session->internals.params.free_dh_params)
212     gnutls_dh_params_deinit (session->internals.params.dh_params);
213
214   if (session->internals.params.free_rsa_params)
215     gnutls_rsa_params_deinit (session->internals.params.rsa_params);
216
217   _gnutls_handshake_hash_buffers_clear (session);
218
219   memset (&session->internals.params, 0, sizeof (session->internals.params));
220 }
221
222 /* This function will clear all the variables in internals
223  * structure within the session, which depend on the current handshake.
224  * This is used to allow further handshakes.
225  */
226 static void
227 _gnutls_handshake_internal_state_init (gnutls_session_t session)
228 {
229   session->internals.extensions_sent_size = 0;
230
231   /* by default no selected certificate */
232   session->internals.adv_version_major = 0;
233   session->internals.adv_version_minor = 0;
234   session->internals.v2_hello = 0;
235   memset (&session->internals.handshake_header_buffer, 0,
236           sizeof (handshake_header_buffer_st));
237   session->internals.direction = 0;
238
239   /* use out of band data for the last
240    * handshake messages received.
241    */
242   session->internals.last_handshake_in = -1;
243   session->internals.last_handshake_out = -1;
244
245   session->internals.resumable = RESUME_TRUE;
246 }
247
248 void
249 _gnutls_handshake_internal_state_clear (gnutls_session_t session)
250 {
251   _gnutls_handshake_internal_state_init (session);
252
253   _gnutls_free_datum (&session->internals.recv_buffer);
254
255   deinit_internal_params (session);
256
257 }
258
259 #define MIN_DH_BITS 727
260 /**
261  * gnutls_init:
262  * @con_end: indicate if this session is to be used for server or client.
263  * @session: is a pointer to a #gnutls_session_t structure.
264  *
265  * This function initializes the current session to null. Every
266  * session must be initialized before use, so internal structures can
267  * be allocated.  This function allocates structures which can only
268  * be free'd by calling gnutls_deinit().  Returns zero on success.
269  *
270  * @con_end can be one of %GNUTLS_CLIENT and %GNUTLS_SERVER.
271  *
272  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
273  **/
274 int
275 gnutls_init (gnutls_session_t * session, gnutls_connection_end_t con_end)
276 {
277   int ret;
278   record_parameters_st *epoch;
279
280   *session = gnutls_calloc (1, sizeof (struct gnutls_session_int));
281   if (*session == NULL)
282     return GNUTLS_E_MEMORY_ERROR;
283
284   ret = _gnutls_epoch_alloc (*session, 0, &epoch);
285   if (ret < 0)
286     {
287       gnutls_assert ();
288       return GNUTLS_E_MEMORY_ERROR;
289     }
290
291   /* Set all NULL algos on epoch 0 */
292   _gnutls_epoch_set_null_algos (*session, epoch);
293
294   (*session)->security_parameters.epoch_next = 1;
295
296   (*session)->security_parameters.entity = con_end;
297
298   /* the default certificate type for TLS */
299   (*session)->security_parameters.cert_type = DEFAULT_CERT_TYPE;
300
301   /* Initialize buffers */
302   _gnutls_buffer_init (&(*session)->internals.application_data_buffer);
303   _gnutls_buffer_init (&(*session)->internals.handshake_data_buffer);
304   _gnutls_buffer_init (&(*session)->internals.handshake_hash_buffer);
305   _gnutls_buffer_init (&(*session)->internals.ia_data_buffer);
306
307   _mbuffer_init (&(*session)->internals.record_send_buffer);
308   _mbuffer_init (&(*session)->internals.record_recv_buffer);
309
310   _mbuffer_init (&(*session)->internals.handshake_send_buffer);
311   _gnutls_buffer_init (&(*session)->internals.handshake_recv_buffer);
312
313   (*session)->key = gnutls_calloc (1, sizeof (struct gnutls_key_st));
314   if ((*session)->key == NULL)
315     {
316       gnutls_free (*session);
317       *session = NULL;
318       return GNUTLS_E_MEMORY_ERROR;
319     }
320
321   (*session)->internals.expire_time = DEFAULT_EXPIRE_TIME;      /* one hour default */
322
323   gnutls_dh_set_prime_bits ((*session), MIN_DH_BITS);
324
325   gnutls_transport_set_lowat ((*session), DEFAULT_LOWAT);       /* the default for tcp */
326
327   gnutls_handshake_set_max_packet_length ((*session),
328                                           MAX_HANDSHAKE_PACKET_SIZE);
329
330   /* set the socket pointers to -1;
331    */
332   (*session)->internals.transport_recv_ptr = (gnutls_transport_ptr_t) - 1;
333   (*session)->internals.transport_send_ptr = (gnutls_transport_ptr_t) - 1;
334
335   /* set the default maximum record size for TLS
336    */
337   (*session)->security_parameters.max_record_recv_size =
338     DEFAULT_MAX_RECORD_SIZE;
339   (*session)->security_parameters.max_record_send_size =
340     DEFAULT_MAX_RECORD_SIZE;
341
342   /* everything else not initialized here is initialized
343    * as NULL or 0. This is why calloc is used.
344    */
345
346   _gnutls_handshake_internal_state_init (*session);
347
348   /* emulate old gnutls behavior for old applications that do not use the priority_*
349    * functions.
350    */
351   (*session)->internals.priorities.sr = SR_PARTIAL;
352
353 #ifdef HAVE_WRITEV
354   gnutls_transport_set_vec_push_function (*session, system_writev);
355 #else
356   gnutls_transport_set_push_function (*session, system_write);
357 #endif
358   gnutls_transport_set_pull_function (*session, system_read);
359   gnutls_transport_set_errno_function (*session, system_errno);
360
361   return 0;
362 }
363
364 /* returns RESUME_FALSE or RESUME_TRUE.
365  */
366 int
367 _gnutls_session_is_resumable (gnutls_session_t session)
368 {
369   return session->internals.resumable;
370 }
371
372
373 /**
374  * gnutls_deinit:
375  * @session: is a #gnutls_session_t structure.
376  *
377  * This function clears all buffers associated with the @session.
378  * This function will also remove session data from the session
379  * database if the session was terminated abnormally.
380  **/
381 void
382 gnutls_deinit (gnutls_session_t session)
383 {
384   unsigned int i;
385
386   if (session == NULL)
387     return;
388
389   /* remove auth info firstly */
390   _gnutls_free_auth_info (session);
391
392   _gnutls_handshake_internal_state_clear (session);
393   _gnutls_handshake_io_buffer_clear (session);
394   _gnutls_ext_free_session_data (session);
395
396   for (i = 0; i < MAX_EPOCH_INDEX; i++)
397     if (session->record_parameters[i] != NULL)
398       {
399         _gnutls_epoch_free (session, session->record_parameters[i]);
400         session->record_parameters[i] = NULL;
401       }
402
403   _gnutls_buffer_clear (&session->internals.ia_data_buffer);
404   _gnutls_buffer_clear (&session->internals.handshake_hash_buffer);
405   _gnutls_buffer_clear (&session->internals.handshake_data_buffer);
406   _gnutls_buffer_clear (&session->internals.application_data_buffer);
407   _mbuffer_clear (&session->internals.record_recv_buffer);
408   _mbuffer_clear (&session->internals.record_send_buffer);
409
410   gnutls_credentials_clear (session);
411   _gnutls_selected_certs_deinit (session);
412
413   if (session->key != NULL)
414     {
415       _gnutls_mpi_release (&session->key->KEY);
416       _gnutls_mpi_release (&session->key->client_Y);
417       _gnutls_mpi_release (&session->key->client_p);
418       _gnutls_mpi_release (&session->key->client_g);
419
420       _gnutls_mpi_release (&session->key->u);
421       _gnutls_mpi_release (&session->key->a);
422       _gnutls_mpi_release (&session->key->x);
423       _gnutls_mpi_release (&session->key->A);
424       _gnutls_mpi_release (&session->key->B);
425       _gnutls_mpi_release (&session->key->b);
426
427       /* RSA */
428       _gnutls_mpi_release (&session->key->rsa[0]);
429       _gnutls_mpi_release (&session->key->rsa[1]);
430
431       _gnutls_mpi_release (&session->key->dh_secret);
432       gnutls_free (session->key);
433
434       session->key = NULL;
435     }
436
437   memset (session, 0, sizeof (struct gnutls_session_int));
438   gnutls_free (session);
439 }
440
441 /* Returns the minimum prime bits that are acceptable.
442  */
443 int
444 _gnutls_dh_get_allowed_prime_bits (gnutls_session_t session)
445 {
446   return session->internals.dh_prime_bits;
447 }
448
449 int
450 _gnutls_dh_set_peer_public (gnutls_session_t session, bigint_t public)
451 {
452   dh_info_st *dh;
453   int ret;
454
455   switch (gnutls_auth_get_type (session))
456     {
457     case GNUTLS_CRD_ANON:
458       {
459         anon_auth_info_t info;
460         info = _gnutls_get_auth_info (session);
461         if (info == NULL)
462           return GNUTLS_E_INTERNAL_ERROR;
463
464         dh = &info->dh;
465         break;
466       }
467     case GNUTLS_CRD_PSK:
468       {
469         psk_auth_info_t info;
470         info = _gnutls_get_auth_info (session);
471         if (info == NULL)
472           return GNUTLS_E_INTERNAL_ERROR;
473
474         dh = &info->dh;
475         break;
476       }
477     case GNUTLS_CRD_CERTIFICATE:
478       {
479         cert_auth_info_t info;
480
481         info = _gnutls_get_auth_info (session);
482         if (info == NULL)
483           return GNUTLS_E_INTERNAL_ERROR;
484
485         dh = &info->dh;
486         break;
487       }
488     default:
489       gnutls_assert ();
490       return GNUTLS_E_INTERNAL_ERROR;
491     }
492
493   if (dh->public_key.data)
494     _gnutls_free_datum (&dh->public_key);
495
496   ret = _gnutls_mpi_dprint_lz (public, &dh->public_key);
497   if (ret < 0)
498     {
499       gnutls_assert ();
500       return ret;
501     }
502
503   return 0;
504 }
505
506 int
507 _gnutls_dh_set_secret_bits (gnutls_session_t session, unsigned bits)
508 {
509   switch (gnutls_auth_get_type (session))
510     {
511     case GNUTLS_CRD_ANON:
512       {
513         anon_auth_info_t info;
514         info = _gnutls_get_auth_info (session);
515         if (info == NULL)
516           return GNUTLS_E_INTERNAL_ERROR;
517         info->dh.secret_bits = bits;
518         break;
519       }
520     case GNUTLS_CRD_PSK:
521       {
522         psk_auth_info_t info;
523         info = _gnutls_get_auth_info (session);
524         if (info == NULL)
525           return GNUTLS_E_INTERNAL_ERROR;
526         info->dh.secret_bits = bits;
527         break;
528       }
529     case GNUTLS_CRD_CERTIFICATE:
530       {
531         cert_auth_info_t info;
532
533         info = _gnutls_get_auth_info (session);
534         if (info == NULL)
535           return GNUTLS_E_INTERNAL_ERROR;
536
537         info->dh.secret_bits = bits;
538         break;
539     default:
540         gnutls_assert ();
541         return GNUTLS_E_INTERNAL_ERROR;
542       }
543     }
544
545   return 0;
546 }
547
548 /* This function will set in the auth info structure the
549  * RSA exponent and the modulus.
550  */
551 int
552 _gnutls_rsa_export_set_pubkey (gnutls_session_t session,
553                                bigint_t exponent, bigint_t modulus)
554 {
555   cert_auth_info_t info;
556   int ret;
557
558   info = _gnutls_get_auth_info (session);
559   if (info == NULL)
560     return GNUTLS_E_INTERNAL_ERROR;
561
562   if (info->rsa_export.modulus.data)
563     _gnutls_free_datum (&info->rsa_export.modulus);
564
565   if (info->rsa_export.exponent.data)
566     _gnutls_free_datum (&info->rsa_export.exponent);
567
568   ret = _gnutls_mpi_dprint_lz (modulus, &info->rsa_export.modulus);
569   if (ret < 0)
570     {
571       gnutls_assert ();
572       return ret;
573     }
574
575   ret = _gnutls_mpi_dprint_lz (exponent, &info->rsa_export.exponent);
576   if (ret < 0)
577     {
578       gnutls_assert ();
579       _gnutls_free_datum (&info->rsa_export.modulus);
580       return ret;
581     }
582
583   return 0;
584 }
585
586
587 /* Sets the prime and the generator in the auth info structure.
588  */
589 int
590 _gnutls_dh_set_group (gnutls_session_t session, bigint_t gen, bigint_t prime)
591 {
592   dh_info_st *dh;
593   int ret;
594
595   switch (gnutls_auth_get_type (session))
596     {
597     case GNUTLS_CRD_ANON:
598       {
599         anon_auth_info_t info;
600         info = _gnutls_get_auth_info (session);
601         if (info == NULL)
602           return GNUTLS_E_INTERNAL_ERROR;
603
604         dh = &info->dh;
605         break;
606       }
607     case GNUTLS_CRD_PSK:
608       {
609         psk_auth_info_t info;
610         info = _gnutls_get_auth_info (session);
611         if (info == NULL)
612           return GNUTLS_E_INTERNAL_ERROR;
613
614         dh = &info->dh;
615         break;
616       }
617     case GNUTLS_CRD_CERTIFICATE:
618       {
619         cert_auth_info_t info;
620
621         info = _gnutls_get_auth_info (session);
622         if (info == NULL)
623           return GNUTLS_E_INTERNAL_ERROR;
624
625         dh = &info->dh;
626         break;
627       }
628     default:
629       gnutls_assert ();
630       return GNUTLS_E_INTERNAL_ERROR;
631     }
632
633   if (dh->prime.data)
634     _gnutls_free_datum (&dh->prime);
635
636   if (dh->generator.data)
637     _gnutls_free_datum (&dh->generator);
638
639   /* prime
640    */
641   ret = _gnutls_mpi_dprint_lz (prime, &dh->prime);
642   if (ret < 0)
643     {
644       gnutls_assert ();
645       return ret;
646     }
647
648   /* generator
649    */
650   ret = _gnutls_mpi_dprint_lz (gen, &dh->generator);
651   if (ret < 0)
652     {
653       gnutls_assert ();
654       _gnutls_free_datum (&dh->prime);
655       return ret;
656     }
657
658   return 0;
659 }
660
661 #ifdef ENABLE_OPENPGP
662 /**
663  * gnutls_openpgp_send_cert:
664  * @session: is a pointer to a #gnutls_session_t structure.
665  * @status: is one of GNUTLS_OPENPGP_CERT, or GNUTLS_OPENPGP_CERT_FINGERPRINT
666  *
667  * This function will order gnutls to send the key fingerprint
668  * instead of the key in the initial handshake procedure. This should
669  * be used with care and only when there is indication or knowledge
670  * that the server can obtain the client's key.
671  **/
672 void
673 gnutls_openpgp_send_cert (gnutls_session_t session,
674                           gnutls_openpgp_crt_status_t status)
675 {
676   session->internals.pgp_fingerprint = status;
677 }
678 #endif
679
680 /**
681  * gnutls_certificate_send_x509_rdn_sequence:
682  * @session: is a pointer to a #gnutls_session_t structure.
683  * @status: is 0 or 1
684  *
685  * If status is non zero, this function will order gnutls not to send
686  * the rdnSequence in the certificate request message. That is the
687  * server will not advertize it's trusted CAs to the peer. If status
688  * is zero then the default behaviour will take effect, which is to
689  * advertize the server's trusted CAs.
690  *
691  * This function has no effect in clients, and in authentication
692  * methods other than certificate with X.509 certificates.
693  **/
694 void
695 gnutls_certificate_send_x509_rdn_sequence (gnutls_session_t session,
696                                            int status)
697 {
698   session->internals.ignore_rdn_sequence = status;
699 }
700
701 #ifdef ENABLE_OPENPGP
702 int
703 _gnutls_openpgp_send_fingerprint (gnutls_session_t session)
704 {
705   return session->internals.pgp_fingerprint;
706 }
707 #endif
708
709 /*-
710  * _gnutls_record_set_default_version - Used to set the default version for the first record packet
711  * @session: is a #gnutls_session_t structure.
712  * @major: is a tls major version
713  * @minor: is a tls minor version
714  *
715  * This function sets the default version that we will use in the first
716  * record packet (client hello). This function is only useful to people
717  * that know TLS internals and want to debug other implementations.
718  -*/
719 void
720 _gnutls_record_set_default_version (gnutls_session_t session,
721                                     unsigned char major, unsigned char minor)
722 {
723   session->internals.default_record_version[0] = major;
724   session->internals.default_record_version[1] = minor;
725 }
726
727 /**
728  * gnutls_handshake_set_private_extensions:
729  * @session: is a #gnutls_session_t structure.
730  * @allow: is an integer (0 or 1)
731  *
732  * This function will enable or disable the use of private cipher
733  * suites (the ones that start with 0xFF).  By default or if @allow
734  * is 0 then these cipher suites will not be advertized nor used.
735  *
736  * Unless this function is called with the option to allow (1), then
737  * no compression algorithms, like LZO.  That is because these
738  * algorithms are not yet defined in any RFC or even internet draft.
739  *
740  * Enabling the private ciphersuites when talking to other than
741  * gnutls servers and clients may cause interoperability problems.
742  **/
743 void
744 gnutls_handshake_set_private_extensions (gnutls_session_t session, int allow)
745 {
746   session->internals.enable_private = allow;
747 }
748
749 inline static int
750 _gnutls_cal_PRF_A (gnutls_mac_algorithm_t algorithm,
751                    const void *secret, int secret_size,
752                    const void *seed, int seed_size, void *result)
753 {
754   digest_hd_st td1;
755   int ret;
756
757   ret = _gnutls_hmac_init (&td1, algorithm, secret, secret_size);
758   if (ret < 0)
759     {
760       gnutls_assert ();
761       return ret;
762     }
763
764   _gnutls_hmac (&td1, seed, seed_size);
765   _gnutls_hmac_deinit (&td1, result);
766
767   return 0;
768 }
769
770 #define MAX_SEED_SIZE 200
771
772 /* Produces "total_bytes" bytes using the hash algorithm specified.
773  * (used in the PRF function)
774  */
775 static int
776 _gnutls_P_hash (gnutls_mac_algorithm_t algorithm,
777                 const opaque * secret, int secret_size,
778                 const opaque * seed, int seed_size,
779                 int total_bytes, opaque * ret)
780 {
781
782   digest_hd_st td2;
783   int i, times, how, blocksize, A_size;
784   opaque final[MAX_HASH_SIZE], Atmp[MAX_SEED_SIZE];
785   int output_bytes, result;
786
787   if (seed_size > MAX_SEED_SIZE || total_bytes <= 0)
788     {
789       gnutls_assert ();
790       return GNUTLS_E_INTERNAL_ERROR;
791     }
792
793   blocksize = _gnutls_hmac_get_algo_len (algorithm);
794
795   output_bytes = 0;
796   do
797     {
798       output_bytes += blocksize;
799     }
800   while (output_bytes < total_bytes);
801
802   /* calculate A(0) */
803
804   memcpy (Atmp, seed, seed_size);
805   A_size = seed_size;
806
807   times = output_bytes / blocksize;
808
809   for (i = 0; i < times; i++)
810     {
811       result = _gnutls_hmac_init (&td2, algorithm, secret, secret_size);
812       if (result < 0)
813         {
814           gnutls_assert ();
815           return result;
816         }
817
818       /* here we calculate A(i+1) */
819       if ((result =
820            _gnutls_cal_PRF_A (algorithm, secret, secret_size, Atmp,
821                               A_size, Atmp)) < 0)
822         {
823           gnutls_assert ();
824           _gnutls_hmac_deinit (&td2, final);
825           return result;
826         }
827
828       A_size = blocksize;
829
830       _gnutls_hmac (&td2, Atmp, A_size);
831       _gnutls_hmac (&td2, seed, seed_size);
832       _gnutls_hmac_deinit (&td2, final);
833
834       if ((1 + i) * blocksize < total_bytes)
835         {
836           how = blocksize;
837         }
838       else
839         {
840           how = total_bytes - (i) * blocksize;
841         }
842
843       if (how > 0)
844         {
845           memcpy (&ret[i * blocksize], final, how);
846         }
847     }
848
849   return 0;
850 }
851
852 /* Xor's two buffers and puts the output in the first one.
853  */
854 inline static void
855 _gnutls_xor (opaque * o1, opaque * o2, int length)
856 {
857   int i;
858   for (i = 0; i < length; i++)
859     {
860       o1[i] ^= o2[i];
861     }
862 }
863
864
865
866 #define MAX_PRF_BYTES 200
867
868 /* The PRF function expands a given secret 
869  * needed by the TLS specification. ret must have a least total_bytes
870  * available.
871  */
872 int
873 _gnutls_PRF (gnutls_session_t session,
874              const opaque * secret, int secret_size, const char *label,
875              int label_size, const opaque * seed, int seed_size,
876              int total_bytes, void *ret)
877 {
878   int l_s, s_seed_size;
879   const opaque *s1, *s2;
880   opaque s_seed[MAX_SEED_SIZE];
881   opaque o1[MAX_PRF_BYTES], o2[MAX_PRF_BYTES];
882   int result;
883   gnutls_protocol_t ver = gnutls_protocol_get_version (session);
884
885   if (total_bytes > MAX_PRF_BYTES)
886     {
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     {
895       gnutls_assert ();
896       return GNUTLS_E_INTERNAL_ERROR;
897     }
898
899   memcpy (s_seed, label, label_size);
900   memcpy (&s_seed[label_size], seed, seed_size);
901
902   if (_gnutls_version_has_selectable_prf (ver))
903     {
904       result =
905         _gnutls_P_hash (GNUTLS_MAC_SHA256, secret, secret_size,
906                         s_seed, s_seed_size, total_bytes, ret);
907       if (result < 0)
908         {
909           gnutls_assert ();
910           return result;
911         }
912     }
913   else
914     {
915       l_s = secret_size / 2;
916
917       s1 = &secret[0];
918       s2 = &secret[l_s];
919
920       if (secret_size % 2 != 0)
921         {
922           l_s++;
923         }
924
925       result =
926         _gnutls_P_hash (GNUTLS_MAC_MD5, s1, l_s, s_seed, s_seed_size,
927                         total_bytes, o1);
928       if (result < 0)
929         {
930           gnutls_assert ();
931           return result;
932         }
933
934       result =
935         _gnutls_P_hash (GNUTLS_MAC_SHA1, s2, l_s, s_seed, s_seed_size,
936                         total_bytes, o2);
937       if (result < 0)
938         {
939           gnutls_assert ();
940           return result;
941         }
942
943       _gnutls_xor (o1, o2, total_bytes);
944
945       memcpy (ret, o1, total_bytes);
946     }
947
948   return 0;                     /* ok */
949
950 }
951
952 /**
953  * gnutls_prf_raw:
954  * @session: is a #gnutls_session_t structure.
955  * @label_size: length of the @label variable.
956  * @label: label used in PRF computation, typically a short string.
957  * @seed_size: length of the @seed variable.
958  * @seed: optional extra data to seed the PRF with.
959  * @outsize: size of pre-allocated output buffer to hold the output.
960  * @out: pre-allocate buffer to hold the generated data.
961  *
962  * Apply the TLS Pseudo-Random-Function (PRF) using the master secret
963  * on some data.
964  *
965  * The @label variable usually contain a string denoting the purpose
966  * for the generated data.  The @seed usually contain data such as the
967  * client and server random, perhaps together with some additional
968  * data that is added to guarantee uniqueness of the output for a
969  * particular purpose.
970  *
971  * Because the output is not guaranteed to be unique for a particular
972  * session unless @seed include the client random and server random
973  * fields (the PRF would output the same data on another connection
974  * resumed from the first one), it is not recommended to use this
975  * function directly.  The gnutls_prf() function seed the PRF with the
976  * client and server random fields directly, and is recommended if you
977  * want to generate pseudo random data unique for each session.
978  *
979  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
980  **/
981 int
982 gnutls_prf_raw (gnutls_session_t session,
983                 size_t label_size,
984                 const char *label,
985                 size_t seed_size, const char *seed, size_t outsize, char *out)
986 {
987   int ret;
988
989   ret = _gnutls_PRF (session,
990                      session->security_parameters.master_secret,
991                      GNUTLS_MASTER_SIZE,
992                      label,
993                      label_size, (opaque *) seed, seed_size, outsize, out);
994
995   return ret;
996 }
997
998 /**
999  * gnutls_prf:
1000  * @session: is a #gnutls_session_t structure.
1001  * @label_size: length of the @label variable.
1002  * @label: label used in PRF computation, typically a short string.
1003  * @server_random_first: non-0 if server random field should be first in seed
1004  * @extra_size: length of the @extra variable.
1005  * @extra: optional extra data to seed the PRF with.
1006  * @outsize: size of pre-allocated output buffer to hold the output.
1007  * @out: pre-allocate buffer to hold the generated data.
1008  *
1009  * Apply the TLS Pseudo-Random-Function (PRF) using the master secret
1010  * on some data, seeded with the client and server random fields.
1011  *
1012  * The @label variable usually contain a string denoting the purpose
1013  * for the generated data.  The @server_random_first indicate whether
1014  * the client random field or the server random field should be first
1015  * in the seed.  Non-0 indicate that the server random field is first,
1016  * 0 that the client random field is first.
1017  *
1018  * The @extra variable can be used to add more data to the seed, after
1019  * the random variables.  It can be used to tie make sure the
1020  * generated output is strongly connected to some additional data
1021  * (e.g., a string used in user authentication).
1022  *
1023  * The output is placed in *@OUT, which must be pre-allocated.
1024  *
1025  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
1026  **/
1027 int
1028 gnutls_prf (gnutls_session_t session,
1029             size_t label_size,
1030             const char *label,
1031             int server_random_first,
1032             size_t extra_size, const char *extra, size_t outsize, char *out)
1033 {
1034   int ret;
1035   opaque *seed;
1036   size_t seedsize = 2 * GNUTLS_RANDOM_SIZE + extra_size;
1037
1038   seed = gnutls_malloc (seedsize);
1039   if (!seed)
1040     {
1041       gnutls_assert ();
1042       return GNUTLS_E_MEMORY_ERROR;
1043     }
1044
1045   memcpy (seed, server_random_first ?
1046           session->security_parameters.server_random :
1047           session->security_parameters.client_random, GNUTLS_RANDOM_SIZE);
1048   memcpy (seed + GNUTLS_RANDOM_SIZE, server_random_first ?
1049           session->security_parameters.client_random :
1050           session->security_parameters.server_random, GNUTLS_RANDOM_SIZE);
1051
1052   memcpy (seed + 2 * GNUTLS_RANDOM_SIZE, extra, extra_size);
1053
1054   ret = _gnutls_PRF (session, session->security_parameters.master_secret,
1055                      GNUTLS_MASTER_SIZE,
1056                      label, label_size, seed, seedsize, outsize, out);
1057
1058   gnutls_free (seed);
1059
1060   return ret;
1061 }
1062
1063 /*-
1064  * gnutls_session_get_client_random:
1065  * @session: is a #gnutls_session_t structure.
1066  *
1067  * Return a pointer to the 32-byte client random field used in the
1068  * session.  The pointer must not be modified or deallocated.
1069  *
1070  * If a client random value has not yet been established, the output
1071  * will be garbage; in particular, a %NULL return value should not be
1072  * expected.
1073  *
1074  * Returns: pointer to client random data.
1075  *
1076  * Deprecated in: 2.11.0
1077  -*/
1078 const void *
1079 gnutls_session_get_client_random (gnutls_session_t session)
1080 {
1081   return (char *) session->security_parameters.client_random;
1082 }
1083
1084 /*-
1085  * gnutls_session_get_server_random:
1086  * @session: is a #gnutls_session_t structure.
1087  *
1088  * Return a pointer to the 32-byte server random field used in the
1089  * session.  The pointer must not be modified or deallocated.
1090  *
1091  * If a server random value has not yet been established, the output
1092  * will be garbage; in particular, a %NULL return value should not be
1093  * expected.
1094  *
1095  * Returns: pointer to server random data.
1096  *
1097  * Deprecated in: 2.11.0
1098  -*/
1099 const void *
1100 gnutls_session_get_server_random (gnutls_session_t session)
1101 {
1102   return (char *) session->security_parameters.server_random;
1103 }
1104
1105 /*-
1106  * gnutls_session_get_master_secret:
1107  * @session: is a #gnutls_session_t structure.
1108  *
1109  * Return a pointer to the 48-byte master secret in the session.  The
1110  * pointer must not be modified or deallocated.
1111  *
1112  * If a master secret value has not yet been established, the output
1113  * will be garbage; in particular, a %NULL return value should not be
1114  * expected.
1115  *
1116  * Consider using gnutls_prf() rather than extracting the master
1117  * secret and use it to derive further data.
1118  *
1119  * Returns: pointer to master secret data.
1120  *
1121  * Deprecated in: 2.11.0
1122  -*/
1123 const void *
1124 gnutls_session_get_master_secret (gnutls_session_t session)
1125 {
1126   return (char *) session->security_parameters.master_secret;
1127 }
1128
1129 /*-
1130  * gnutls_session_set_finished_function:
1131  * @session: is a #gnutls_session_t structure.
1132  * @func: a #gnutls_finished_callback_func callback.
1133  *
1134  * Register a callback function for the session that will be called
1135  * when a TLS Finished message has been generated.  The function is
1136  * typically used to copy away the TLS finished message for later use
1137  * as a channel binding or similar purpose.
1138  *
1139  * The callback should follow this prototype:
1140  *
1141  * void callback (gnutls_session_t @session, const void *@finished, size_t @len);
1142  *
1143  * The @finished parameter will contain the binary TLS finished
1144  * message, and @len will contains its length.  For SSLv3 connections,
1145  * the @len parameter will be 36 and for TLS connections it will be
1146  * 12.
1147  *
1148  * It is recommended that the function returns quickly in order to not
1149  * delay the handshake.  Use the function to store a copy of the TLS
1150  * finished message for later use.
1151  *
1152  * Since: 2.6.0
1153  * Deprecated in: 2.11.0
1154  -*/
1155 void
1156 gnutls_session_set_finished_function (gnutls_session_t session,
1157                                       gnutls_finished_callback_func func)
1158 {
1159   session->internals.finished_func = func;
1160 }
1161
1162 /**
1163  * gnutls_session_is_resumed:
1164  * @session: is a #gnutls_session_t structure.
1165  *
1166  * Check whether session is resumed or not.
1167  *
1168  * Returns: non zero if this session is resumed, or a zero if this is
1169  *   a new session.
1170  **/
1171 int
1172 gnutls_session_is_resumed (gnutls_session_t session)
1173 {
1174   if (session->security_parameters.entity == GNUTLS_CLIENT)
1175     {
1176       if (session->security_parameters.session_id_size > 0 &&
1177           session->security_parameters.session_id_size ==
1178           session->internals.resumed_security_parameters.session_id_size
1179           && memcmp (session->security_parameters.session_id,
1180                      session->internals.
1181                      resumed_security_parameters.session_id,
1182                      session->security_parameters.session_id_size) == 0)
1183         return 1;
1184     }
1185   else
1186     {
1187       if (session->internals.resumed == RESUME_TRUE)
1188         return 1;
1189     }
1190
1191   return 0;
1192 }
1193
1194 /*-
1195  * _gnutls_session_is_export - Used to check whether this session is of export grade
1196  * @session: is a #gnutls_session_t structure.
1197  *
1198  * This function will return non zero if this session is of export grade.
1199  -*/
1200 int
1201 _gnutls_session_is_export (gnutls_session_t session)
1202 {
1203   gnutls_cipher_algorithm_t cipher;
1204
1205   cipher =
1206     _gnutls_cipher_suite_get_cipher_algo (&session->
1207                                           security_parameters.current_cipher_suite);
1208
1209   if (_gnutls_cipher_get_export_flag (cipher) != 0)
1210     return 1;
1211
1212   return 0;
1213 }
1214
1215 /*-
1216  * _gnutls_session_is_psk - Used to check whether this session uses PSK kx
1217  * @session: is a #gnutls_session_t structure.
1218  *
1219  * This function will return non zero if this session uses a PSK key
1220  * exchange algorithm.
1221  -*/
1222 int
1223 _gnutls_session_is_psk (gnutls_session_t session)
1224 {
1225   gnutls_kx_algorithm_t kx;
1226
1227   kx =
1228     _gnutls_cipher_suite_get_kx_algo (&session->
1229                                       security_parameters.current_cipher_suite);
1230   if (kx == GNUTLS_KX_PSK || kx == GNUTLS_KX_DHE_PSK)
1231     return 1;
1232
1233   return 0;
1234 }
1235
1236 /**
1237  * gnutls_session_get_ptr:
1238  * @session: is a #gnutls_session_t structure.
1239  *
1240  * Get user pointer for session.  Useful in callbacks.  This is the
1241  *   pointer set with gnutls_session_set_ptr().
1242  *
1243  * Returns: the user given pointer from the session structure, or
1244  *   %NULL if it was never set.
1245  **/
1246 void *
1247 gnutls_session_get_ptr (gnutls_session_t session)
1248 {
1249   return session->internals.user_ptr;
1250 }
1251
1252 /**
1253  * gnutls_session_set_ptr:
1254  * @session: is a #gnutls_session_t structure.
1255  * @ptr: is the user pointer
1256  *
1257  * This function will set (associate) the user given pointer @ptr to
1258  * the session structure.  This is pointer can be accessed with
1259  * gnutls_session_get_ptr().
1260  **/
1261 void
1262 gnutls_session_set_ptr (gnutls_session_t session, void *ptr)
1263 {
1264   session->internals.user_ptr = ptr;
1265 }
1266
1267
1268 /**
1269  * gnutls_record_get_direction:
1270  * @session: is a #gnutls_session_t structure.
1271  *
1272  * This function provides information about the internals of the
1273  * record protocol and is only useful if a prior gnutls function call
1274  * (e.g.  gnutls_handshake()) was interrupted for some reason, that
1275  * is, if a function returned %GNUTLS_E_INTERRUPTED or
1276  * %GNUTLS_E_AGAIN.  In such a case, you might want to call select()
1277  * or poll() before calling the interrupted gnutls function again.  To
1278  * tell you whether a file descriptor should be selected for either
1279  * reading or writing, gnutls_record_get_direction() returns 0 if the
1280  * interrupted function was trying to read data, and 1 if it was
1281  * trying to write data.
1282  *
1283  * Returns: 0 if trying to read data, 1 if trying to write data.
1284  **/
1285 int
1286 gnutls_record_get_direction (gnutls_session_t session)
1287 {
1288   return session->internals.direction;
1289 }
1290
1291 /*-
1292  * _gnutls_rsa_pms_set_version - Sets a version to be used at the RSA PMS
1293  * @session: is a #gnutls_session_t structure.
1294  * @major: is the major version to use
1295  * @minor: is the minor version to use
1296  *
1297  * This function will set the given version number to be used at the
1298  * RSA PMS secret. This is only useful to clients, which want to
1299  * test server's capabilities.
1300  -*/
1301 void
1302 _gnutls_rsa_pms_set_version (gnutls_session_t session,
1303                              unsigned char major, unsigned char minor)
1304 {
1305   session->internals.rsa_pms_version[0] = major;
1306   session->internals.rsa_pms_version[1] = minor;
1307 }
1308
1309 /**
1310  * gnutls_handshake_set_post_client_hello_function:
1311  * @session: is a #gnutls_session_t structure.
1312  * @func: is the function to be called
1313  *
1314  * This function will set a callback to be called after the client
1315  * hello has been received (callback valid in server side only). This
1316  * allows the server to adjust settings based on received extensions.
1317  *
1318  * Those settings could be ciphersuites, requesting certificate, or
1319  * anything else except for version negotiation (this is done before
1320  * the hello message is parsed).
1321  *
1322  * This callback must return 0 on success or a gnutls error code to
1323  * terminate the handshake.
1324  *
1325  * Warning: You should not use this function to terminate the
1326  * handshake based on client input unless you know what you are
1327  * doing. Before the handshake is finished there is no way to know if
1328  * there is a man-in-the-middle attack being performed.
1329  **/
1330 void
1331 gnutls_handshake_set_post_client_hello_function (gnutls_session_t session,
1332                                                  gnutls_handshake_post_client_hello_func
1333                                                  func)
1334 {
1335   session->internals.user_hello_func = func;
1336 }
1337
1338 /**
1339  * gnutls_session_enable_compatibility_mode:
1340  * @session: is a #gnutls_session_t structure.
1341  *
1342  * This function can be used to disable certain (security) features in
1343  * TLS in order to maintain maximum compatibility with buggy
1344  * clients. It is equivalent to calling:
1345  * gnutls_record_disable_padding()
1346  *
1347  * Normally only servers that require maximum compatibility with
1348  * everything out there, need to call this function.
1349  **/
1350 void
1351 gnutls_session_enable_compatibility_mode (gnutls_session_t session)
1352 {
1353   gnutls_record_disable_padding (session);
1354 }
1355
1356 /**
1357  * gnutls_session_channel_binding:
1358  * @session: is a #gnutls_session_t structure.
1359  * @cbtype: an #gnutls_channel_binding_t enumeration type
1360  * @cb: output buffer array with data
1361  *
1362  * Extract given channel binding data of the @cbtype (e.g.,
1363  * %GNUTLS_CB_TLS_UNIQUE) type.
1364  *
1365  * Returns: %GNUTLS_E_SUCCESS on success,
1366  * %GNUTLS_E_UNIMPLEMENTED_FEATURE if the @cbtype is unsupported,
1367  * %GNUTLS_E_CHANNEL_BINDING_NOT_AVAILABLE if the data is not
1368  * currently available, or an error code.
1369  *
1370  * Since: 2.12.0
1371  **/
1372 int
1373 gnutls_session_channel_binding (gnutls_session_t session,
1374                                 gnutls_channel_binding_t cbtype,
1375                                 gnutls_datum_t * cb)
1376 {
1377   if (cbtype != GNUTLS_CB_TLS_UNIQUE)
1378     return GNUTLS_E_UNIMPLEMENTED_FEATURE;
1379
1380   if (!session->internals.initial_negotiation_completed)
1381     return GNUTLS_E_CHANNEL_BINDING_NOT_AVAILABLE;
1382
1383   cb->size = session->internals.cb_tls_unique_len;
1384   cb->data = gnutls_malloc (cb->size);
1385   if (cb->data == NULL)
1386     return GNUTLS_E_MEMORY_ERROR;
1387
1388   memcpy (cb->data, session->internals.cb_tls_unique, cb->size);
1389
1390   return 0;
1391 }