2 * Copyright (C) 2000-2013 Free Software Foundation, Inc.
3 * Copyright (C) 2012,2013 Nikos Mavrogiannopoulos
5 * Author: Nikos Mavrogiannopoulos
7 * This file is part of GnuTLS.
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.
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.
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/>
24 /* Functions that are record layer specific, are included in this file.
27 /* allocate this many bytes more when encrypting or decrypting, to
28 * compensate for broken backends such as cryptodev.
30 #define CIPHER_SLACK_SIZE 32
32 #include "gnutls_int.h"
33 #include "gnutls_errors.h"
35 #include "gnutls_compress.h"
36 #include "gnutls_cipher.h"
37 #include "gnutls_buffers.h"
38 #include "gnutls_mbuffers.h"
39 #include "gnutls_handshake.h"
40 #include "gnutls_hash_int.h"
41 #include "gnutls_cipher_int.h"
42 #include "algorithms.h"
43 #include "gnutls_db.h"
44 #include "gnutls_auth.h"
45 #include "gnutls_num.h"
46 #include "gnutls_record.h"
47 #include "gnutls_datum.h"
48 #include "gnutls_constate.h"
49 #include "ext/max_record.h"
50 #include <ext/heartbeat.h>
51 #include <gnutls_state.h>
52 #include <gnutls_dtls.h>
53 #include <gnutls_dh.h>
56 struct tls_record_st {
59 uint64 sequence; /* DTLS */
61 uint16_t packet_size; /* header_size + length */
63 uint16_t epoch; /* valid in DTLS only */
64 unsigned v2:1; /* whether an SSLv2 client hello */
69 * gnutls_record_disable_padding:
70 * @session: is a #gnutls_session_t structure.
72 * Used to disabled padding in TLS 1.0 and above. Normally you do not
73 * need to use this function, but there are buggy clients that
74 * complain if a server pads the encrypted data. This of course will
75 * disable protection against statistical attacks on the data.
77 * This functions is defunt since 3.1.7. Random padding is disabled
78 * by default unless requested using gnutls_range_send_message().
81 void gnutls_record_disable_padding(gnutls_session_t session)
87 * gnutls_record_set_max_empty_records:
88 * @session: is a #gnutls_session_t structure.
89 * @i: is the desired value of maximum empty records that can be accepted in a row.
91 * Used to set the maximum number of empty fragments that can be accepted
92 * in a row. Accepting many empty fragments is useful for receiving length-hidden
93 * content, where empty fragments filled with pad are sent to hide the real
94 * length of a message. However, a malicious peer could send empty fragments to
95 * mount a DoS attack, so as a safety measure, a maximum number of empty fragments
96 * is accepted by default. If you know your application must accept a given number
97 * of empty fragments in a row, you can use this function to set the desired value.
100 gnutls_record_set_max_empty_records(gnutls_session_t session,
101 const unsigned int i)
103 session->internals.priorities.max_empty_records = i;
107 * gnutls_transport_set_ptr:
108 * @session: is a #gnutls_session_t structure.
109 * @ptr: is the value.
111 * Used to set the first argument of the transport function (for push
112 * and pull callbacks). In berkeley style sockets this function will set the
113 * connection descriptor.
117 gnutls_transport_set_ptr(gnutls_session_t session,
118 gnutls_transport_ptr_t ptr)
120 session->internals.transport_recv_ptr = ptr;
121 session->internals.transport_send_ptr = ptr;
125 * gnutls_transport_set_ptr2:
126 * @session: is a #gnutls_session_t structure.
127 * @recv_ptr: is the value for the pull function
128 * @send_ptr: is the value for the push function
130 * Used to set the first argument of the transport function (for push
131 * and pull callbacks). In berkeley style sockets this function will set the
132 * connection descriptor. With this function you can use two different
133 * pointers for receiving and sending.
136 gnutls_transport_set_ptr2(gnutls_session_t session,
137 gnutls_transport_ptr_t recv_ptr,
138 gnutls_transport_ptr_t send_ptr)
140 session->internals.transport_send_ptr = send_ptr;
141 session->internals.transport_recv_ptr = recv_ptr;
145 * gnutls_transport_set_int2:
146 * @session: is a #gnutls_session_t structure.
147 * @recv_int: is the value for the pull function
148 * @send_int: is the value for the push function
150 * Used to set the first argument of the transport function (for push
151 * and pull callbacks), when using the berkeley style sockets.
152 * With this function you can set two different
153 * pointers for receiving and sending.
158 gnutls_transport_set_int2(gnutls_session_t session,
159 int recv_int, int send_int)
161 session->internals.transport_send_ptr =
162 (gnutls_transport_ptr_t) (long) send_int;
163 session->internals.transport_recv_ptr =
164 (gnutls_transport_ptr_t) (long) recv_int;
168 /* this will be a macro */
170 * gnutls_transport_set_int:
171 * @session: is a #gnutls_session_t structure.
174 * Used to set the first argument of the transport function (for push
175 * and pull callbacks) for berkeley style sockets.
180 void gnutls_transport_set_int(gnutls_session_t session, int i)
182 session->internals.transport_recv_ptr =
183 (gnutls_transport_ptr_t) (long) i;
184 session->internals.transport_send_ptr =
185 (gnutls_transport_ptr_t) (long) i;
190 * gnutls_transport_get_ptr:
191 * @session: is a #gnutls_session_t structure.
193 * Used to get the first argument of the transport function (like
194 * PUSH and PULL). This must have been set using
195 * gnutls_transport_set_ptr().
197 * Returns: The first argument of the transport function.
199 gnutls_transport_ptr_t gnutls_transport_get_ptr(gnutls_session_t session)
201 return session->internals.transport_recv_ptr;
205 * gnutls_transport_get_ptr2:
206 * @session: is a #gnutls_session_t structure.
207 * @recv_ptr: will hold the value for the pull function
208 * @send_ptr: will hold the value for the push function
210 * Used to get the arguments of the transport functions (like PUSH
211 * and PULL). These should have been set using
212 * gnutls_transport_set_ptr2().
215 gnutls_transport_get_ptr2(gnutls_session_t session,
216 gnutls_transport_ptr_t * recv_ptr,
217 gnutls_transport_ptr_t * send_ptr)
220 *recv_ptr = session->internals.transport_recv_ptr;
221 *send_ptr = session->internals.transport_send_ptr;
225 * gnutls_transport_get_int2:
226 * @session: is a #gnutls_session_t structure.
227 * @recv_int: will hold the value for the pull function
228 * @send_int: will hold the value for the push function
230 * Used to get the arguments of the transport functions (like PUSH
231 * and PULL). These should have been set using
232 * gnutls_transport_set_int2().
237 gnutls_transport_get_int2(gnutls_session_t session,
238 int *recv_int, int *send_int)
241 *recv_int = (long) session->internals.transport_recv_ptr;
242 *send_int = (long) session->internals.transport_send_ptr;
246 * gnutls_transport_get_int:
247 * @session: is a #gnutls_session_t structure.
249 * Used to get the first argument of the transport function (like
250 * PUSH and PULL). This must have been set using
251 * gnutls_transport_set_int().
253 * Returns: The first argument of the transport function.
257 int gnutls_transport_get_int(gnutls_session_t session)
259 return (long) session->internals.transport_recv_ptr;
264 * @session: is a #gnutls_session_t structure.
265 * @how: is an integer
267 * Terminates the current TLS/SSL connection. The connection should
268 * have been initiated using gnutls_handshake(). @how should be one
269 * of %GNUTLS_SHUT_RDWR, %GNUTLS_SHUT_WR.
271 * In case of %GNUTLS_SHUT_RDWR the TLS session gets
272 * terminated and further receives and sends will be disallowed. If
273 * the return value is zero you may continue using the underlying
274 * transport layer. %GNUTLS_SHUT_RDWR sends an alert containing a close
275 * request and waits for the peer to reply with the same message.
277 * In case of %GNUTLS_SHUT_WR the TLS session gets terminated
278 * and further sends will be disallowed. In order to reuse the
279 * connection you should wait for an EOF from the peer.
280 * %GNUTLS_SHUT_WR sends an alert containing a close request.
282 * Note that not all implementations will properly terminate a TLS
283 * connection. Some of them, usually for performance reasons, will
284 * terminate only the underlying transport layer, and thus not
285 * distinguishing between a malicious party prematurely terminating
286 * the connection and normal termination.
288 * This function may also return %GNUTLS_E_AGAIN or
289 * %GNUTLS_E_INTERRUPTED; cf. gnutls_record_get_direction().
291 * Returns: %GNUTLS_E_SUCCESS on success, or an error code, see
292 * function documentation for entire semantics.
294 int gnutls_bye(gnutls_session_t session, gnutls_close_request_t how)
301 ret = _gnutls_io_write_flush(session);
310 gnutls_alert_send(session, GNUTLS_AL_WARNING,
311 GNUTLS_A_CLOSE_NOTIFY);
320 if (how == GNUTLS_SHUT_RDWR) {
323 _gnutls_recv_int(session, GNUTLS_ALERT,
324 -1, NULL, NULL, 0, NULL,
328 while (ret == GNUTLS_E_GOT_APPLICATION_DATA);
331 session->internals.may_not_read = 1;
343 return GNUTLS_E_INTERNAL_ERROR;
348 session->internals.may_not_write = 1;
352 inline static void session_invalidate(gnutls_session_t session)
354 session->internals.invalid_connection = 1;
358 inline static void session_unresumable(gnutls_session_t session)
360 session->internals.resumable = RESUME_FALSE;
363 /* returns 0 if session is valid
365 inline static int session_is_valid(gnutls_session_t session)
367 if (session->internals.invalid_connection != 0)
368 return GNUTLS_E_INVALID_SESSION;
373 /* Copies the record version into the headers. The
374 * version must have 2 bytes at least.
377 copy_record_version(gnutls_session_t session,
378 gnutls_handshake_description_t htype,
381 const version_entry_st *lver;
383 if (session->internals.initial_negotiation_completed
384 || htype != GNUTLS_HANDSHAKE_CLIENT_HELLO
385 || session->internals.default_record_version[0] == 0) {
386 lver = get_version(session);
388 version[0] = lver->major;
389 version[1] = lver->minor;
391 version[0] = session->internals.default_record_version[0];
392 version[1] = session->internals.default_record_version[1];
396 /* Increments the sequence value
399 sequence_increment(gnutls_session_t session, uint64 * value)
401 if (IS_DTLS(session)) {
402 return _gnutls_uint48pp(value);
404 return _gnutls_uint64pp(value);
408 /* This function behaves exactly like write(). The only difference is
409 * that it accepts, the gnutls_session_t and the content_type_t of data to
410 * send (if called by the user the Content is specific)
411 * It is intended to transfer data, under the current session.
413 * @type: The content type to send
414 * @htype: If this is a handshake message then the handshake type
415 * @epoch_rel: %EPOCH_READ_* or %EPOCH_WRITE_*
416 * @data: the data to be sent
417 * @data_size: the size of the @data
418 * @min_pad: the minimum required padding
419 * @mflags: zero or %MBUFFER_FLUSH
421 * Oct 30 2001: Removed capability to send data more than MAX_RECORD_SIZE.
422 * This makes the function much easier to read, and more error resistant
423 * (there were cases were the old function could mess everything up).
426 * This function may accept a NULL pointer for data, and 0 for size, if
427 * and only if the previous send was interrupted for some reason.
431 _gnutls_send_tlen_int(gnutls_session_t session, content_type_t type,
432 gnutls_handshake_description_t htype,
433 unsigned int epoch_rel, const void *_data,
434 size_t data_size, size_t min_pad,
443 const uint8_t *data = _data;
444 record_parameters_st *record_params;
445 size_t max_send_size;
446 record_state_st *record_state;
448 ret = _gnutls_epoch_get(session, epoch_rel, &record_params);
450 return gnutls_assert_val(ret);
452 /* Safeguard against processing data with an incomplete cipher state. */
453 if (!record_params->initialized)
454 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
456 record_state = &record_params->write;
458 /* Do not allow null pointer if the send buffer is empty.
459 * If the previous send was interrupted then a null pointer is
460 * ok, and means to resume.
462 if (session->internals.record_send_buffer.byte_length == 0 &&
463 (data_size == 0 && _data == NULL)) {
465 return GNUTLS_E_INVALID_REQUEST;
468 if (type != GNUTLS_ALERT) /* alert messages are sent anyway */
469 if (session_is_valid(session)
470 || session->internals.may_not_write != 0) {
472 return GNUTLS_E_INVALID_SESSION;
475 max_send_size = max_user_send_size(session, record_params);
477 if (data_size > max_send_size) {
478 if (IS_DTLS(session))
479 return gnutls_assert_val(GNUTLS_E_LARGE_PACKET);
481 send_data_size = max_send_size;
483 send_data_size = data_size;
485 /* Only encrypt if we don't have data to send
486 * from the previous run. - probably interrupted.
489 && session->internals.record_send_buffer.byte_length > 0) {
490 ret = _gnutls_io_write_flush(session);
496 retval = session->internals.record_send_buffer_user_size;
498 if (unlikely((send_data_size == 0 && min_pad == 0)))
499 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
501 /* now proceed to packet encryption
503 cipher_size = MAX_RECORD_SEND_SIZE(session);
505 bufel = _mbuffer_alloc_align16(cipher_size + CIPHER_SLACK_SIZE,
506 get_total_headers2(session, record_params));
508 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
510 headers = _mbuffer_get_uhead_ptr(bufel);
512 /* Use the default record version, if it is
514 copy_record_version(session, htype, &headers[1]);
515 /* Adjust header length and add sequence for DTLS */
516 if (IS_DTLS(session))
518 &record_state->sequence_number.i, 8);
521 ("REC[%p]: Preparing Packet %s(%d) with length: %d and min pad: %d\n",
522 session, _gnutls_packet2str(type), type,
523 (int) data_size, (int) min_pad);
525 header_size = RECORD_HEADER_SIZE(session);
526 _mbuffer_set_udata_size(bufel, cipher_size);
527 _mbuffer_set_uhead_size(bufel, header_size);
530 _gnutls_encrypt(session,
531 data, send_data_size, min_pad,
532 bufel, type, record_params);
536 ret = GNUTLS_E_ENCRYPTION_FAILED;
538 return ret; /* error */
541 cipher_size = _mbuffer_get_udata_size(bufel);
542 retval = send_data_size;
543 session->internals.record_send_buffer_user_size =
546 /* increase sequence number
548 if (sequence_increment
549 (session, &record_state->sequence_number) != 0) {
550 session_invalidate(session);
554 (GNUTLS_E_RECORD_LIMIT_REACHED);
557 ret = _gnutls_io_write_buffered(session, bufel, mflags);
560 if (ret != cipher_size) {
561 /* If we have sent any data then just return
562 * the error value. Do not invalidate the session.
564 if (ret < 0 && gnutls_error_is_fatal(ret) == 0)
565 return gnutls_assert_val(ret);
568 ret = gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
570 session_unresumable(session);
571 session->internals.may_not_write = 1;
572 return gnutls_assert_val(ret);
575 session->internals.record_send_buffer_user_size = 0;
578 ("REC[%p]: Sent Packet[%d] %s(%d) in epoch %d and length: %d\n",
579 session, (unsigned int)
580 _gnutls_uint64touint32(&record_state->sequence_number),
581 _gnutls_packet2str(type), type, (int) record_params->epoch,
588 check_recv_type(gnutls_session_t session, content_type_t recv_type)
591 case GNUTLS_CHANGE_CIPHER_SPEC:
593 case GNUTLS_HANDSHAKE:
594 case GNUTLS_HEARTBEAT:
595 case GNUTLS_APPLICATION_DATA:
599 _gnutls_audit_log(session,
600 "Received record packet of unknown type %u\n",
601 (unsigned int) recv_type);
602 return GNUTLS_E_UNEXPECTED_PACKET;
608 /* Checks if there are pending data in the record buffers. If there are
609 * then it copies the data.
612 check_buffers(gnutls_session_t session, content_type_t type,
613 uint8_t * data, int data_size, void *seq)
615 if ((type == GNUTLS_APPLICATION_DATA ||
616 type == GNUTLS_HANDSHAKE || type == GNUTLS_CHANGE_CIPHER_SPEC)
617 && _gnutls_record_buffer_get_size(session) > 0) {
620 _gnutls_record_buffer_get(type, session, data,
623 if (IS_DTLS(session)) {
624 if (ret == GNUTLS_E_UNEXPECTED_PACKET) {
625 ret = GNUTLS_E_AGAIN;
638 /* Checks and retrieves any pending data in the application data record buffers.
641 check_packet_buffers(gnutls_session_t session, content_type_t type,
642 gnutls_packet_t *packet)
644 if (_gnutls_record_buffer_get_size(session) > 0) {
647 _gnutls_record_buffer_get_packet(type, session,
650 if (IS_DTLS(session)) {
651 if (ret == GNUTLS_E_UNEXPECTED_PACKET) {
652 ret = GNUTLS_E_AGAIN;
668 /* Here we check if the advertized version is the one we
669 * negotiated in the handshake.
672 record_check_version(gnutls_session_t session,
673 gnutls_handshake_description_t htype,
676 const version_entry_st *vers = get_version(session);
679 if (vers->major != version[0] || vers->minor != version[1])
682 if (!IS_DTLS(session)) {
683 if (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO ||
684 htype == GNUTLS_HANDSHAKE_SERVER_HELLO) {
685 if (version[0] != 3) {
688 ("REC[%p]: INVALID VERSION PACKET: (%d) %d.%d\n",
689 session, htype, version[0],
691 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
693 } else if (diff != 0) {
694 /* Reject record packets that have a different version than the
695 * one negotiated. Note that this version is not protected by any
696 * mac. I don't really think that this check serves any purpose.
700 ("REC[%p]: INVALID VERSION PACKET: (%d) %d.%d\n",
701 session, htype, version[0], version[1]);
703 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
707 /* In DTLS the only information we have here is whether we
708 * expect a handshake message or not.
710 if (htype == (gnutls_handshake_description_t) - 1) {
712 /* Reject record packets that have a different version than the
713 * one negotiated. Note that this version is not protected by any
714 * mac. I don't really think that this check serves any purpose.
718 ("REC[%p]: INVALID VERSION PACKET: (%d) %d.%d\n",
719 session, htype, version[0],
722 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
724 } else if (vers->id > GNUTLS_DTLS1_0 && version[0] > 254) {
727 ("REC[%p]: INVALID DTLS VERSION PACKET: (%d) %d.%d\n",
728 session, htype, version[0], version[1]);
729 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
730 } else if (vers->id == GNUTLS_DTLS0_9 && version[0] > 1) {
733 ("REC[%p]: INVALID DTLS VERSION PACKET: (%d) %d.%d\n",
734 session, htype, version[0], version[1]);
735 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
742 /* This function will check if the received record type is
743 * the one we actually expect and adds it to the proper
744 * buffer. The bufel will be deinitialized after calling
745 * this function, even if it fails.
748 record_add_to_buffers(gnutls_session_t session,
749 struct tls_record_st *recv, content_type_t type,
750 gnutls_handshake_description_t htype,
751 uint64 * seq, mbuffer_st * bufel)
756 if ((recv->type == type)
757 && (type == GNUTLS_APPLICATION_DATA ||
758 type == GNUTLS_CHANGE_CIPHER_SPEC ||
759 type == GNUTLS_HANDSHAKE)) {
760 _gnutls_record_buffer_put(session, type, seq, bufel);
762 /* if we received application data as expected then we
763 * deactivate the async timer */
764 _dtls_async_timer_delete(session);
766 /* if the expected type is different than the received
768 switch (recv->type) {
770 if (bufel->msg.size < 2) {
773 (GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
774 goto unexpected_packet;
778 ("REC[%p]: Alert[%d|%d] - %s - was received\n",
779 session, bufel->msg.data[0],
781 gnutls_alert_get_name((int) bufel->msg.
784 session->internals.last_alert = bufel->msg.data[1];
786 /* if close notify is received and
787 * the alert is not fatal
789 if (bufel->msg.data[1] == GNUTLS_A_CLOSE_NOTIFY
790 && bufel->msg.data[0] != GNUTLS_AL_FATAL) {
791 /* If we have been expecting for an alert do
793 session->internals.read_eof = 1;
794 ret = GNUTLS_E_SESSION_EOF;
797 /* if the alert is FATAL or WARNING
798 * return the apropriate message
802 ret = GNUTLS_E_WARNING_ALERT_RECEIVED;
803 if (bufel->msg.data[0] == GNUTLS_AL_FATAL) {
804 session_unresumable(session);
805 session_invalidate(session);
808 (GNUTLS_E_FATAL_ALERT_RECEIVED);
814 case GNUTLS_CHANGE_CIPHER_SPEC:
815 if (!(IS_DTLS(session))) {
816 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
820 _gnutls_record_buffer_put(session, recv->type, seq,
825 #ifdef ENABLE_HEARTBEAT
826 case GNUTLS_HEARTBEAT:
827 ret = _gnutls_heartbeat_handle(session, bufel);
831 case GNUTLS_APPLICATION_DATA:
832 if (session->internals.
833 initial_negotiation_completed == 0) {
836 (GNUTLS_E_UNEXPECTED_PACKET);
837 goto unexpected_packet;
841 /* the got_application data is only returned
842 * if expecting client hello (for rehandshake
843 * reasons). Otherwise it is an unexpected packet
845 if (type == GNUTLS_ALERT
846 || (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO
847 && type == GNUTLS_HANDSHAKE)) {
848 /* even if data is unexpected put it into the buffer */
849 _gnutls_record_buffer_put(session, recv->type,
853 (GNUTLS_E_GOT_APPLICATION_DATA);
857 (GNUTLS_E_UNEXPECTED_PACKET);
858 goto unexpected_packet;
863 case GNUTLS_HANDSHAKE:
864 /* In DTLS we might receive a handshake replay from the peer to indicate
865 * the our last TLS handshake messages were not received.
867 if (IS_DTLS(session)) {
868 if (type == GNUTLS_CHANGE_CIPHER_SPEC) {
871 (GNUTLS_E_UNEXPECTED_PACKET);
872 goto unexpected_packet;
875 if (_dtls_is_async(session)
876 && _dtls_async_timer_active(session)) {
877 if (session->security_parameters.
878 entity == GNUTLS_SERVER
880 GNUTLS_HANDSHAKE_CLIENT_HELLO)
882 /* client requested rehandshake. Delete the timer */
883 _dtls_async_timer_delete
888 RECV_STATE_DTLS_RETRANSMIT;
899 goto unexpected_packet;
906 /* This is legal if HELLO_REQUEST is received - and we are a client.
907 * If we are a server, a client may initiate a renegotiation at any time.
909 if (session->security_parameters.entity ==
912 GNUTLS_HANDSHAKE_CLIENT_HELLO) {
914 _gnutls_record_buffer_put(session,
917 return GNUTLS_E_REHANDSHAKE;
920 /* If we are already in a handshake then a Hello
921 * Request is illegal. But here we don't really care
922 * since this message will never make it up here.
925 /* So we accept it, if it is a Hello. If not, this will
926 * fail and trigger flight retransmissions after some time. */
928 _gnutls_recv_hello_request(session,
931 goto unexpected_packet;
937 ("REC[%p]: Received unexpected packet %d (%s) expecting %d (%s)\n",
939 _gnutls_packet2str(recv->type), type,
940 _gnutls_packet2str(type));
943 ret = GNUTLS_E_UNEXPECTED_PACKET;
944 goto unexpected_packet;
951 if (IS_DTLS(session) && ret != GNUTLS_E_REHANDSHAKE) {
952 _mbuffer_xfree(&bufel);
953 RETURN_DTLS_EAGAIN_OR_TIMEOUT(session, ret);
957 _mbuffer_xfree(&bufel);
963 /* Checks the record headers and returns the length, version and
967 record_read_headers(gnutls_session_t session,
968 uint8_t headers[MAX_RECORD_HEADER_SIZE],
970 gnutls_handshake_description_t htype,
971 struct tls_record_st *record)
974 /* Read the first two bytes to determine if this is a
978 if (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO
979 && type == GNUTLS_HANDSHAKE && headers[0] > 127
980 && !(IS_DTLS(session))) {
982 /* if msb set and expecting handshake message
983 * it should be SSL 2 hello
985 record->version[0] = 3; /* assume SSL 3.0 */
986 record->version[1] = 0;
988 record->length = (((headers[0] & 0x7f) << 8)) | headers[1];
990 /* SSL 2.0 headers */
991 record->header_size = record->packet_size = 2;
992 record->type = GNUTLS_HANDSHAKE; /* we accept only v2 client hello
995 /* in order to assist the handshake protocol.
996 * V2 compatibility is a mess.
1000 memset(&record->sequence, 0, sizeof(record->sequence));
1003 ("REC[%p]: SSL 2.0 %s packet received. Length: %d\n",
1004 session, _gnutls_packet2str(record->type),
1008 /* dtls version 1.0 and TLS version 1.x */
1011 record->type = headers[0];
1012 record->version[0] = headers[1];
1013 record->version[1] = headers[2];
1015 if (IS_DTLS(session)) {
1016 memcpy(record->sequence.i, &headers[3], 8);
1017 record->length = _gnutls_read_uint16(&headers[11]);
1019 _gnutls_read_uint16(record->sequence.i);
1021 memset(&record->sequence, 0,
1022 sizeof(record->sequence));
1023 record->length = _gnutls_read_uint16(&headers[3]);
1028 ("REC[%p]: SSL %d.%d %s packet received. Epoch %d, length: %d\n",
1029 session, (int) record->version[0],
1030 (int) record->version[1],
1031 _gnutls_packet2str(record->type), (int) record->epoch,
1036 record->packet_size += record->length;
1040 static int recv_headers(gnutls_session_t session,
1041 record_parameters_st *record_params,
1042 content_type_t type,
1043 gnutls_handshake_description_t htype,
1044 struct tls_record_st *record, unsigned int *ms)
1047 gnutls_datum_t raw; /* raw headers */
1048 /* Read the headers.
1050 record->header_size = record->packet_size =
1051 RECORD_HEADER_SIZE(session);
1054 _gnutls_io_read_buffered(session, record->header_size, -1, ms);
1055 if (ret != record->header_size) {
1056 if (ret < 0 && gnutls_error_is_fatal(ret) == 0)
1060 ret = GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1062 ret = GNUTLS_E_PREMATURE_TERMINATION;
1064 return gnutls_assert_val(ret);
1067 ret = _mbuffer_linearize_align16(&session->internals.record_recv_buffer,
1068 get_total_headers2(session, record_params));
1070 return gnutls_assert_val(ret);
1072 _mbuffer_head_get_first(&session->internals.record_recv_buffer,
1074 if (raw.size < RECORD_HEADER_SIZE(session))
1076 gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
1078 record_read_headers(session, raw.data, type, htype, record);
1080 /* Check if the DTLS epoch is valid */
1081 if (IS_DTLS(session)) {
1082 if (_gnutls_epoch_is_valid(session, record->epoch) == 0) {
1083 _gnutls_audit_log(session,
1084 "Discarded message[%u] with invalid epoch %u.\n",
1086 _gnutls_uint64touint32(&record->
1088 (unsigned int) record->sequence.
1090 (unsigned int) record->sequence.
1093 /* doesn't matter, just a fatal error */
1094 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1098 /* Here we check if the Type of the received packet is
1101 if ((ret = check_recv_type(session, record->type)) < 0)
1102 return gnutls_assert_val(ret);
1104 /* Here we check if the advertized version is the one we
1105 * negotiated in the handshake.
1108 record_check_version(session, htype, record->version)) < 0)
1109 return gnutls_assert_val(ret);
1111 if (record->length > max_record_recv_size(session)) {
1113 (session, "Received packet with illegal length: %u\n",
1114 (unsigned int) record->length);
1116 gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
1120 ("REC[%p]: Expected Packet %s(%d)\n", session,
1121 _gnutls_packet2str(type), type);
1123 ("REC[%p]: Received Packet %s(%d) with length: %d\n", session,
1124 _gnutls_packet2str(record->type), record->type,
1131 /* @ms: is the number of milliseconds to wait for data. Use zero for indefinite.
1133 * This will receive record layer packets and add them to
1134 * application_data_buffer and handshake_data_buffer.
1136 * If the htype is not -1 then handshake timeouts
1140 _gnutls_recv_in_buffers(gnutls_session_t session, content_type_t type,
1141 gnutls_handshake_description_t htype,
1144 uint64 *packet_sequence;
1145 gnutls_datum_t ciphertext;
1146 mbuffer_st *bufel = NULL, *decrypted = NULL;
1149 unsigned int empty_fragments = 0;
1150 record_parameters_st *record_params;
1151 record_state_st *record_state;
1152 struct tls_record_st record;
1156 if (empty_fragments >
1157 session->internals.priorities.max_empty_records) {
1159 return GNUTLS_E_TOO_MANY_EMPTY_PACKETS;
1162 if (session->internals.read_eof != 0) {
1163 /* if we have already read an EOF
1166 } else if (session_is_valid(session) != 0
1167 || session->internals.may_not_read != 0)
1168 return gnutls_assert_val(GNUTLS_E_INVALID_SESSION);
1170 /* get the record state parameters */
1172 _gnutls_epoch_get(session, EPOCH_READ_CURRENT, &record_params);
1174 return gnutls_assert_val(ret);
1176 /* Safeguard against processing data with an incomplete cipher state. */
1177 if (!record_params->initialized)
1178 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1180 record_state = &record_params->read;
1182 /* receive headers */
1183 ret = recv_headers(session, record_params, type, htype, &record, &ms);
1185 ret = gnutls_assert_val_fatal(ret);
1189 if (IS_DTLS(session))
1190 packet_sequence = &record.sequence;
1192 packet_sequence = &record_state->sequence_number;
1194 /* Read the packet data and insert it to record_recv_buffer.
1197 _gnutls_io_read_buffered(session, record.packet_size,
1199 if (ret != record.packet_size) {
1204 /* ok now we are sure that we have read all the data - so
1207 ret = _mbuffer_linearize_align16(&session->internals.record_recv_buffer,
1208 get_total_headers2(session, record_params));
1210 return gnutls_assert_val(ret);
1213 _mbuffer_head_get_first(&session->internals.record_recv_buffer,
1216 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1218 /* We allocate the maximum possible to allow few compressed bytes to expand to a
1219 * full record. Moreover we add space for any pad and the MAC (in case
1220 * they are encrypted).
1222 ret = max_decrypted_size(session) + MAX_PAD_SIZE + MAX_HASH_SIZE;
1223 decrypted = _mbuffer_alloc_align16(ret, 0);
1224 if (decrypted == NULL)
1225 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
1227 _mbuffer_set_udata_size(decrypted, ret);
1229 (uint8_t *) _mbuffer_get_udata_ptr(bufel) + record.header_size;
1230 ciphertext.size = record.length;
1232 /* decrypt the data we got.
1234 t.data = _mbuffer_get_udata_ptr(decrypted);
1235 t.size = _mbuffer_get_udata_size(decrypted);
1237 _gnutls_decrypt(session, &ciphertext, &t,
1238 record.type, record_params, packet_sequence);
1240 _mbuffer_set_udata_size(decrypted, ret);
1242 _mbuffer_head_remove_bytes(&session->internals.record_recv_buffer,
1243 record.header_size + record.length);
1246 _gnutls_audit_log(session,
1247 "Discarded message[%u] due to invalid decryption\n",
1249 _gnutls_uint64touint32(packet_sequence));
1250 goto sanity_check_error;
1253 /* check for duplicates. We check after the message
1254 * is processed and authenticated to avoid someone
1255 * messing with our windows.
1257 if (IS_DTLS(session)
1258 && session->internals.no_replay_protection == 0) {
1259 ret = _dtls_record_check(record_params, packet_sequence);
1262 ("REC[%p]: Discarded duplicate message[%u.%u]: %s\n",
1264 (unsigned int) record.sequence.i[0] * 256 +
1265 (unsigned int) record.sequence.i[1],
1267 _gnutls_uint64touint32(packet_sequence),
1268 _gnutls_packet2str(record.type));
1269 goto sanity_check_error;
1272 ("REC[%p]: Decrypted Packet[%u.%u] %s(%d) with length: %d\n",
1274 (unsigned int) record.sequence.i[0] * 256 +
1275 (unsigned int) record.sequence.i[1],
1277 _gnutls_uint64touint32(packet_sequence),
1278 _gnutls_packet2str(record.type), record.type,
1279 (int) _mbuffer_get_udata_size(decrypted));
1282 ("REC[%p]: Decrypted Packet[%u] %s(%d) with length: %d\n",
1285 _gnutls_uint64touint32(packet_sequence),
1286 _gnutls_packet2str(record.type), record.type,
1287 (int) _mbuffer_get_udata_size(decrypted));
1290 /* increase sequence number
1292 if (!IS_DTLS(session)
1293 && sequence_increment(session,
1294 &record_state->sequence_number) != 0) {
1295 session_invalidate(session);
1297 ret = GNUTLS_E_RECORD_LIMIT_REACHED;
1298 goto sanity_check_error;
1301 /* (originally for) TLS 1.0 CBC protection.
1302 * Actually this code is called if we just received
1303 * an empty packet. An empty TLS packet is usually
1304 * sent to protect some vulnerabilities in the CBC mode.
1305 * In that case we go to the beginning and start reading
1308 if (_mbuffer_get_udata_size(decrypted) == 0) {
1309 _mbuffer_xfree(&decrypted);
1315 decrypted->htype = GNUTLS_HANDSHAKE_CLIENT_HELLO_V2;
1317 uint8_t *p = _mbuffer_get_udata_ptr(decrypted);
1318 decrypted->htype = p[0];
1322 record_add_to_buffers(session, &record, type, htype,
1323 packet_sequence, decrypted);
1325 /* decrypted is now either deinitialized or buffered somewhere else */
1328 return gnutls_assert_val(ret);
1333 session->internals.dtls.packets_dropped++;
1335 /* discard the whole received fragment. */
1337 _mbuffer_head_pop_first(&session->internals.
1338 record_recv_buffer);
1339 _mbuffer_xfree(&bufel);
1340 return gnutls_assert_val(GNUTLS_E_AGAIN);
1343 if (IS_DTLS(session)) {
1344 session->internals.dtls.packets_dropped++;
1345 ret = gnutls_assert_val(GNUTLS_E_AGAIN);
1349 session_unresumable(session);
1350 session_invalidate(session);
1353 _mbuffer_xfree(&decrypted);
1358 && (gnutls_error_is_fatal(ret) == 0
1359 || ret == GNUTLS_E_TIMEDOUT))
1362 if (type == GNUTLS_ALERT) { /* we were expecting close notify */
1363 session_invalidate(session);
1368 if (IS_DTLS(session)) {
1372 session_invalidate(session);
1373 session_unresumable(session);
1376 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1381 /* This function behaves exactly like read(). The only difference is
1382 * that it accepts the gnutls_session_t and the content_type_t of data to
1383 * receive (if called by the user the Content is Userdata only)
1384 * It is intended to receive data, under the current session.
1386 * The gnutls_handshake_description_t was introduced to support SSL V2.0 client hellos.
1389 _gnutls_recv_int(gnutls_session_t session, content_type_t type,
1390 gnutls_handshake_description_t htype,
1391 gnutls_packet_t *packet,
1392 uint8_t * data, size_t data_size, void *seq,
1397 if (packet == NULL && (type != GNUTLS_ALERT && type != GNUTLS_HEARTBEAT)
1398 && (data_size == 0 || data == NULL))
1399 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
1401 if (session->internals.read_eof != 0) {
1402 /* if we have already read an EOF
1405 } else if (session_is_valid(session) != 0
1406 || session->internals.may_not_read != 0) {
1408 return GNUTLS_E_INVALID_SESSION;
1411 switch (session->internals.recv_state) {
1412 case RECV_STATE_DTLS_RETRANSMIT:
1413 ret = _dtls_retransmit(session);
1415 return gnutls_assert_val(ret);
1417 session->internals.recv_state = RECV_STATE_0;
1420 _dtls_async_timer_check(session);
1422 if (packet == NULL) {
1423 /* If we have enough data in the cache do not bother receiving
1424 * a new packet. (in order to flush the cache)
1426 ret = check_buffers(session, type, data, data_size, seq);
1430 ret = _gnutls_recv_in_buffers(session, type, htype, ms);
1431 if (ret < 0 && ret != GNUTLS_E_SESSION_EOF)
1432 return gnutls_assert_val(ret);
1434 return check_buffers(session, type, data, data_size, seq);
1436 ret = check_packet_buffers(session, type, packet);
1440 ret = _gnutls_recv_in_buffers(session, type, -1, ms);
1441 if (ret < 0 && ret != GNUTLS_E_SESSION_EOF)
1442 return gnutls_assert_val(ret);
1444 return check_packet_buffers(session, type, packet);
1447 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1452 * gnutls_packet_get:
1453 * @packet: is a #gnutls_packet_t structure.
1454 * @data: will contain the data present in the @packet structure (may be %NULL)
1455 * @sequence: the 8-bytes of the packet sequence number (may be %NULL)
1457 * This function returns the data and sequence number associated with
1458 * the received packet.
1463 void gnutls_packet_get(gnutls_packet_t packet, gnutls_datum_t *data, unsigned char *sequence)
1465 if (unlikely(packet == NULL)) {
1474 memcpy(sequence, packet->record_sequence.i, 8);
1478 data->size = packet->msg.size - packet->mark;
1479 data->data = packet->msg.data + packet->mark;
1484 * gnutls_packet_deinit:
1485 * @packet: is a pointer to a #gnutls_packet_st structure.
1487 * This function will deinitialize all data associated with
1488 * the received packet.
1492 void gnutls_packet_deinit(gnutls_packet_t packet)
1494 gnutls_free(packet);
1498 * gnutls_record_recv_packet:
1499 * @session: is a #gnutls_session_t structure.
1500 * @packet: the structure that will hold the packet data
1502 * This is a lower-level function thatn gnutls_record_recv() and allows
1503 * to directly receive the whole decrypted packet. That avoids a
1504 * memory copy, and is mostly applicable to applications seeking high
1507 * The received packet is accessed using gnutls_packet_get() and
1508 * must be deinitialized using gnutls_packet_deinit(). The returned
1509 * packet will be %NULL if the return value is zero (EOF).
1511 * Returns: The number of bytes received and zero on EOF (for stream
1512 * connections). A negative error code is returned in case of an error.
1517 gnutls_record_recv_packet(gnutls_session_t session,
1518 gnutls_packet_t *packet)
1520 return _gnutls_recv_int(session, GNUTLS_APPLICATION_DATA, -1, packet,
1522 session->internals.record_timeout_ms);
1526 * gnutls_record_send:
1527 * @session: is a #gnutls_session_t structure.
1528 * @data: contains the data to send
1529 * @data_size: is the length of the data
1531 * This function has the similar semantics with send(). The only
1532 * difference is that it accepts a GnuTLS session, and uses different
1534 * Note that if the send buffer is full, send() will block this
1535 * function. See the send() documentation for more information.
1537 * You can replace the default push function which is send(), by using
1538 * gnutls_transport_set_push_function().
1540 * If the EINTR is returned by the internal push function
1541 * then %GNUTLS_E_INTERRUPTED will be returned. If
1542 * %GNUTLS_E_INTERRUPTED or %GNUTLS_E_AGAIN is returned, you must
1543 * call this function again, with the exact same parameters; alternatively
1544 * you could provide a %NULL pointer for data, and 0 for
1545 * size. cf. gnutls_record_get_direction().
1547 * Note that in DTLS this function will return the %GNUTLS_E_LARGE_PACKET
1548 * error code if the send data exceed the data MTU value - as returned
1549 * by gnutls_dtls_get_data_mtu(). The errno value EMSGSIZE
1550 * also maps to %GNUTLS_E_LARGE_PACKET.
1551 * Note that since 3.2.13 this function can be called under cork in DTLS
1552 * mode, and will refuse to send data over the MTU size by returning
1553 * %GNUTLS_E_LARGE_PACKET.
1555 * Returns: The number of bytes sent, or a negative error code. The
1556 * number of bytes sent might be less than @data_size. The maximum
1557 * number of bytes this function can send in a single call depends
1558 * on the negotiated maximum record size.
1561 gnutls_record_send(gnutls_session_t session, const void *data,
1564 if (session->internals.record_flush_mode == RECORD_FLUSH) {
1565 return _gnutls_send_int(session, GNUTLS_APPLICATION_DATA,
1566 -1, EPOCH_WRITE_CURRENT, data,
1567 data_size, MBUFFER_FLUSH);
1568 } else { /* GNUTLS_CORKED */
1572 if (IS_DTLS(session)) {
1573 if (data_size + session->internals.record_presend_buffer.length >
1574 gnutls_dtls_get_data_mtu(session)) {
1575 return gnutls_assert_val(GNUTLS_E_LARGE_PACKET);
1580 _gnutls_buffer_append_data(&session->internals.
1581 record_presend_buffer, data,
1584 return gnutls_assert_val(ret);
1592 * @session: is a #gnutls_session_t structure.
1594 * If called gnutls_record_send() will no longer send partial records.
1595 * All queued records will be sent when gnutls_uncork() is called, or
1596 * when the maximum record size is reached.
1598 * This function is safe to use with DTLS after GnuTLS 3.3.0.
1602 void gnutls_record_cork(gnutls_session_t session)
1604 session->internals.record_flush_mode = RECORD_CORKED;
1609 * @session: is a #gnutls_session_t structure.
1610 * @flags: Could be zero or %GNUTLS_RECORD_WAIT
1612 * This resets the effect of gnutls_cork(), and flushes any pending
1613 * data. If the %GNUTLS_RECORD_WAIT flag is specified then this
1614 * function will block until the data is sent or a fatal error
1615 * occurs (i.e., the function will retry on %GNUTLS_E_AGAIN and
1616 * %GNUTLS_E_INTERRUPTED).
1618 * If the flag %GNUTLS_RECORD_WAIT is not specified and the function
1619 * is interrupted then the %GNUTLS_E_AGAIN or %GNUTLS_E_INTERRUPTED
1620 * errors will be returned. To obtain the data left in the corked
1621 * buffer use gnutls_record_check_corked().
1623 * Returns: On success the number of transmitted data is returned, or
1624 * otherwise a negative error code.
1628 int gnutls_record_uncork(gnutls_session_t session, unsigned int flags)
1633 if (session->internals.record_flush_mode == RECORD_FLUSH)
1634 return 0; /* nothing to be done */
1636 session->internals.record_flush_mode = RECORD_FLUSH;
1638 while (session->internals.record_presend_buffer.length > 0) {
1639 if (flags == GNUTLS_RECORD_WAIT) {
1642 gnutls_record_send(session,
1644 record_presend_buffer.
1647 record_presend_buffer.
1650 while (ret < 0 && (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED));
1653 gnutls_record_send(session,
1655 record_presend_buffer.data,
1657 record_presend_buffer.
1663 session->internals.record_presend_buffer.data += ret;
1664 session->internals.record_presend_buffer.length -= ret;
1671 session->internals.record_flush_mode = RECORD_CORKED;
1676 * gnutls_record_recv:
1677 * @session: is a #gnutls_session_t structure.
1678 * @data: the buffer that the data will be read into
1679 * @data_size: the number of requested bytes
1681 * This function has the similar semantics with recv(). The only
1682 * difference is that it accepts a GnuTLS session, and uses different
1684 * In the special case that a server requests a renegotiation, the
1685 * client may receive an error code of %GNUTLS_E_REHANDSHAKE. This
1686 * message may be simply ignored, replied with an alert
1687 * %GNUTLS_A_NO_RENEGOTIATION, or replied with a new handshake,
1688 * depending on the client's will.
1689 * If %EINTR is returned by the internal push function (the default
1690 * is recv()) then %GNUTLS_E_INTERRUPTED will be returned. If
1691 * %GNUTLS_E_INTERRUPTED or %GNUTLS_E_AGAIN is returned, you must
1692 * call this function again to get the data. See also
1693 * gnutls_record_get_direction().
1694 * A server may also receive %GNUTLS_E_REHANDSHAKE when a client has
1695 * initiated a handshake. In that case the server can only initiate a
1696 * handshake or terminate the connection.
1698 * Returns: The number of bytes received and zero on EOF (for stream
1699 * connections). A negative error code is returned in case of an error.
1700 * The number of bytes received might be less than the requested @data_size.
1703 gnutls_record_recv(gnutls_session_t session, void *data, size_t data_size)
1705 return _gnutls_recv_int(session, GNUTLS_APPLICATION_DATA, -1, NULL,
1706 data, data_size, NULL,
1707 session->internals.record_timeout_ms);
1711 * gnutls_record_recv_seq:
1712 * @session: is a #gnutls_session_t structure.
1713 * @data: the buffer that the data will be read into
1714 * @data_size: the number of requested bytes
1715 * @seq: is the packet's 64-bit sequence number. Should have space for 8 bytes.
1717 * This function is the same as gnutls_record_recv(), except that
1718 * it returns in addition to data, the sequence number of the data.
1719 * This is useful in DTLS where record packets might be received
1720 * out-of-order. The returned 8-byte sequence number is an
1721 * integer in big-endian format and should be
1722 * treated as a unique message identification.
1724 * Returns: The number of bytes received and zero on EOF. A negative
1725 * error code is returned in case of an error. The number of bytes
1726 * received might be less than @data_size.
1731 gnutls_record_recv_seq(gnutls_session_t session, void *data,
1732 size_t data_size, unsigned char *seq)
1734 return _gnutls_recv_int(session, GNUTLS_APPLICATION_DATA, -1, NULL,
1735 data, data_size, seq,
1736 session->internals.record_timeout_ms);
1740 * gnutls_record_set_timeout:
1741 * @session: is a #gnutls_session_t structure.
1742 * @ms: is a timeout value in milliseconds
1744 * This function sets the receive timeout for the record layer
1745 * to the provided value. Use an @ms value of zero to disable
1746 * timeout (the default).
1750 void gnutls_record_set_timeout(gnutls_session_t session, unsigned int ms)
1752 session->internals.record_timeout_ms = ms;