no need to check for DTLS
[gnutls.git] / lib / gnutls_record.c
blobe6250f84f179e0e204c4be3e284749dc2b03a2ae
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 <gnutls_state.h>
50 #include <gnutls_dtls.h>
51 #include <gnutls_dh.h>
53 struct tls_record_st {
54 uint16_t header_size;
55 uint8_t version[2];
56 uint64 sequence; /* DTLS */
57 uint16_t length;
58 uint16_t packet_size; /* header_size + length */
59 content_type_t type;
60 uint16_t epoch; /* valid in DTLS only */
61 int v2:1; /* whether an SSLv2 client hello */
62 /* the data */
65 /**
66 * gnutls_record_disable_padding:
67 * @session: is a #gnutls_session_t structure.
69 * Used to disabled padding in TLS 1.0 and above. Normally you do not
70 * need to use this function, but there are buggy clients that
71 * complain if a server pads the encrypted data. This of course will
72 * disable protection against statistical attacks on the data.
74 * Normally only servers that require maximum compatibility with everything
75 * out there, need to call this function.
76 **/
77 void
78 gnutls_record_disable_padding (gnutls_session_t session)
80 session->internals.priorities.no_padding = 1;
83 /**
84 * gnutls_transport_set_ptr:
85 * @session: is a #gnutls_session_t structure.
86 * @ptr: is the value.
88 * Used to set the first argument of the transport function (for push
89 * and pull callbacks). In berkeley style sockets this function will set the
90 * connection descriptor.
91 **/
92 void
93 gnutls_transport_set_ptr (gnutls_session_t session,
94 gnutls_transport_ptr_t ptr)
96 session->internals.transport_recv_ptr = ptr;
97 session->internals.transport_send_ptr = ptr;
101 * gnutls_transport_set_ptr2:
102 * @session: is a #gnutls_session_t structure.
103 * @recv_ptr: is the value for the pull function
104 * @send_ptr: is the value for the push function
106 * Used to set the first argument of the transport function (for push
107 * and pull callbacks). In berkeley style sockets this function will set the
108 * connection descriptor. With this function you can use two different
109 * pointers for receiving and sending.
111 void
112 gnutls_transport_set_ptr2 (gnutls_session_t session,
113 gnutls_transport_ptr_t recv_ptr,
114 gnutls_transport_ptr_t send_ptr)
116 session->internals.transport_send_ptr = send_ptr;
117 session->internals.transport_recv_ptr = recv_ptr;
121 * gnutls_transport_get_ptr:
122 * @session: is a #gnutls_session_t structure.
124 * Used to get the first argument of the transport function (like
125 * PUSH and PULL). This must have been set using
126 * gnutls_transport_set_ptr().
128 * Returns: The first argument of the transport function.
130 gnutls_transport_ptr_t
131 gnutls_transport_get_ptr (gnutls_session_t session)
133 return session->internals.transport_recv_ptr;
137 * gnutls_transport_get_ptr2:
138 * @session: is a #gnutls_session_t structure.
139 * @recv_ptr: will hold the value for the pull function
140 * @send_ptr: will hold the value for the push function
142 * Used to get the arguments of the transport functions (like PUSH
143 * and PULL). These should have been set using
144 * gnutls_transport_set_ptr2().
146 void
147 gnutls_transport_get_ptr2 (gnutls_session_t session,
148 gnutls_transport_ptr_t * recv_ptr,
149 gnutls_transport_ptr_t * send_ptr)
152 *recv_ptr = session->internals.transport_recv_ptr;
153 *send_ptr = session->internals.transport_send_ptr;
157 * gnutls_bye:
158 * @session: is a #gnutls_session_t structure.
159 * @how: is an integer
161 * Terminates the current TLS/SSL connection. The connection should
162 * have been initiated using gnutls_handshake(). @how should be one
163 * of %GNUTLS_SHUT_RDWR, %GNUTLS_SHUT_WR.
165 * In case of %GNUTLS_SHUT_RDWR the TLS session gets
166 * terminated and further receives and sends will be disallowed. If
167 * the return value is zero you may continue using the underlying
168 * transport layer. %GNUTLS_SHUT_RDWR sends an alert containing a close
169 * request and waits for the peer to reply with the same message.
171 * In case of %GNUTLS_SHUT_WR the TLS session gets terminated
172 * and further sends will be disallowed. In order to reuse the
173 * connection you should wait for an EOF from the peer.
174 * %GNUTLS_SHUT_WR sends an alert containing a close request.
176 * Note that not all implementations will properly terminate a TLS
177 * connection. Some of them, usually for performance reasons, will
178 * terminate only the underlying transport layer, and thus not
179 * distinguishing between a malicious party prematurely terminating
180 * the connection and normal termination.
182 * This function may also return %GNUTLS_E_AGAIN or
183 * %GNUTLS_E_INTERRUPTED; cf. gnutls_record_get_direction().
185 * Returns: %GNUTLS_E_SUCCESS on success, or an error code, see
186 * function documentation for entire semantics.
189 gnutls_bye (gnutls_session_t session, gnutls_close_request_t how)
191 int ret = 0;
193 switch (STATE)
195 case STATE0:
196 case STATE60:
197 ret = _gnutls_io_write_flush (session);
198 STATE = STATE60;
199 if (ret < 0)
201 gnutls_assert ();
202 return ret;
205 case STATE61:
206 ret =
207 gnutls_alert_send (session, GNUTLS_AL_WARNING, GNUTLS_A_CLOSE_NOTIFY);
208 STATE = STATE61;
209 if (ret < 0)
211 gnutls_assert ();
212 return ret;
215 case STATE62:
216 STATE = STATE62;
217 if (how == GNUTLS_SHUT_RDWR)
221 ret = _gnutls_recv_int (session, GNUTLS_ALERT, -1, NULL, 0, NULL);
223 while (ret == GNUTLS_E_GOT_APPLICATION_DATA);
225 if (ret >= 0)
226 session->internals.may_not_read = 1;
228 if (ret < 0)
230 gnutls_assert ();
231 return ret;
234 STATE = STATE62;
236 break;
237 default:
238 gnutls_assert ();
239 return GNUTLS_E_INTERNAL_ERROR;
242 STATE = STATE0;
244 session->internals.may_not_write = 1;
245 return 0;
248 inline static void
249 session_invalidate (gnutls_session_t session)
251 session->internals.invalid_connection = 1;
255 inline static void
256 session_unresumable (gnutls_session_t session)
258 session->internals.resumable = RESUME_FALSE;
261 /* returns 0 if session is valid
263 inline static int
264 session_is_valid (gnutls_session_t session)
266 if (session->internals.invalid_connection != 0)
267 return GNUTLS_E_INVALID_SESSION;
269 return 0;
272 /* Copies the record version into the headers. The
273 * version must have 2 bytes at least.
275 inline static void
276 copy_record_version (gnutls_session_t session,
277 gnutls_handshake_description_t htype, uint8_t version[2])
279 gnutls_protocol_t lver;
281 if (session->internals.initial_negotiation_completed || htype != GNUTLS_HANDSHAKE_CLIENT_HELLO
282 || session->internals.default_record_version[0] == 0)
284 lver = gnutls_protocol_get_version (session);
286 version[0] = _gnutls_version_get_major (lver);
287 version[1] = _gnutls_version_get_minor (lver);
289 else
291 version[0] = session->internals.default_record_version[0];
292 version[1] = session->internals.default_record_version[1];
296 /* Increments the sequence value
298 inline static int
299 sequence_increment (gnutls_session_t session,
300 uint64 * value)
302 if (IS_DTLS(session))
304 return _gnutls_uint48pp(value);
306 else
308 return _gnutls_uint64pp(value);
312 /* This function behaves exactly like write(). The only difference is
313 * that it accepts, the gnutls_session_t and the content_type_t of data to
314 * send (if called by the user the Content is specific)
315 * It is intended to transfer data, under the current session.
317 * Oct 30 2001: Removed capability to send data more than MAX_RECORD_SIZE.
318 * This makes the function much easier to read, and more error resistant
319 * (there were cases were the old function could mess everything up).
320 * --nmav
322 * This function may accept a NULL pointer for data, and 0 for size, if
323 * and only if the previous send was interrupted for some reason.
326 ssize_t
327 _gnutls_send_int (gnutls_session_t session, content_type_t type,
328 gnutls_handshake_description_t htype,
329 unsigned int epoch_rel, const void *_data,
330 size_t data_size, unsigned int mflags)
332 mbuffer_st *bufel;
333 ssize_t cipher_size;
334 int retval, ret;
335 int send_data_size;
336 uint8_t headers[MAX_RECORD_HEADER_SIZE];
337 int header_size;
338 const uint8_t *data = _data;
339 record_parameters_st *record_params;
340 record_state_st *record_state;
342 ret = _gnutls_epoch_get (session, epoch_rel, &record_params);
343 if (ret < 0)
344 return gnutls_assert_val(ret);
346 /* Safeguard against processing data with an incomplete cipher state. */
347 if (!record_params->initialized)
348 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
350 record_state = &record_params->write;
352 /* Do not allow null pointer if the send buffer is empty.
353 * If the previous send was interrupted then a null pointer is
354 * ok, and means to resume.
356 if (session->internals.record_send_buffer.byte_length == 0 &&
357 (data_size == 0 && _data == NULL))
359 gnutls_assert ();
360 return GNUTLS_E_INVALID_REQUEST;
363 if (type != GNUTLS_ALERT) /* alert messages are sent anyway */
364 if (session_is_valid (session) || session->internals.may_not_write != 0)
366 gnutls_assert ();
367 return GNUTLS_E_INVALID_SESSION;
370 headers[0] = type;
372 /* Use the default record version, if it is
373 * set.
375 copy_record_version (session, htype, &headers[1]);
377 header_size = RECORD_HEADER_SIZE(session);
378 /* Adjust header length and add sequence for DTLS */
379 if (IS_DTLS(session))
380 memcpy(&headers[3], &record_state->sequence_number.i, 8);
382 _gnutls_record_log
383 ("REC[%p]: Preparing Packet %s(%d) with length: %d\n", session,
384 _gnutls_packet2str (type), type, (int) data_size);
386 if (data_size > MAX_RECORD_SEND_SIZE(session))
387 send_data_size = MAX_RECORD_SEND_SIZE(session);
388 else
389 send_data_size = data_size;
391 /* Only encrypt if we don't have data to send
392 * from the previous run. - probably interrupted.
394 if (mflags != 0 && session->internals.record_send_buffer.byte_length > 0)
396 ret = _gnutls_io_write_flush (session);
397 if (ret > 0)
398 cipher_size = ret;
399 else
400 cipher_size = 0;
402 retval = session->internals.record_send_buffer_user_size;
404 else
406 /* now proceed to packet encryption
408 cipher_size = send_data_size + MAX_RECORD_OVERHEAD + CIPHER_SLACK_SIZE;
409 bufel = _mbuffer_alloc (cipher_size, cipher_size);
410 if (bufel == NULL)
411 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
413 ret =
414 _gnutls_encrypt (session, headers, header_size, data,
415 send_data_size, _mbuffer_get_udata_ptr (bufel),
416 cipher_size, type, record_params);
417 if (ret <= 0)
419 gnutls_assert ();
420 if (ret == 0)
421 ret = GNUTLS_E_ENCRYPTION_FAILED;
422 gnutls_free (bufel);
423 return ret; /* error */
426 cipher_size = ret;
427 retval = send_data_size;
428 session->internals.record_send_buffer_user_size = send_data_size;
430 /* increase sequence number
432 if (sequence_increment (session, &record_state->sequence_number) != 0)
434 session_invalidate (session);
435 gnutls_free (bufel);
436 return gnutls_assert_val(GNUTLS_E_RECORD_LIMIT_REACHED);
439 _mbuffer_set_udata_size (bufel, cipher_size);
440 ret = _gnutls_io_write_buffered (session, bufel, mflags);
443 if (ret != cipher_size)
445 /* If we have sent any data then just return
446 * the error value. Do not invalidate the session.
448 if (ret < 0 && gnutls_error_is_fatal (ret) == 0)
449 return gnutls_assert_val(ret);
451 if (ret > 0)
452 ret = gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
454 session_unresumable (session);
455 session->internals.may_not_write = 1;
456 return gnutls_assert_val(ret);
459 session->internals.record_send_buffer_user_size = 0;
461 _gnutls_record_log ("REC[%p]: Sent Packet[%d] %s(%d) in epoch %d and length: %d\n",
462 session,
463 (unsigned int)
464 _gnutls_uint64touint32
465 (&record_state->sequence_number),
466 _gnutls_packet2str (type), type,
467 (int) record_params->epoch,
468 (int) cipher_size);
470 return retval;
473 inline static int
474 check_recv_type (gnutls_session_t session, content_type_t recv_type)
476 switch (recv_type)
478 case GNUTLS_CHANGE_CIPHER_SPEC:
479 case GNUTLS_ALERT:
480 case GNUTLS_HANDSHAKE:
481 case GNUTLS_APPLICATION_DATA:
482 return 0;
483 default:
484 gnutls_assert ();
485 _gnutls_audit_log(session, "Received record packet of unknown type %u\n", (unsigned int)recv_type);
486 return GNUTLS_E_UNEXPECTED_PACKET;
492 /* Checks if there are pending data in the record buffers. If there are
493 * then it copies the data.
495 static int
496 check_buffers (gnutls_session_t session, content_type_t type,
497 uint8_t * data, int data_size, void* seq)
499 if ((type == GNUTLS_APPLICATION_DATA ||
500 type == GNUTLS_HANDSHAKE ||
501 type == GNUTLS_CHANGE_CIPHER_SPEC)
502 && _gnutls_record_buffer_get_size (session) > 0)
504 int ret;
505 ret = _gnutls_record_buffer_get (type, session, data, data_size, seq);
506 if (ret < 0)
508 if (IS_DTLS(session))
510 if (ret == GNUTLS_E_UNEXPECTED_PACKET)
512 ret = GNUTLS_E_AGAIN;
515 gnutls_assert ();
516 return ret;
519 return ret;
522 return 0;
527 /* Here we check if the advertized version is the one we
528 * negotiated in the handshake.
530 inline static int
531 record_check_version (gnutls_session_t session,
532 gnutls_handshake_description_t htype, uint8_t version[2])
534 if (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO)
536 /* Reject hello packets with major version higher than 3.
538 if (!(IS_DTLS(session)) && version[0] > 3)
540 gnutls_assert ();
541 _gnutls_record_log
542 ("REC[%p]: INVALID VERSION PACKET: (%d) %d.%d\n", session,
543 htype, version[0], version[1]);
544 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
547 else if (htype != GNUTLS_HANDSHAKE_SERVER_HELLO &&
548 gnutls_protocol_get_version (session) !=
549 _gnutls_version_get (version[0], version[1]))
551 /* Reject record packets that have a different version than the
552 * one negotiated. Note that this version is not protected by any
553 * mac. I don't really think that this check serves any purpose.
555 gnutls_assert ();
556 _gnutls_record_log ("REC[%p]: INVALID VERSION PACKET: (%d) %d.%d\n",
557 session, htype, version[0], version[1]);
559 return GNUTLS_E_UNSUPPORTED_VERSION_PACKET;
562 return 0;
565 /* This function will check if the received record type is
566 * the one we actually expect and adds it to the proper
567 * buffer. The bufel will be deinitialized after calling
568 * this function, even if it fails.
570 static int
571 record_add_to_buffers (gnutls_session_t session,
572 struct tls_record_st *recv, content_type_t type,
573 gnutls_handshake_description_t htype,
574 uint64* seq,
575 mbuffer_st* bufel)
578 int ret;
580 if ((recv->type == type)
581 && (type == GNUTLS_APPLICATION_DATA ||
582 type == GNUTLS_CHANGE_CIPHER_SPEC ||
583 type == GNUTLS_HANDSHAKE))
585 _gnutls_record_buffer_put (session, type, seq, bufel);
587 /* if we received application data as expected then we
588 * deactivate the async timer */
589 _dtls_async_timer_delete(session);
591 else
593 /* if the expected type is different than the received
595 switch (recv->type)
597 case GNUTLS_ALERT:
598 if (bufel->msg.size < 2)
600 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
601 goto unexpected_packet;
604 _gnutls_record_log
605 ("REC[%p]: Alert[%d|%d] - %s - was received\n", session,
606 bufel->msg.data[0], bufel->msg.data[1], gnutls_alert_get_name ((int) bufel->msg.data[1]));
608 session->internals.last_alert = bufel->msg.data[1];
610 /* if close notify is received and
611 * the alert is not fatal
613 if (bufel->msg.data[1] == GNUTLS_A_CLOSE_NOTIFY && bufel->msg.data[0] != GNUTLS_AL_FATAL)
615 /* If we have been expecting for an alert do
617 session->internals.read_eof = 1;
618 ret = GNUTLS_E_SESSION_EOF;
619 goto cleanup;
621 else
623 /* if the alert is FATAL or WARNING
624 * return the apropriate message
627 gnutls_assert ();
628 ret = GNUTLS_E_WARNING_ALERT_RECEIVED;
629 if (bufel->msg.data[0] == GNUTLS_AL_FATAL)
631 session_unresumable (session);
632 session_invalidate (session);
633 ret = gnutls_assert_val(GNUTLS_E_FATAL_ALERT_RECEIVED);
635 goto cleanup;
637 break;
639 case GNUTLS_CHANGE_CIPHER_SPEC:
640 if (!(IS_DTLS(session)))
641 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
643 _gnutls_record_buffer_put (session, recv->type, seq, bufel);
645 break;
646 case GNUTLS_APPLICATION_DATA:
647 if (session->internals.initial_negotiation_completed == 0)
649 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
650 goto unexpected_packet;
654 /* the got_application data is only returned
655 * if expecting client hello (for rehandshake
656 * reasons). Otherwise it is an unexpected packet
658 if (type == GNUTLS_ALERT || (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO
659 && type == GNUTLS_HANDSHAKE))
661 /* even if data is unexpected put it into the buffer */
662 if ((ret =
663 _gnutls_record_buffer_put (session, recv->type, seq,
664 bufel)) < 0)
666 gnutls_assert ();
667 goto cleanup;
670 return gnutls_assert_val(GNUTLS_E_GOT_APPLICATION_DATA);
672 else
674 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
675 goto unexpected_packet;
678 break;
679 case GNUTLS_HANDSHAKE:
680 /* In DTLS we might receive a handshake replay from the peer to indicate
681 * the our last TLS handshake messages were not received.
683 if (IS_DTLS(session))
685 if (type == GNUTLS_CHANGE_CIPHER_SPEC)
687 ret = gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET);
688 goto unexpected_packet;
691 if (_dtls_is_async(session) && _dtls_async_timer_active(session))
693 if (session->security_parameters.entity == GNUTLS_SERVER &&
694 bufel->htype == GNUTLS_HANDSHAKE_CLIENT_HELLO)
696 /* client requested rehandshake. Delete the timer */
697 _dtls_async_timer_delete(session);
699 else
701 ret = _dtls_retransmit(session);
702 if (ret == 0)
704 ret = gnutls_assert_val(GNUTLS_E_AGAIN);
705 goto unexpected_packet;
707 goto cleanup;
712 /* This is legal if HELLO_REQUEST is received - and we are a client.
713 * If we are a server, a client may initiate a renegotiation at any time.
715 if (session->security_parameters.entity == GNUTLS_SERVER &&
716 bufel->htype == GNUTLS_HANDSHAKE_CLIENT_HELLO)
718 gnutls_assert ();
719 ret =
720 _gnutls_record_buffer_put (session, recv->type, seq, bufel);
721 if (ret < 0)
723 gnutls_assert ();
724 goto cleanup;
726 return GNUTLS_E_REHANDSHAKE;
729 /* If we are already in a handshake then a Hello
730 * Request is illegal. But here we don't really care
731 * since this message will never make it up here.
734 /* So we accept it, if it is a Hello. If not, this will
735 * fail and trigger flight retransmissions after some time. */
736 ret = _gnutls_recv_hello_request (session, bufel->msg.data, bufel->msg.size);
737 goto unexpected_packet;
739 break;
740 default:
742 _gnutls_record_log
743 ("REC[%p]: Received Unknown packet %d expecting %d\n",
744 session, recv->type, type);
746 gnutls_assert ();
747 ret = GNUTLS_E_UNEXPECTED_PACKET;
748 goto unexpected_packet;
752 return 0;
754 unexpected_packet:
755 if (IS_DTLS(session) && ret != GNUTLS_E_REHANDSHAKE)
757 _mbuffer_xfree(&bufel);
758 RETURN_DTLS_EAGAIN_OR_TIMEOUT(session, ret);
761 cleanup:
762 _mbuffer_xfree(&bufel);
763 return ret;
767 int _gnutls_get_max_decrypted_data(gnutls_session_t session)
769 int ret;
771 if (gnutls_compression_get (session) != GNUTLS_COMP_NULL ||
772 session->internals.priorities.allow_large_records != 0)
773 ret = MAX_RECORD_RECV_SIZE(session) + EXTRA_COMP_SIZE;
774 else
775 ret = MAX_RECORD_RECV_SIZE(session);
777 return ret;
780 /* Checks the record headers and returns the length, version and
781 * content type.
783 static void
784 record_read_headers (gnutls_session_t session,
785 uint8_t headers[MAX_RECORD_HEADER_SIZE],
786 content_type_t type,
787 gnutls_handshake_description_t htype,
788 struct tls_record_st* record)
791 /* Read the first two bytes to determine if this is a
792 * version 2 message
795 if (htype == GNUTLS_HANDSHAKE_CLIENT_HELLO && type == GNUTLS_HANDSHAKE
796 && headers[0] > 127 && !(IS_DTLS(session)))
799 /* if msb set and expecting handshake message
800 * it should be SSL 2 hello
802 record->version[0] = 3; /* assume SSL 3.0 */
803 record->version[1] = 0;
805 record->length = (((headers[0] & 0x7f) << 8)) | headers[1];
807 /* SSL 2.0 headers */
808 record->header_size = record->packet_size = 2;
809 record->type = GNUTLS_HANDSHAKE; /* we accept only v2 client hello
812 /* in order to assist the handshake protocol.
813 * V2 compatibility is a mess.
815 record->v2 = 1;
816 record->epoch = 0;
818 _gnutls_record_log ("REC[%p]: SSL 2.0 %s packet received. Length: %d\n",
819 session,
820 _gnutls_packet2str (record->type),
821 record->length);
824 else
826 /* dtls version 1.0 and TLS version 1.x */
827 record->v2 = 0;
829 record->type = headers[0];
830 record->version[0] = headers[1];
831 record->version[1] = headers[2];
833 if(IS_DTLS(session))
835 memcpy(record->sequence.i, &headers[3], 8);
836 record->length = _gnutls_read_uint16 (&headers[11]);
837 record->epoch = _gnutls_read_uint16(record->sequence.i);
839 else
841 record->length = _gnutls_read_uint16 (&headers[3]);
842 record->epoch = 0;
845 _gnutls_record_log ("REC[%p]: SSL %d.%d %s packet received. Epoch %d, length: %d\n",
846 session, (int)record->version[0], (int)record->version[1],
847 _gnutls_packet2str (record->type),
848 (int)record->epoch, record->length);
852 record->packet_size += record->length;
856 static int recv_headers( gnutls_session_t session, content_type_t type,
857 gnutls_handshake_description_t htype, struct tls_record_st* record)
859 int ret;
860 gnutls_datum_t raw; /* raw headers */
861 /* Read the headers.
863 record->header_size = record->packet_size = RECORD_HEADER_SIZE(session);
865 if ((ret =
866 _gnutls_io_read_buffered (session, record->header_size, -1)) != record->header_size)
868 if (ret < 0 && gnutls_error_is_fatal (ret) == 0)
869 return ret;
871 if (ret > 0)
872 ret = GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
873 else if (ret == 0)
874 ret = GNUTLS_E_PREMATURE_TERMINATION;
876 return gnutls_assert_val(ret);
879 ret = _mbuffer_linearize (&session->internals.record_recv_buffer);
880 if (ret < 0)
881 return gnutls_assert_val(ret);
883 _mbuffer_head_get_first (&session->internals.record_recv_buffer, &raw);
884 if (raw.size < RECORD_HEADER_SIZE(session))
885 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
887 record_read_headers (session, raw.data, type, htype, record);
889 /* Check if the DTLS epoch is valid */
890 if (IS_DTLS(session))
892 if (_gnutls_epoch_is_valid(session, record->epoch) == 0)
894 _gnutls_audit_log(session, "Discarded message[%u] with invalid epoch %u.\n",
895 (unsigned int)_gnutls_uint64touint32 (&record->sequence),
896 (unsigned int)record->sequence.i[0]*256+(unsigned int)record->sequence.i[1]);
897 gnutls_assert();
898 /* doesn't matter, just a fatal error */
899 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
903 /* Here we check if the Type of the received packet is
904 * ok.
906 if ((ret = check_recv_type (session, record->type)) < 0)
907 return gnutls_assert_val(ret);
909 /* Here we check if the advertized version is the one we
910 * negotiated in the handshake.
912 if ((ret = record_check_version (session, htype, record->version)) < 0)
913 return gnutls_assert_val(ret);
915 if (record->length > MAX_RECV_SIZE(session))
917 _gnutls_audit_log
918 (session, "Received packet with illegal length: %u\n", (unsigned int)record->length);
919 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
922 _gnutls_record_log
923 ("REC[%p]: Expected Packet %s(%d)\n", session,
924 _gnutls_packet2str (type), type);
925 _gnutls_record_log ("REC[%p]: Received Packet %s(%d) with length: %d\n",
926 session,
927 _gnutls_packet2str (record->type), record->type, record->length);
930 return 0;
933 #define MAX_EMPTY_PACKETS_SEQUENCE 4
935 /* This will receive record layer packets and add them to
936 * application_data_buffer and handshake_data_buffer.
938 ssize_t
939 _gnutls_recv_in_buffers (gnutls_session_t session, content_type_t type,
940 gnutls_handshake_description_t htype)
942 uint64 *packet_sequence;
943 uint8_t *ciphertext;
944 mbuffer_st* bufel = NULL, *decrypted = NULL;
945 int ret;
946 int empty_packet = 0;
947 record_parameters_st *record_params;
948 record_state_st *record_state;
949 struct tls_record_st record;
951 begin:
953 if (empty_packet > MAX_EMPTY_PACKETS_SEQUENCE)
955 gnutls_assert ();
956 return GNUTLS_E_TOO_MANY_EMPTY_PACKETS;
959 memset(&record, 0, sizeof(record));
961 if (session->internals.read_eof != 0)
963 /* if we have already read an EOF
965 return 0;
967 else if (session_is_valid (session) != 0
968 || session->internals.may_not_read != 0)
969 return gnutls_assert_val(GNUTLS_E_INVALID_SESSION);
971 /* get the record state parameters */
972 ret = _gnutls_epoch_get (session, EPOCH_READ_CURRENT, &record_params);
973 if (ret < 0)
974 return gnutls_assert_val (ret);
976 /* Safeguard against processing data with an incomplete cipher state. */
977 if (!record_params->initialized)
978 return gnutls_assert_val (GNUTLS_E_INTERNAL_ERROR);
980 record_state = &record_params->read;
982 /* receive headers */
983 ret = recv_headers(session, type, htype, &record);
984 if (ret < 0)
986 ret = gnutls_assert_val_fatal(ret);
987 goto recv_error;
990 if (IS_DTLS(session))
991 packet_sequence = &record.sequence;
992 else
993 packet_sequence = &record_state->sequence_number;
995 /* Read the packet data and insert it to record_recv_buffer.
997 ret =
998 _gnutls_io_read_buffered (session, record.packet_size,
999 record.type);
1000 if (ret != record.packet_size)
1002 gnutls_assert();
1003 goto recv_error;
1006 /* ok now we are sure that we have read all the data - so
1007 * move on !
1009 ret = _mbuffer_linearize (&session->internals.record_recv_buffer);
1010 if (ret < 0)
1011 return gnutls_assert_val(ret);
1013 bufel = _mbuffer_head_get_first (&session->internals.record_recv_buffer, NULL);
1014 if (bufel == NULL)
1015 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1017 /* We allocate the maximum possible to allow few compressed bytes to expand to a
1018 * full record.
1020 decrypted = _mbuffer_alloc(MAX_RECORD_RECV_SIZE(session),
1021 MAX_RECORD_RECV_SIZE(session));
1022 if (decrypted == NULL)
1023 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
1025 ciphertext = (uint8_t*)_mbuffer_get_udata_ptr(bufel) + record.header_size;
1027 /* decrypt the data we got.
1029 ret =
1030 _gnutls_decrypt (session, ciphertext, record.length,
1031 _mbuffer_get_udata_ptr(decrypted), _mbuffer_get_udata_size(decrypted),
1032 record.type, record_params, packet_sequence);
1033 if (ret >= 0) _mbuffer_set_udata_size(decrypted, ret);
1035 _mbuffer_head_remove_bytes (&session->internals.record_recv_buffer,
1036 record.header_size + record.length);
1037 if (ret < 0)
1039 gnutls_assert();
1040 _gnutls_audit_log(session, "Discarded message[%u] due to invalid decryption\n",
1041 (unsigned int)_gnutls_uint64touint32 (packet_sequence));
1042 goto sanity_check_error;
1045 /* check for duplicates. We check after the message
1046 * is processed and authenticated to avoid someone
1047 * messing with our windows.
1049 if (IS_DTLS(session))
1051 ret = _dtls_record_check(record_params, packet_sequence);
1052 if (ret < 0)
1054 _gnutls_audit_log(session, "Discarded duplicate message[%u]: %s\n",
1055 (unsigned int) _gnutls_uint64touint32 (packet_sequence), _gnutls_packet2str (record.type));
1056 goto sanity_check_error;
1058 _gnutls_record_log
1059 ("REC[%p]: Decrypted Packet[%u.%u] %s(%d) with length: %d\n", session,
1060 (unsigned int)record.sequence.i[0]*256 +(unsigned int)record.sequence.i[1],
1061 (unsigned int) _gnutls_uint64touint32 (packet_sequence),
1062 _gnutls_packet2str (record.type), record.type, (int)_mbuffer_get_udata_size(decrypted));
1064 else
1066 _gnutls_record_log
1067 ("REC[%p]: Decrypted Packet[%u] %s(%d) with length: %d\n", session,
1068 (unsigned int) _gnutls_uint64touint32 (packet_sequence),
1069 _gnutls_packet2str (record.type), record.type, (int)_mbuffer_get_udata_size(decrypted));
1072 /* increase sequence number
1074 if (!IS_DTLS(session) && sequence_increment (session, &record_state->sequence_number) != 0)
1076 session_invalidate (session);
1077 gnutls_assert ();
1078 ret = GNUTLS_E_RECORD_LIMIT_REACHED;
1079 goto sanity_check_error;
1082 /* (originally for) TLS 1.0 CBC protection.
1083 * Actually this code is called if we just received
1084 * an empty packet. An empty TLS packet is usually
1085 * sent to protect some vulnerabilities in the CBC mode.
1086 * In that case we go to the beginning and start reading
1087 * the next packet.
1089 if (_mbuffer_get_udata_size(decrypted) == 0)
1091 _mbuffer_xfree(&decrypted);
1092 empty_packet++;
1093 goto begin;
1096 if (record.v2)
1097 decrypted->htype = GNUTLS_HANDSHAKE_CLIENT_HELLO_V2;
1098 else
1100 uint8_t * p = _mbuffer_get_udata_ptr(decrypted);
1101 decrypted->htype = p[0];
1104 ret =
1105 record_add_to_buffers (session, &record, type, htype,
1106 packet_sequence, decrypted);
1108 /* bufel is now either deinitialized or buffered somewhere else */
1110 if (ret < 0)
1111 return gnutls_assert_val(ret);
1113 return ret;
1115 discard:
1116 session->internals.dtls.packets_dropped++;
1118 /* discard the whole received fragment. */
1119 bufel = _mbuffer_head_pop_first(&session->internals.record_recv_buffer);
1120 _mbuffer_xfree(&bufel);
1121 return gnutls_assert_val(GNUTLS_E_AGAIN);
1123 sanity_check_error:
1124 if (IS_DTLS(session))
1126 session->internals.dtls.packets_dropped++;
1127 ret = gnutls_assert_val(GNUTLS_E_AGAIN);
1128 goto cleanup;
1131 session_unresumable (session);
1132 session_invalidate (session);
1134 cleanup:
1135 _mbuffer_xfree(&decrypted);
1136 return ret;
1138 recv_error:
1139 if (ret < 0 && gnutls_error_is_fatal (ret) == 0)
1140 return ret;
1142 if (IS_DTLS(session))
1144 goto discard;
1147 session_invalidate (session);
1148 if (type == GNUTLS_ALERT) /* we were expecting close notify */
1150 gnutls_assert ();
1151 return 0;
1153 session_unresumable (session);
1155 if (ret == 0)
1156 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
1157 else
1158 return ret;
1161 /* This function behaves exactly like read(). The only difference is
1162 * that it accepts the gnutls_session_t and the content_type_t of data to
1163 * receive (if called by the user the Content is Userdata only)
1164 * It is intended to receive data, under the current session.
1166 * The gnutls_handshake_description_t was introduced to support SSL V2.0 client hellos.
1168 ssize_t
1169 _gnutls_recv_int (gnutls_session_t session, content_type_t type,
1170 gnutls_handshake_description_t htype,
1171 uint8_t * data, size_t data_size, void* seq)
1173 int ret;
1175 if (type != GNUTLS_ALERT && (data_size == 0 || data == NULL))
1177 return GNUTLS_E_INVALID_REQUEST;
1180 if (session->internals.read_eof != 0)
1182 /* if we have already read an EOF
1184 return 0;
1186 else if (session_is_valid (session) != 0
1187 || session->internals.may_not_read != 0)
1189 gnutls_assert ();
1190 return GNUTLS_E_INVALID_SESSION;
1193 _dtls_async_timer_check(session);
1195 /* If we have enough data in the cache do not bother receiving
1196 * a new packet. (in order to flush the cache)
1198 ret = check_buffers (session, type, data, data_size, seq);
1199 if (ret != 0)
1200 return ret;
1202 ret = _gnutls_recv_in_buffers(session, type, htype);
1203 if (ret < 0 && ret != GNUTLS_E_SESSION_EOF)
1204 return gnutls_assert_val(ret);
1206 return check_buffers (session, type, data, data_size, seq);
1211 * gnutls_record_send:
1212 * @session: is a #gnutls_session_t structure.
1213 * @data: contains the data to send
1214 * @data_size: is the length of the data
1216 * This function has the similar semantics with send(). The only
1217 * difference is that it accepts a GnuTLS session, and uses different
1218 * error codes.
1219 * Note that if the send buffer is full, send() will block this
1220 * function. See the send() documentation for full information. You
1221 * can replace the default push function by using
1222 * gnutls_transport_set_ptr2() with a call to send() with a
1223 * MSG_DONTWAIT flag if blocking is a problem.
1224 * If the EINTR is returned by the internal push function (the
1225 * default is send()) then %GNUTLS_E_INTERRUPTED will be returned. If
1226 * %GNUTLS_E_INTERRUPTED or %GNUTLS_E_AGAIN is returned, you must
1227 * call this function again, with the same parameters; alternatively
1228 * you could provide a %NULL pointer for data, and 0 for
1229 * size. cf. gnutls_record_get_direction(). The errno value EMSGSIZE
1230 * maps to %GNUTLS_E_LARGE_PACKET.
1232 * Returns: The number of bytes sent, or a negative error code. The
1233 * number of bytes sent might be less than @data_size. The maximum
1234 * number of bytes this function can send in a single call depends
1235 * on the negotiated maximum record size.
1237 ssize_t
1238 gnutls_record_send (gnutls_session_t session, const void *data,
1239 size_t data_size)
1241 return _gnutls_send_int (session, GNUTLS_APPLICATION_DATA, -1,
1242 EPOCH_WRITE_CURRENT, data, data_size,
1243 MBUFFER_FLUSH);
1247 * gnutls_record_recv:
1248 * @session: is a #gnutls_session_t structure.
1249 * @data: the buffer that the data will be read into
1250 * @data_size: the number of requested bytes
1252 * This function has the similar semantics with recv(). The only
1253 * difference is that it accepts a GnuTLS session, and uses different
1254 * error codes.
1255 * In the special case that a server requests a renegotiation, the
1256 * client may receive an error code of %GNUTLS_E_REHANDSHAKE. This
1257 * message may be simply ignored, replied with an alert
1258 * %GNUTLS_A_NO_RENEGOTIATION, or replied with a new handshake,
1259 * depending on the client's will.
1260 * If %EINTR is returned by the internal push function (the default
1261 * is recv()) then %GNUTLS_E_INTERRUPTED will be returned. If
1262 * %GNUTLS_E_INTERRUPTED or %GNUTLS_E_AGAIN is returned, you must
1263 * call this function again to get the data. See also
1264 * gnutls_record_get_direction().
1265 * A server may also receive %GNUTLS_E_REHANDSHAKE when a client has
1266 * initiated a handshake. In that case the server can only initiate a
1267 * handshake or terminate the connection.
1269 * Returns: The number of bytes received and zero on EOF (for stream
1270 * connections). A negative error code is returned in case of an error.
1271 * The number of bytes received might be less than the requested @data_size.
1273 ssize_t
1274 gnutls_record_recv (gnutls_session_t session, void *data, size_t data_size)
1276 return _gnutls_recv_int (session, GNUTLS_APPLICATION_DATA, -1, data,
1277 data_size, NULL);
1281 * gnutls_record_recv_seq:
1282 * @session: is a #gnutls_session_t structure.
1283 * @data: the buffer that the data will be read into
1284 * @data_size: the number of requested bytes
1285 * @seq: is the packet's 64-bit sequence number. Should have space for 8 bytes.
1287 * This function is the same as gnutls_record_recv(), except that
1288 * it returns in addition to data, the sequence number of the data.
1289 * This is useful in DTLS where record packets might be received
1290 * out-of-order. The returned 8-byte sequence number is an
1291 * integer in big-endian format and should be
1292 * treated as a unique message identification.
1294 * Returns: The number of bytes received and zero on EOF. A negative
1295 * error code is returned in case of an error. The number of bytes
1296 * received might be less than @data_size.
1298 * Since: 3.0
1300 ssize_t
1301 gnutls_record_recv_seq (gnutls_session_t session, void *data, size_t data_size,
1302 unsigned char *seq)
1304 return _gnutls_recv_int (session, GNUTLS_APPLICATION_DATA, -1, data,
1305 data_size, seq);