certtool is able to set certificate policies via a template
[gnutls.git] / lib / gnutls_record.c
bloba361e054211b581830c107f66e0ef1d4ae9d9e73
1 /*
2 * Copyright (C) 2000-2012 Free Software Foundation, Inc.
4 * Author: Nikos Mavrogiannopoulos
6 * This file is part of GnuTLS.
8 * The GnuTLS is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public License
10 * as published by the Free Software Foundation; either version 3 of
11 * the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>
23 /* Functions that are record layer specific, are included in this file.
26 /* allocate this many bytes more when encrypting or decrypting, to
27 * compensate for broken backends such as cryptodev.
29 #define CIPHER_SLACK_SIZE 32
31 #include "gnutls_int.h"
32 #include "gnutls_errors.h"
33 #include "debug.h"
34 #include "gnutls_compress.h"
35 #include "gnutls_cipher.h"
36 #include "gnutls_buffers.h"
37 #include "gnutls_mbuffers.h"
38 #include "gnutls_handshake.h"
39 #include "gnutls_hash_int.h"
40 #include "gnutls_cipher_int.h"
41 #include "algorithms.h"
42 #include "gnutls_db.h"
43 #include "gnutls_auth.h"
44 #include "gnutls_num.h"
45 #include "gnutls_record.h"
46 #include "gnutls_datum.h"
47 #include "gnutls_constate.h"
48 #include "ext/max_record.h"
49 #include <ext/heartbeat.h>
50 #include <gnutls_state.h>
51 #include <gnutls_dtls.h>
52 #include <gnutls_dh.h>
53 #include <random.h>
55 struct tls_record_st {
56 uint16_t header_size;
57 uint8_t version[2];
58 uint64 sequence; /* DTLS */
59 uint16_t length;
60 uint16_t packet_size; /* header_size + length */
61 content_type_t type;
62 uint16_t epoch; /* valid in DTLS only */
63 int v2:1; /* whether an SSLv2 client hello */
64 /* the data */
67 /**
68 * gnutls_record_disable_padding:
69 * @session: is a #gnutls_session_t structure.
71 * Used to disabled padding in TLS 1.0 and above. Normally you do not
72 * need to use this function, but there are buggy clients that
73 * complain if a server pads the encrypted data. This of course will
74 * disable protection against statistical attacks on the data.
76 * Normally only servers that require maximum compatibility with everything
77 * out there, need to call this function.
78 **/
79 void
80 gnutls_record_disable_padding (gnutls_session_t session)
82 session->internals.priorities.no_padding = 1;
85 /**
86 * gnutls_transport_set_ptr:
87 * @session: is a #gnutls_session_t structure.
88 * @ptr: is the value.
90 * Used to set the first argument of the transport function (for push
91 * and pull callbacks). In berkeley style sockets this function will set the
92 * connection descriptor.
93 **/
94 void
95 gnutls_transport_set_ptr (gnutls_session_t session,
96 gnutls_transport_ptr_t ptr)
98 session->internals.transport_recv_ptr = ptr;
99 session->internals.transport_send_ptr = ptr;
103 * gnutls_transport_set_ptr2:
104 * @session: is a #gnutls_session_t structure.
105 * @recv_ptr: is the value for the pull function
106 * @send_ptr: is the value for the push function
108 * Used to set the first argument of the transport function (for push
109 * and pull callbacks). In berkeley style sockets this function will set the
110 * connection descriptor. With this function you can use two different
111 * pointers for receiving and sending.
113 void
114 gnutls_transport_set_ptr2 (gnutls_session_t session,
115 gnutls_transport_ptr_t recv_ptr,
116 gnutls_transport_ptr_t send_ptr)
118 session->internals.transport_send_ptr = send_ptr;
119 session->internals.transport_recv_ptr = recv_ptr;
123 * gnutls_transport_get_ptr:
124 * @session: is a #gnutls_session_t structure.
126 * Used to get the first argument of the transport function (like
127 * PUSH and PULL). This must have been set using
128 * gnutls_transport_set_ptr().
130 * Returns: The first argument of the transport function.
132 gnutls_transport_ptr_t
133 gnutls_transport_get_ptr (gnutls_session_t session)
135 return session->internals.transport_recv_ptr;
139 * gnutls_transport_get_ptr2:
140 * @session: is a #gnutls_session_t structure.
141 * @recv_ptr: will hold the value for the pull function
142 * @send_ptr: will hold the value for the push function
144 * Used to get the arguments of the transport functions (like PUSH
145 * and PULL). These should have been set using
146 * gnutls_transport_set_ptr2().
148 void
149 gnutls_transport_get_ptr2 (gnutls_session_t session,
150 gnutls_transport_ptr_t * recv_ptr,
151 gnutls_transport_ptr_t * send_ptr)
154 *recv_ptr = session->internals.transport_recv_ptr;
155 *send_ptr = session->internals.transport_send_ptr;
159 * gnutls_bye:
160 * @session: is a #gnutls_session_t structure.
161 * @how: is an integer
163 * Terminates the current TLS/SSL connection. The connection should
164 * have been initiated using gnutls_handshake(). @how should be one
165 * of %GNUTLS_SHUT_RDWR, %GNUTLS_SHUT_WR.
167 * In case of %GNUTLS_SHUT_RDWR the TLS session gets
168 * terminated and further receives and sends will be disallowed. If
169 * the return value is zero you may continue using the underlying
170 * transport layer. %GNUTLS_SHUT_RDWR sends an alert containing a close
171 * request and waits for the peer to reply with the same message.
173 * In case of %GNUTLS_SHUT_WR the TLS session gets terminated
174 * and further sends will be disallowed. In order to reuse the
175 * connection you should wait for an EOF from the peer.
176 * %GNUTLS_SHUT_WR sends an alert containing a close request.
178 * Note that not all implementations will properly terminate a TLS
179 * connection. Some of them, usually for performance reasons, will
180 * terminate only the underlying transport layer, and thus not
181 * distinguishing between a malicious party prematurely terminating
182 * the connection and normal termination.
184 * This function may also return %GNUTLS_E_AGAIN or
185 * %GNUTLS_E_INTERRUPTED; cf. gnutls_record_get_direction().
187 * Returns: %GNUTLS_E_SUCCESS on success, or an error code, see
188 * function documentation for entire semantics.
191 gnutls_bye (gnutls_session_t session, gnutls_close_request_t how)
193 int ret = 0;
195 switch (STATE)
197 case STATE0:
198 case STATE60:
199 ret = _gnutls_io_write_flush (session);
200 STATE = STATE60;
201 if (ret < 0)
203 gnutls_assert ();
204 return ret;
207 case STATE61:
208 ret =
209 gnutls_alert_send (session, GNUTLS_AL_WARNING, GNUTLS_A_CLOSE_NOTIFY);
210 STATE = STATE61;
211 if (ret < 0)
213 gnutls_assert ();
214 return ret;
217 case STATE62:
218 STATE = STATE62;
219 if (how == GNUTLS_SHUT_RDWR)
223 ret = _gnutls_recv_int (session, GNUTLS_ALERT, -1, NULL, 0, NULL, 0);
225 while (ret == GNUTLS_E_GOT_APPLICATION_DATA);
227 if (ret >= 0)
228 session->internals.may_not_read = 1;
230 if (ret < 0)
232 gnutls_assert ();
233 return ret;
236 STATE = STATE62;
238 break;
239 default:
240 gnutls_assert ();
241 return GNUTLS_E_INTERNAL_ERROR;
244 STATE = STATE0;
246 session->internals.may_not_write = 1;
247 return 0;
250 inline static void
251 session_invalidate (gnutls_session_t session)
253 session->internals.invalid_connection = 1;
257 inline static void
258 session_unresumable (gnutls_session_t session)
260 session->internals.resumable = RESUME_FALSE;
263 /* returns 0 if session is valid
265 inline static int
266 session_is_valid (gnutls_session_t session)
268 if (session->internals.invalid_connection != 0)
269 return GNUTLS_E_INVALID_SESSION;
271 return 0;
274 /* Copies the record version into the headers. The
275 * version must have 2 bytes at least.
277 inline static void
278 copy_record_version (gnutls_session_t session,
279 gnutls_handshake_description_t htype, uint8_t version[2])
281 gnutls_protocol_t lver;
283 if (session->internals.initial_negotiation_completed || htype != GNUTLS_HANDSHAKE_CLIENT_HELLO
284 || session->internals.default_record_version[0] == 0)
286 lver = gnutls_protocol_get_version (session);
288 version[0] = _gnutls_version_get_major (lver);
289 version[1] = _gnutls_version_get_minor (lver);
291 else
293 version[0] = session->internals.default_record_version[0];
294 version[1] = session->internals.default_record_version[1];
298 /* Increments the sequence value
300 inline static int
301 sequence_increment (gnutls_session_t session,
302 uint64 * value)
304 if (IS_DTLS(session))
306 return _gnutls_uint48pp(value);
308 else
310 return _gnutls_uint64pp(value);
314 /* This function behaves exactly like write(). The only difference is
315 * that it accepts, the gnutls_session_t and the content_type_t of data to
316 * send (if called by the user the Content is specific)
317 * It is intended to transfer data, under the current session.
319 * Oct 30 2001: Removed capability to send data more than MAX_RECORD_SIZE.
320 * This makes the function much easier to read, and more error resistant
321 * (there were cases were the old function could mess everything up).
322 * --nmav
324 * This function may accept a NULL pointer for data, and 0 for size, if
325 * and only if the previous send was interrupted for some reason.
328 ssize_t
329 _gnutls_send_int (gnutls_session_t session, content_type_t type,
330 gnutls_handshake_description_t htype,
331 unsigned int epoch_rel, const void *_data,
332 size_t data_size, unsigned int mflags)
334 mbuffer_st *bufel;
335 ssize_t cipher_size;
336 int retval, ret;
337 int send_data_size;
338 uint8_t headers[MAX_RECORD_HEADER_SIZE];
339 int header_size;
340 const uint8_t *data = _data;
341 record_parameters_st *record_params;
342 record_state_st *record_state;
344 ret = _gnutls_epoch_get (session, epoch_rel, &record_params);
345 if (ret < 0)
346 return gnutls_assert_val(ret);
348 /* Safeguard against processing data with an incomplete cipher state. */
349 if (!record_params->initialized)
350 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
352 record_state = &record_params->write;
354 /* Do not allow null pointer if the send buffer is empty.
355 * If the previous send was interrupted then a null pointer is
356 * ok, and means to resume.
358 if (session->internals.record_send_buffer.byte_length == 0 &&
359 (data_size == 0 && _data == NULL))
361 gnutls_assert ();
362 return GNUTLS_E_INVALID_REQUEST;
365 if (type != GNUTLS_ALERT) /* alert messages are sent anyway */
366 if (session_is_valid (session) || session->internals.may_not_write != 0)
368 gnutls_assert ();
369 return GNUTLS_E_INVALID_SESSION;
372 headers[0] = type;
374 /* Use the default record version, if it is
375 * set.
377 copy_record_version (session, htype, &headers[1]);
379 header_size = RECORD_HEADER_SIZE(session);
380 /* Adjust header length and add sequence for DTLS */
381 if (IS_DTLS(session))
382 memcpy(&headers[3], &record_state->sequence_number.i, 8);
384 _gnutls_record_log
385 ("REC[%p]: Preparing Packet %s(%d) with length: %d\n", session,
386 _gnutls_packet2str (type), type, (int) data_size);
388 if (data_size > MAX_RECORD_SEND_SIZE(session))
390 if (IS_DTLS(session))
392 gnutls_assert ();
393 return GNUTLS_E_LARGE_PACKET;
395 send_data_size = MAX_RECORD_SEND_SIZE(session);
397 else
398 send_data_size = data_size;
400 /* Only encrypt if we don't have data to send
401 * from the previous run. - probably interrupted.
403 if (mflags != 0 && session->internals.record_send_buffer.byte_length > 0)
405 ret = _gnutls_io_write_flush (session);
406 if (ret > 0)
407 cipher_size = ret;
408 else
409 cipher_size = 0;
411 retval = session->internals.record_send_buffer_user_size;
413 else
415 /* now proceed to packet encryption
417 cipher_size = send_data_size + MAX_RECORD_OVERHEAD + CIPHER_SLACK_SIZE;
418 bufel = _mbuffer_alloc (cipher_size, cipher_size);
419 if (bufel == NULL)
420 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
422 ret =
423 _gnutls_encrypt (session, headers, header_size, data,
424 send_data_size, _mbuffer_get_udata_ptr (bufel),
425 cipher_size, type, record_params);
426 if (ret <= 0)
428 gnutls_assert ();
429 if (ret == 0)
430 ret = GNUTLS_E_ENCRYPTION_FAILED;
431 gnutls_free (bufel);
432 return ret; /* error */
435 cipher_size = ret;
436 retval = send_data_size;
437 session->internals.record_send_buffer_user_size = send_data_size;
439 /* increase sequence number
441 if (sequence_increment (session, &record_state->sequence_number) != 0)
443 session_invalidate (session);
444 gnutls_free (bufel);
445 return gnutls_assert_val(GNUTLS_E_RECORD_LIMIT_REACHED);
448 _mbuffer_set_udata_size (bufel, cipher_size);
449 ret = _gnutls_io_write_buffered (session, bufel, mflags);
452 if (ret != cipher_size)
454 /* If we have sent any data then just return
455 * the error value. Do not invalidate the session.
457 if (ret < 0 && gnutls_error_is_fatal (ret) == 0)
458 return gnutls_assert_val(ret);
460 if (ret > 0)
461 ret = gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
463 session_unresumable (session);
464 session->internals.may_not_write = 1;
465 return gnutls_assert_val(ret);
468 session->internals.record_send_buffer_user_size = 0;
470 _gnutls_record_log ("REC[%p]: Sent Packet[%d] %s(%d) in epoch %d and length: %d\n",
471 session,
472 (unsigned int)
473 _gnutls_uint64touint32
474 (&record_state->sequence_number),
475 _gnutls_packet2str (type), type,
476 (int) record_params->epoch,
477 (int) cipher_size);
479 return retval;
482 inline static int
483 check_recv_type (gnutls_session_t session, content_type_t recv_type)
485 switch (recv_type)
487 case GNUTLS_CHANGE_CIPHER_SPEC:
488 case GNUTLS_ALERT:
489 case GNUTLS_HANDSHAKE:
490 case GNUTLS_HEARTBEAT:
491 case GNUTLS_APPLICATION_DATA:
492 return 0;
493 default:
494 gnutls_assert ();
495 _gnutls_audit_log(session, "Received record packet of unknown type %u\n", (unsigned int)recv_type);
496 return GNUTLS_E_UNEXPECTED_PACKET;
502 /* Checks if there are pending data in the record buffers. If there are
503 * then it copies the data.
505 static int
506 check_buffers (gnutls_session_t session, content_type_t type,
507 uint8_t * data, int data_size, void* seq)
509 if ((type == GNUTLS_APPLICATION_DATA ||
510 type == GNUTLS_HANDSHAKE ||
511 type == GNUTLS_CHANGE_CIPHER_SPEC)
512 && _gnutls_record_buffer_get_size (session) > 0)
514 int ret;
515 ret = _gnutls_record_buffer_get (type, session, data, data_size, seq);
516 if (ret < 0)
518 if (IS_DTLS(session))
520 if (ret == GNUTLS_E_UNEXPECTED_PACKET)
522 ret = GNUTLS_E_AGAIN;
525 gnutls_assert ();
526 return ret;
529 return ret;
532 return 0;
537 /* Here we check if the advertized version is the one we
538 * negotiated in the handshake.
540 inline static int
541 record_check_version (gnutls_session_t session,
542 gnutls_handshake_description_t htype, uint8_t version[2])
544 if (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO)
546 /* Reject hello packets with major version higher than 3.
548 if (!(IS_DTLS(session)) && version[0] > 3)
550 gnutls_assert ();
551 _gnutls_record_log
552 ("REC[%p]: INVALID VERSION PACKET: (%d) %d.%d\n", session,
553 htype, version[0], version[1]);
554 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
557 else if (htype != GNUTLS_HANDSHAKE_SERVER_HELLO &&
558 gnutls_protocol_get_version (session) !=
559 _gnutls_version_get (version[0], version[1]))
561 /* Reject record packets that have a different version than the
562 * one negotiated. Note that this version is not protected by any
563 * mac. I don't really think that this check serves any purpose.
565 gnutls_assert ();
566 _gnutls_record_log ("REC[%p]: INVALID VERSION PACKET: (%d) %d.%d\n",
567 session, htype, version[0], version[1]);
569 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
572 return 0;
575 /* This function will check if the received record type is
576 * the one we actually expect and adds it to the proper
577 * buffer. The bufel will be deinitialized after calling
578 * this function, even if it fails.
580 static int
581 record_add_to_buffers (gnutls_session_t session,
582 struct tls_record_st *recv, content_type_t type,
583 gnutls_handshake_description_t htype,
584 uint64* seq,
585 mbuffer_st* bufel)
588 int ret;
590 if ((recv->type == type)
591 && (type == GNUTLS_APPLICATION_DATA ||
592 type == GNUTLS_CHANGE_CIPHER_SPEC ||
593 type == GNUTLS_HANDSHAKE))
595 _gnutls_record_buffer_put (session, type, seq, bufel);
597 /* if we received application data as expected then we
598 * deactivate the async timer */
599 _dtls_async_timer_delete(session);
601 else
603 /* if the expected type is different than the received
605 switch (recv->type)
607 case GNUTLS_ALERT:
608 if (bufel->msg.size < 2)
610 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
611 goto unexpected_packet;
614 _gnutls_record_log
615 ("REC[%p]: Alert[%d|%d] - %s - was received\n", session,
616 bufel->msg.data[0], bufel->msg.data[1], gnutls_alert_get_name ((int) bufel->msg.data[1]));
618 session->internals.last_alert = bufel->msg.data[1];
620 /* if close notify is received and
621 * the alert is not fatal
623 if (bufel->msg.data[1] == GNUTLS_A_CLOSE_NOTIFY && bufel->msg.data[0] != GNUTLS_AL_FATAL)
625 /* If we have been expecting for an alert do
627 session->internals.read_eof = 1;
628 ret = GNUTLS_E_SESSION_EOF;
629 goto cleanup;
631 else
633 /* if the alert is FATAL or WARNING
634 * return the apropriate message
637 gnutls_assert ();
638 ret = GNUTLS_E_WARNING_ALERT_RECEIVED;
639 if (bufel->msg.data[0] == GNUTLS_AL_FATAL)
641 session_unresumable (session);
642 session_invalidate (session);
643 ret = gnutls_assert_val(GNUTLS_E_FATAL_ALERT_RECEIVED);
645 goto cleanup;
647 break;
649 case GNUTLS_CHANGE_CIPHER_SPEC:
650 if (!(IS_DTLS(session)))
651 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
653 _gnutls_record_buffer_put (session, recv->type, seq, bufel);
655 break;
657 case GNUTLS_HEARTBEAT:
658 ret = _gnutls_heartbeat_handle (session, bufel);
659 goto cleanup;
661 case GNUTLS_APPLICATION_DATA:
662 if (session->internals.initial_negotiation_completed == 0)
664 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
665 goto unexpected_packet;
669 /* the got_application data is only returned
670 * if expecting client hello (for rehandshake
671 * reasons). Otherwise it is an unexpected packet
673 if (type == GNUTLS_ALERT || (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO
674 && type == GNUTLS_HANDSHAKE))
676 /* even if data is unexpected put it into the buffer */
677 if ((ret =
678 _gnutls_record_buffer_put (session, recv->type, seq,
679 bufel)) < 0)
681 gnutls_assert ();
682 goto cleanup;
685 return gnutls_assert_val(GNUTLS_E_GOT_APPLICATION_DATA);
687 else
689 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
690 goto unexpected_packet;
693 break;
695 case GNUTLS_HANDSHAKE:
696 /* In DTLS we might receive a handshake replay from the peer to indicate
697 * the our last TLS handshake messages were not received.
699 if (IS_DTLS(session))
701 if (type == GNUTLS_CHANGE_CIPHER_SPEC)
703 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
704 goto unexpected_packet;
707 if (_dtls_is_async(session) && _dtls_async_timer_active(session))
709 if (session->security_parameters.entity == GNUTLS_SERVER &&
710 bufel->htype == GNUTLS_HANDSHAKE_CLIENT_HELLO)
712 /* client requested rehandshake. Delete the timer */
713 _dtls_async_timer_delete(session);
715 else
717 session->internals.recv_state = RECV_STATE_DTLS_RETRANSMIT;
718 ret = _dtls_retransmit(session);
719 if (ret == 0)
721 session->internals.recv_state = RECV_STATE_0;
722 ret = gnutls_assert_val(GNUTLS_E_AGAIN);
723 goto unexpected_packet;
725 goto cleanup;
730 /* This is legal if HELLO_REQUEST is received - and we are a client.
731 * If we are a server, a client may initiate a renegotiation at any time.
733 if (session->security_parameters.entity == GNUTLS_SERVER &&
734 bufel->htype == GNUTLS_HANDSHAKE_CLIENT_HELLO)
736 gnutls_assert ();
737 ret =
738 _gnutls_record_buffer_put (session, recv->type, seq, bufel);
739 if (ret < 0)
741 gnutls_assert ();
742 goto cleanup;
744 return GNUTLS_E_REHANDSHAKE;
747 /* If we are already in a handshake then a Hello
748 * Request is illegal. But here we don't really care
749 * since this message will never make it up here.
752 /* So we accept it, if it is a Hello. If not, this will
753 * fail and trigger flight retransmissions after some time. */
754 ret = _gnutls_recv_hello_request (session, bufel->msg.data, bufel->msg.size);
755 goto unexpected_packet;
757 break;
758 default:
760 _gnutls_record_log
761 ("REC[%p]: Received unexpected packet %d (%s) expecting %d (%s)\n",
762 session, recv->type, _gnutls_packet2str(recv->type), type, _gnutls_packet2str(type));
764 gnutls_assert ();
765 ret = GNUTLS_E_UNEXPECTED_PACKET;
766 goto unexpected_packet;
770 return 0;
772 unexpected_packet:
773 if (IS_DTLS(session) && ret != GNUTLS_E_REHANDSHAKE)
775 _mbuffer_xfree(&bufel);
776 RETURN_DTLS_EAGAIN_OR_TIMEOUT(session, ret);
779 cleanup:
780 _mbuffer_xfree(&bufel);
781 return ret;
785 int _gnutls_get_max_decrypted_data(gnutls_session_t session)
787 int ret;
789 if (gnutls_compression_get (session) != GNUTLS_COMP_NULL ||
790 session->internals.priorities.allow_large_records != 0)
791 ret = MAX_RECORD_RECV_SIZE(session) + EXTRA_COMP_SIZE;
792 else
793 ret = MAX_RECORD_RECV_SIZE(session);
795 return ret;
798 /* Checks the record headers and returns the length, version and
799 * content type.
801 static void
802 record_read_headers (gnutls_session_t session,
803 uint8_t headers[MAX_RECORD_HEADER_SIZE],
804 content_type_t type,
805 gnutls_handshake_description_t htype,
806 struct tls_record_st* record)
809 /* Read the first two bytes to determine if this is a
810 * version 2 message
813 if (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO && type == GNUTLS_HANDSHAKE
814 && headers[0] > 127 && !(IS_DTLS(session)))
817 /* if msb set and expecting handshake message
818 * it should be SSL 2 hello
820 record->version[0] = 3; /* assume SSL 3.0 */
821 record->version[1] = 0;
823 record->length = (((headers[0] & 0x7f) << 8)) | headers[1];
825 /* SSL 2.0 headers */
826 record->header_size = record->packet_size = 2;
827 record->type = GNUTLS_HANDSHAKE; /* we accept only v2 client hello
830 /* in order to assist the handshake protocol.
831 * V2 compatibility is a mess.
833 record->v2 = 1;
834 record->epoch = 0;
836 _gnutls_record_log ("REC[%p]: SSL 2.0 %s packet received. Length: %d\n",
837 session,
838 _gnutls_packet2str (record->type),
839 record->length);
842 else
844 /* dtls version 1.0 and TLS version 1.x */
845 record->v2 = 0;
847 record->type = headers[0];
848 record->version[0] = headers[1];
849 record->version[1] = headers[2];
851 if(IS_DTLS(session))
853 memcpy(record->sequence.i, &headers[3], 8);
854 record->length = _gnutls_read_uint16 (&headers[11]);
855 record->epoch = _gnutls_read_uint16(record->sequence.i);
857 else
859 record->length = _gnutls_read_uint16 (&headers[3]);
860 record->epoch = 0;
863 _gnutls_record_log ("REC[%p]: SSL %d.%d %s packet received. Epoch %d, length: %d\n",
864 session, (int)record->version[0], (int)record->version[1],
865 _gnutls_packet2str (record->type),
866 (int)record->epoch, record->length);
870 record->packet_size += record->length;
874 static int recv_headers( gnutls_session_t session, content_type_t type,
875 gnutls_handshake_description_t htype,
876 struct tls_record_st* record,
877 unsigned int *ms)
879 int ret;
880 gnutls_datum_t raw; /* raw headers */
881 /* Read the headers.
883 record->header_size = record->packet_size = RECORD_HEADER_SIZE(session);
885 if ((ret =
886 _gnutls_io_read_buffered (session, record->header_size, -1, ms)) != record->header_size)
888 if (ret < 0 && gnutls_error_is_fatal (ret) == 0)
889 return ret;
891 if (ret > 0)
892 ret = GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
893 else if (ret == 0)
894 ret = GNUTLS_E_PREMATURE_TERMINATION;
896 return gnutls_assert_val(ret);
899 ret = _mbuffer_linearize (&session->internals.record_recv_buffer);
900 if (ret < 0)
901 return gnutls_assert_val(ret);
903 _mbuffer_head_get_first (&session->internals.record_recv_buffer, &raw);
904 if (raw.size < RECORD_HEADER_SIZE(session))
905 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
907 record_read_headers (session, raw.data, type, htype, record);
909 /* Check if the DTLS epoch is valid */
910 if (IS_DTLS(session))
912 if (_gnutls_epoch_is_valid(session, record->epoch) == 0)
914 _gnutls_audit_log(session, "Discarded message[%u] with invalid epoch %u.\n",
915 (unsigned int)_gnutls_uint64touint32 (&record->sequence),
916 (unsigned int)record->sequence.i[0]*256+(unsigned int)record->sequence.i[1]);
917 gnutls_assert();
918 /* doesn't matter, just a fatal error */
919 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
923 /* Here we check if the Type of the received packet is
924 * ok.
926 if ((ret = check_recv_type (session, record->type)) < 0)
927 return gnutls_assert_val(ret);
929 /* Here we check if the advertized version is the one we
930 * negotiated in the handshake.
932 if ((ret = record_check_version (session, htype, record->version)) < 0)
933 return gnutls_assert_val(ret);
935 if (record->length > MAX_RECV_SIZE(session))
937 _gnutls_audit_log
938 (session, "Received packet with illegal length: %u\n", (unsigned int)record->length);
939 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
942 _gnutls_record_log
943 ("REC[%p]: Expected Packet %s(%d)\n", session,
944 _gnutls_packet2str (type), type);
945 _gnutls_record_log ("REC[%p]: Received Packet %s(%d) with length: %d\n",
946 session,
947 _gnutls_packet2str (record->type), record->type, record->length);
950 return 0;
953 #define MAX_EMPTY_PACKETS_SEQUENCE 4
955 /* @ms: is the number of milliseconds to wait for data. Use zero for indefinite.
957 * This will receive record layer packets and add them to
958 * application_data_buffer and handshake_data_buffer.
960 * If the htype is not -1 then handshake timeouts
961 * will be enforced.
963 ssize_t
964 _gnutls_recv_in_buffers (gnutls_session_t session, content_type_t type,
965 gnutls_handshake_description_t htype, unsigned int ms)
967 uint64 *packet_sequence;
968 uint8_t *ciphertext;
969 mbuffer_st* bufel = NULL, *decrypted = NULL;
970 int ret;
971 int empty_packet = 0;
972 record_parameters_st *record_params;
973 record_state_st *record_state;
974 struct tls_record_st record;
976 begin:
978 if (empty_packet > MAX_EMPTY_PACKETS_SEQUENCE)
980 gnutls_assert ();
981 return GNUTLS_E_TOO_MANY_EMPTY_PACKETS;
984 memset(&record, 0, sizeof(record));
986 if (session->internals.read_eof != 0)
988 /* if we have already read an EOF
990 return 0;
992 else if (session_is_valid (session) != 0
993 || session->internals.may_not_read != 0)
994 return gnutls_assert_val(GNUTLS_E_INVALID_SESSION);
996 /* get the record state parameters */
997 ret = _gnutls_epoch_get (session, EPOCH_READ_CURRENT, &record_params);
998 if (ret < 0)
999 return gnutls_assert_val (ret);
1001 /* Safeguard against processing data with an incomplete cipher state. */
1002 if (!record_params->initialized)
1003 return gnutls_assert_val (GNUTLS_E_INTERNAL_ERROR);
1005 record_state = &record_params->read;
1007 /* receive headers */
1008 ret = recv_headers(session, type, htype, &record, &ms);
1009 if (ret < 0)
1011 ret = gnutls_assert_val_fatal(ret);
1012 goto recv_error;
1015 if (IS_DTLS(session))
1016 packet_sequence = &record.sequence;
1017 else
1018 packet_sequence = &record_state->sequence_number;
1020 /* Read the packet data and insert it to record_recv_buffer.
1022 ret =
1023 _gnutls_io_read_buffered (session, record.packet_size,
1024 record.type, &ms);
1025 if (ret != record.packet_size)
1027 gnutls_assert();
1028 goto recv_error;
1031 /* ok now we are sure that we have read all the data - so
1032 * move on !
1034 ret = _mbuffer_linearize (&session->internals.record_recv_buffer);
1035 if (ret < 0)
1036 return gnutls_assert_val(ret);
1038 bufel = _mbuffer_head_get_first (&session->internals.record_recv_buffer, NULL);
1039 if (bufel == NULL)
1040 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1042 /* We allocate the maximum possible to allow few compressed bytes to expand to a
1043 * full record.
1045 decrypted = _mbuffer_alloc(MAX_RECORD_RECV_SIZE(session),
1046 MAX_RECORD_RECV_SIZE(session));
1047 if (decrypted == NULL)
1048 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
1050 ciphertext = (uint8_t*)_mbuffer_get_udata_ptr(bufel) + record.header_size;
1052 /* decrypt the data we got.
1054 ret =
1055 _gnutls_decrypt (session, ciphertext, record.length,
1056 _mbuffer_get_udata_ptr(decrypted), _mbuffer_get_udata_size(decrypted),
1057 record.type, record_params, packet_sequence);
1058 if (ret >= 0) _mbuffer_set_udata_size(decrypted, ret);
1060 _mbuffer_head_remove_bytes (&session->internals.record_recv_buffer,
1061 record.header_size + record.length);
1062 if (ret < 0)
1064 gnutls_assert();
1065 _gnutls_audit_log(session, "Discarded message[%u] due to invalid decryption\n",
1066 (unsigned int)_gnutls_uint64touint32 (packet_sequence));
1067 goto sanity_check_error;
1070 /* check for duplicates. We check after the message
1071 * is processed and authenticated to avoid someone
1072 * messing with our windows.
1074 if (IS_DTLS(session))
1076 ret = _dtls_record_check(record_params, packet_sequence);
1077 if (ret < 0)
1079 _gnutls_audit_log(session, "Discarded duplicate message[%u]: %s\n",
1080 (unsigned int) _gnutls_uint64touint32 (packet_sequence), _gnutls_packet2str (record.type));
1081 goto sanity_check_error;
1083 _gnutls_record_log
1084 ("REC[%p]: Decrypted Packet[%u.%u] %s(%d) with length: %d\n", session,
1085 (unsigned int)record.sequence.i[0]*256 +(unsigned int)record.sequence.i[1],
1086 (unsigned int) _gnutls_uint64touint32 (packet_sequence),
1087 _gnutls_packet2str (record.type), record.type, (int)_mbuffer_get_udata_size(decrypted));
1089 else
1091 _gnutls_record_log
1092 ("REC[%p]: Decrypted Packet[%u] %s(%d) with length: %d\n", session,
1093 (unsigned int) _gnutls_uint64touint32 (packet_sequence),
1094 _gnutls_packet2str (record.type), record.type, (int)_mbuffer_get_udata_size(decrypted));
1097 /* increase sequence number
1099 if (!IS_DTLS(session) && sequence_increment (session, &record_state->sequence_number) != 0)
1101 session_invalidate (session);
1102 gnutls_assert ();
1103 ret = GNUTLS_E_RECORD_LIMIT_REACHED;
1104 goto sanity_check_error;
1107 /* (originally for) TLS 1.0 CBC protection.
1108 * Actually this code is called if we just received
1109 * an empty packet. An empty TLS packet is usually
1110 * sent to protect some vulnerabilities in the CBC mode.
1111 * In that case we go to the beginning and start reading
1112 * the next packet.
1114 if (_mbuffer_get_udata_size(decrypted) == 0)
1116 _mbuffer_xfree(&decrypted);
1117 empty_packet++;
1118 goto begin;
1121 if (record.v2)
1122 decrypted->htype = GNUTLS_HANDSHAKE_CLIENT_HELLO_V2;
1123 else
1125 uint8_t * p = _mbuffer_get_udata_ptr(decrypted);
1126 decrypted->htype = p[0];
1129 ret =
1130 record_add_to_buffers (session, &record, type, htype,
1131 packet_sequence, decrypted);
1133 /* bufel is now either deinitialized or buffered somewhere else */
1135 if (ret < 0)
1136 return gnutls_assert_val(ret);
1138 return ret;
1140 discard:
1141 session->internals.dtls.packets_dropped++;
1143 /* discard the whole received fragment. */
1144 bufel = _mbuffer_head_pop_first(&session->internals.record_recv_buffer);
1145 _mbuffer_xfree(&bufel);
1146 return gnutls_assert_val(GNUTLS_E_AGAIN);
1148 sanity_check_error:
1149 if (IS_DTLS(session))
1151 session->internals.dtls.packets_dropped++;
1152 ret = gnutls_assert_val(GNUTLS_E_AGAIN);
1153 goto cleanup;
1156 session_unresumable (session);
1157 session_invalidate (session);
1159 cleanup:
1160 _mbuffer_xfree(&decrypted);
1161 return ret;
1163 recv_error:
1164 if (ret < 0 && (gnutls_error_is_fatal (ret) == 0 || ret == GNUTLS_E_TIMEDOUT))
1165 return ret;
1167 if (IS_DTLS(session))
1169 goto discard;
1172 session_invalidate (session);
1173 if (type == GNUTLS_ALERT) /* we were expecting close notify */
1175 gnutls_assert ();
1176 return 0;
1178 session_unresumable (session);
1180 if (ret == 0)
1181 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1182 else
1183 return ret;
1186 /* This function behaves exactly like read(). The only difference is
1187 * that it accepts the gnutls_session_t and the content_type_t of data to
1188 * receive (if called by the user the Content is Userdata only)
1189 * It is intended to receive data, under the current session.
1191 * The gnutls_handshake_description_t was introduced to support SSL V2.0 client hellos.
1193 ssize_t
1194 _gnutls_recv_int (gnutls_session_t session, content_type_t type,
1195 gnutls_handshake_description_t htype,
1196 uint8_t * data, size_t data_size, void* seq,
1197 unsigned int ms)
1199 int ret;
1201 if ((type != GNUTLS_ALERT && type != GNUTLS_HEARTBEAT) && (data_size == 0 || data == NULL))
1202 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
1204 if (session->internals.read_eof != 0)
1206 /* if we have already read an EOF
1208 return 0;
1210 else if (session_is_valid (session) != 0
1211 || session->internals.may_not_read != 0)
1213 gnutls_assert ();
1214 return GNUTLS_E_INVALID_SESSION;
1217 switch(session->internals.recv_state)
1219 case RECV_STATE_DTLS_RETRANSMIT:
1220 ret = _dtls_retransmit(session);
1221 if (ret < 0)
1222 return gnutls_assert_val(ret);
1224 session->internals.recv_state = RECV_STATE_0;
1225 case RECV_STATE_0:
1227 _dtls_async_timer_check(session);
1228 /* If we have enough data in the cache do not bother receiving
1229 * a new packet. (in order to flush the cache)
1231 ret = check_buffers (session, type, data, data_size, seq);
1232 if (ret != 0)
1233 return ret;
1235 ret = _gnutls_recv_in_buffers(session, type, htype, ms);
1236 if (ret < 0 && ret != GNUTLS_E_SESSION_EOF)
1237 return gnutls_assert_val(ret);
1239 return check_buffers (session, type, data, data_size, seq);
1240 default:
1241 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1246 * gnutls_record_send:
1247 * @session: is a #gnutls_session_t structure.
1248 * @data: contains the data to send
1249 * @data_size: is the length of the data
1251 * This function has the similar semantics with send(). The only
1252 * difference is that it accepts a GnuTLS session, and uses different
1253 * error codes.
1254 * Note that if the send buffer is full, send() will block this
1255 * function. See the send() documentation for full information. You
1256 * can replace the default push function by using
1257 * gnutls_transport_set_ptr2() with a call to send() with a
1258 * MSG_DONTWAIT flag if blocking is a problem.
1259 * If the EINTR is returned by the internal push function (the
1260 * default is send()) then %GNUTLS_E_INTERRUPTED will be returned. If
1261 * %GNUTLS_E_INTERRUPTED or %GNUTLS_E_AGAIN is returned, you must
1262 * call this function again, with the same parameters; alternatively
1263 * you could provide a %NULL pointer for data, and 0 for
1264 * size. cf. gnutls_record_get_direction(). The errno value EMSGSIZE
1265 * maps to %GNUTLS_E_LARGE_PACKET.
1267 * Returns: The number of bytes sent, or a negative error code. The
1268 * number of bytes sent might be less than @data_size. The maximum
1269 * number of bytes this function can send in a single call depends
1270 * on the negotiated maximum record size.
1272 ssize_t
1273 gnutls_record_send (gnutls_session_t session, const void *data,
1274 size_t data_size)
1276 return _gnutls_send_int (session, GNUTLS_APPLICATION_DATA, -1,
1277 EPOCH_WRITE_CURRENT, data, data_size,
1278 MBUFFER_FLUSH);
1282 * gnutls_record_recv:
1283 * @session: is a #gnutls_session_t structure.
1284 * @data: the buffer that the data will be read into
1285 * @data_size: the number of requested bytes
1287 * This function has the similar semantics with recv(). The only
1288 * difference is that it accepts a GnuTLS session, and uses different
1289 * error codes.
1290 * In the special case that a server requests a renegotiation, the
1291 * client may receive an error code of %GNUTLS_E_REHANDSHAKE. This
1292 * message may be simply ignored, replied with an alert
1293 * %GNUTLS_A_NO_RENEGOTIATION, or replied with a new handshake,
1294 * depending on the client's will.
1295 * If %EINTR is returned by the internal push function (the default
1296 * is recv()) then %GNUTLS_E_INTERRUPTED will be returned. If
1297 * %GNUTLS_E_INTERRUPTED or %GNUTLS_E_AGAIN is returned, you must
1298 * call this function again to get the data. See also
1299 * gnutls_record_get_direction().
1300 * A server may also receive %GNUTLS_E_REHANDSHAKE when a client has
1301 * initiated a handshake. In that case the server can only initiate a
1302 * handshake or terminate the connection.
1304 * Returns: The number of bytes received and zero on EOF (for stream
1305 * connections). A negative error code is returned in case of an error.
1306 * The number of bytes received might be less than the requested @data_size.
1308 ssize_t
1309 gnutls_record_recv (gnutls_session_t session, void *data, size_t data_size)
1311 return _gnutls_recv_int (session, GNUTLS_APPLICATION_DATA, -1, data, data_size, NULL, 0);
1315 * gnutls_record_recv_seq:
1316 * @session: is a #gnutls_session_t structure.
1317 * @data: the buffer that the data will be read into
1318 * @data_size: the number of requested bytes
1319 * @seq: is the packet's 64-bit sequence number. Should have space for 8 bytes.
1321 * This function is the same as gnutls_record_recv(), except that
1322 * it returns in addition to data, the sequence number of the data.
1323 * This is useful in DTLS where record packets might be received
1324 * out-of-order. The returned 8-byte sequence number is an
1325 * integer in big-endian format and should be
1326 * treated as a unique message identification.
1328 * Returns: The number of bytes received and zero on EOF. A negative
1329 * error code is returned in case of an error. The number of bytes
1330 * received might be less than @data_size.
1332 * Since: 3.0
1334 ssize_t
1335 gnutls_record_recv_seq (gnutls_session_t session, void *data, size_t data_size,
1336 unsigned char *seq)
1338 return _gnutls_recv_int (session, GNUTLS_APPLICATION_DATA, -1, data,
1339 data_size, seq, 0);