updated licenses
[gnutls.git] / lib / gnutls_record.c
blob28d0ee899b19858ffcb05d11fbfa6857a573928f
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;
874 return gnutls_assert_val(ret);
877 ret = _mbuffer_linearize (&session->internals.record_recv_buffer);
878 if (ret < 0)
879 return gnutls_assert_val(ret);
881 _mbuffer_head_get_first (&session->internals.record_recv_buffer, &raw);
882 if (raw.size < RECORD_HEADER_SIZE(session))
883 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
885 record_read_headers (session, raw.data, type, htype, record);
887 /* Check if the DTLS epoch is valid */
888 if (IS_DTLS(session))
890 if (_gnutls_epoch_is_valid(session, record->epoch) == 0)
892 _gnutls_audit_log(session, "Discarded message[%u] with invalid epoch %u.\n",
893 (unsigned int)_gnutls_uint64touint32 (&record->sequence),
894 (unsigned int)record->sequence.i[0]*256+(unsigned int)record->sequence.i[1]);
895 gnutls_assert();
896 /* doesn't matter, just a fatal error */
897 return GNUTLS_E_UNEXPECTED_PACKET_LENGTH;
901 /* Here we check if the Type of the received packet is
902 * ok.
904 if ((ret = check_recv_type (session, record->type)) < 0)
905 return gnutls_assert_val(ret);
907 /* Here we check if the advertized version is the one we
908 * negotiated in the handshake.
910 if ((ret = record_check_version (session, htype, record->version)) < 0)
911 return gnutls_assert_val(ret);
913 if (record->length > MAX_RECV_SIZE(session))
915 _gnutls_audit_log
916 (session, "Received packet with illegal length: %u\n", (unsigned int)record->length);
917 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
920 _gnutls_record_log
921 ("REC[%p]: Expected Packet %s(%d)\n", session,
922 _gnutls_packet2str (type), type);
923 _gnutls_record_log ("REC[%p]: Received Packet %s(%d) with length: %d\n",
924 session,
925 _gnutls_packet2str (record->type), record->type, record->length);
928 return 0;
931 #define MAX_EMPTY_PACKETS_SEQUENCE 4
933 /* This will receive record layer packets and add them to
934 * application_data_buffer and handshake_data_buffer.
936 ssize_t
937 _gnutls_recv_in_buffers (gnutls_session_t session, content_type_t type,
938 gnutls_handshake_description_t htype)
940 uint64 *packet_sequence;
941 uint8_t *ciphertext;
942 mbuffer_st* bufel = NULL, *decrypted = NULL;
943 int ret;
944 int empty_packet = 0;
945 record_parameters_st *record_params;
946 record_state_st *record_state;
947 struct tls_record_st record;
949 begin:
951 if (empty_packet > MAX_EMPTY_PACKETS_SEQUENCE)
953 gnutls_assert ();
954 return GNUTLS_E_TOO_MANY_EMPTY_PACKETS;
957 memset(&record, 0, sizeof(record));
959 if (session->internals.read_eof != 0)
961 /* if we have already read an EOF
963 return 0;
965 else if (session_is_valid (session) != 0
966 || session->internals.may_not_read != 0)
967 return gnutls_assert_val(GNUTLS_E_INVALID_SESSION);
969 /* get the record state parameters */
970 ret = _gnutls_epoch_get (session, EPOCH_READ_CURRENT, &record_params);
971 if (ret < 0)
972 return gnutls_assert_val (ret);
974 /* Safeguard against processing data with an incomplete cipher state. */
975 if (!record_params->initialized)
976 return gnutls_assert_val (GNUTLS_E_INTERNAL_ERROR);
978 record_state = &record_params->read;
980 /* receive headers */
981 ret = recv_headers(session, type, htype, &record);
982 if (ret < 0)
984 ret = gnutls_assert_val_fatal(ret);
985 goto recv_error;
988 if (IS_DTLS(session))
989 packet_sequence = &record.sequence;
990 else
991 packet_sequence = &record_state->sequence_number;
993 /* Read the packet data and insert it to record_recv_buffer.
995 ret =
996 _gnutls_io_read_buffered (session, record.packet_size,
997 record.type);
998 if (ret != record.packet_size)
1000 gnutls_assert();
1001 goto recv_error;
1004 /* ok now we are sure that we have read all the data - so
1005 * move on !
1007 ret = _mbuffer_linearize (&session->internals.record_recv_buffer);
1008 if (ret < 0)
1009 return gnutls_assert_val(ret);
1011 bufel = _mbuffer_head_get_first (&session->internals.record_recv_buffer, NULL);
1012 if (bufel == NULL)
1013 return gnutls_assert_val(GNUTLS_E_INTERNAL_ERROR);
1015 /* We allocate the maximum possible to allow few compressed bytes to expand to a
1016 * full record.
1018 decrypted = _mbuffer_alloc(MAX_RECORD_RECV_SIZE(session),
1019 MAX_RECORD_RECV_SIZE(session));
1020 if (decrypted == NULL)
1021 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
1023 ciphertext = (uint8_t*)_mbuffer_get_udata_ptr(bufel) + record.header_size;
1025 /* decrypt the data we got.
1027 ret =
1028 _gnutls_decrypt (session, ciphertext, record.length,
1029 _mbuffer_get_udata_ptr(decrypted), _mbuffer_get_udata_size(decrypted),
1030 record.type, record_params, packet_sequence);
1031 if (ret >= 0) _mbuffer_set_udata_size(decrypted, ret);
1033 _mbuffer_head_remove_bytes (&session->internals.record_recv_buffer,
1034 record.header_size + record.length);
1035 if (ret < 0)
1037 gnutls_assert();
1038 _gnutls_audit_log(session, "Discarded message[%u] due to invalid decryption\n",
1039 (unsigned int)_gnutls_uint64touint32 (packet_sequence));
1040 goto sanity_check_error;
1043 /* check for duplicates. We check after the message
1044 * is processed and authenticated to avoid someone
1045 * messing with our windows.
1047 if (IS_DTLS(session))
1049 ret = _dtls_record_check(record_params, packet_sequence);
1050 if (ret < 0)
1052 _gnutls_audit_log(session, "Discarded duplicate message[%u]: %s\n",
1053 (unsigned int) _gnutls_uint64touint32 (packet_sequence), _gnutls_packet2str (record.type));
1054 goto sanity_check_error;
1056 _gnutls_record_log
1057 ("REC[%p]: Decrypted Packet[%u.%u] %s(%d) with length: %d\n", session,
1058 (unsigned int)record.sequence.i[0]*256 +(unsigned int)record.sequence.i[1],
1059 (unsigned int) _gnutls_uint64touint32 (packet_sequence),
1060 _gnutls_packet2str (record.type), record.type, (int)_mbuffer_get_udata_size(decrypted));
1062 else
1064 _gnutls_record_log
1065 ("REC[%p]: Decrypted Packet[%u] %s(%d) with length: %d\n", session,
1066 (unsigned int) _gnutls_uint64touint32 (packet_sequence),
1067 _gnutls_packet2str (record.type), record.type, (int)_mbuffer_get_udata_size(decrypted));
1070 /* increase sequence number
1072 if (!IS_DTLS(session) && sequence_increment (session, &record_state->sequence_number) != 0)
1074 session_invalidate (session);
1075 gnutls_assert ();
1076 ret = GNUTLS_E_RECORD_LIMIT_REACHED;
1077 goto sanity_check_error;
1080 /* (originally for) TLS 1.0 CBC protection.
1081 * Actually this code is called if we just received
1082 * an empty packet. An empty TLS packet is usually
1083 * sent to protect some vulnerabilities in the CBC mode.
1084 * In that case we go to the beginning and start reading
1085 * the next packet.
1087 if (_mbuffer_get_udata_size(decrypted) == 0)
1089 _mbuffer_xfree(&decrypted);
1090 empty_packet++;
1091 goto begin;
1094 if (record.v2)
1095 decrypted->htype = GNUTLS_HANDSHAKE_CLIENT_HELLO_V2;
1096 else
1098 uint8_t * p = _mbuffer_get_udata_ptr(decrypted);
1099 decrypted->htype = p[0];
1102 ret =
1103 record_add_to_buffers (session, &record, type, htype,
1104 packet_sequence, decrypted);
1106 /* bufel is now either deinitialized or buffered somewhere else */
1108 if (ret < 0)
1109 return gnutls_assert_val(ret);
1111 return ret;
1113 discard:
1114 session->internals.dtls.packets_dropped++;
1116 /* discard the whole received fragment. */
1117 bufel = _mbuffer_head_pop_first(&session->internals.record_recv_buffer);
1118 _mbuffer_xfree(&bufel);
1119 return gnutls_assert_val(GNUTLS_E_AGAIN);
1121 sanity_check_error:
1122 if (IS_DTLS(session))
1124 session->internals.dtls.packets_dropped++;
1125 ret = gnutls_assert_val(GNUTLS_E_AGAIN);
1126 goto cleanup;
1129 session_unresumable (session);
1130 session_invalidate (session);
1132 cleanup:
1133 _mbuffer_xfree(&decrypted);
1134 return ret;
1136 recv_error:
1137 if (ret < 0 && gnutls_error_is_fatal (ret) == 0)
1138 return ret;
1140 if (IS_DTLS(session))
1142 goto discard;
1145 session_invalidate (session);
1146 if (type == GNUTLS_ALERT) /* we were expecting close notify */
1148 gnutls_assert ();
1149 return 0;
1151 session_unresumable (session);
1153 if (ret == 0)
1154 return GNUTLS_E_PREMATURE_TERMINATION;
1155 else
1156 return ret;
1159 /* This function behaves exactly like read(). The only difference is
1160 * that it accepts the gnutls_session_t and the content_type_t of data to
1161 * receive (if called by the user the Content is Userdata only)
1162 * It is intended to receive data, under the current session.
1164 * The gnutls_handshake_description_t was introduced to support SSL V2.0 client hellos.
1166 ssize_t
1167 _gnutls_recv_int (gnutls_session_t session, content_type_t type,
1168 gnutls_handshake_description_t htype,
1169 uint8_t * data, size_t data_size, void* seq)
1171 int ret;
1173 if (type != GNUTLS_ALERT && (data_size == 0 || data == NULL))
1175 return GNUTLS_E_INVALID_REQUEST;
1178 if (session->internals.read_eof != 0)
1180 /* if we have already read an EOF
1182 return 0;
1184 else if (session_is_valid (session) != 0
1185 || session->internals.may_not_read != 0)
1187 gnutls_assert ();
1188 return GNUTLS_E_INVALID_SESSION;
1191 _dtls_async_timer_check(session);
1193 /* If we have enough data in the cache do not bother receiving
1194 * a new packet. (in order to flush the cache)
1196 ret = check_buffers (session, type, data, data_size, seq);
1197 if (ret != 0)
1198 return ret;
1200 ret = _gnutls_recv_in_buffers(session, type, htype);
1201 if (ret < 0 && ret != GNUTLS_E_SESSION_EOF)
1202 return gnutls_assert_val(ret);
1204 return check_buffers (session, type, data, data_size, seq);
1209 * gnutls_record_send:
1210 * @session: is a #gnutls_session_t structure.
1211 * @data: contains the data to send
1212 * @data_size: is the length of the data
1214 * This function has the similar semantics with send(). The only
1215 * difference is that it accepts a GnuTLS session, and uses different
1216 * error codes.
1217 * Note that if the send buffer is full, send() will block this
1218 * function. See the send() documentation for full information. You
1219 * can replace the default push function by using
1220 * gnutls_transport_set_ptr2() with a call to send() with a
1221 * MSG_DONTWAIT flag if blocking is a problem.
1222 * If the EINTR is returned by the internal push function (the
1223 * default is send()) then %GNUTLS_E_INTERRUPTED will be returned. If
1224 * %GNUTLS_E_INTERRUPTED or %GNUTLS_E_AGAIN is returned, you must
1225 * call this function again, with the same parameters; alternatively
1226 * you could provide a %NULL pointer for data, and 0 for
1227 * size. cf. gnutls_record_get_direction().
1229 * Returns: The number of bytes sent, or a negative error code. The
1230 * number of bytes sent might be less than @data_size. The maximum
1231 * number of bytes this function can send in a single call depends
1232 * on the negotiated maximum record size.
1234 ssize_t
1235 gnutls_record_send (gnutls_session_t session, const void *data,
1236 size_t data_size)
1238 return _gnutls_send_int (session, GNUTLS_APPLICATION_DATA, -1,
1239 EPOCH_WRITE_CURRENT, data, data_size,
1240 MBUFFER_FLUSH);
1244 * gnutls_record_recv:
1245 * @session: is a #gnutls_session_t structure.
1246 * @data: the buffer that the data will be read into
1247 * @data_size: the number of requested bytes
1249 * This function has the similar semantics with recv(). The only
1250 * difference is that it accepts a GnuTLS session, and uses different
1251 * error codes.
1252 * In the special case that a server requests a renegotiation, the
1253 * client may receive an error code of %GNUTLS_E_REHANDSHAKE. This
1254 * message may be simply ignored, replied with an alert
1255 * %GNUTLS_A_NO_RENEGOTIATION, or replied with a new handshake,
1256 * depending on the client's will.
1257 * If %EINTR is returned by the internal push function (the default
1258 * is recv()) then %GNUTLS_E_INTERRUPTED will be returned. If
1259 * %GNUTLS_E_INTERRUPTED or %GNUTLS_E_AGAIN is returned, you must
1260 * call this function again to get the data. See also
1261 * gnutls_record_get_direction().
1262 * A server may also receive %GNUTLS_E_REHANDSHAKE when a client has
1263 * initiated a handshake. In that case the server can only initiate a
1264 * handshake or terminate the connection.
1266 * Returns: The number of bytes received and zero on EOF (for stream
1267 * connections). A negative error code is returned in case of an error.
1268 * The number of bytes received might be less than the requested @data_size.
1270 ssize_t
1271 gnutls_record_recv (gnutls_session_t session, void *data, size_t data_size)
1273 return _gnutls_recv_int (session, GNUTLS_APPLICATION_DATA, -1, data,
1274 data_size, NULL);
1278 * gnutls_record_recv_seq:
1279 * @session: is a #gnutls_session_t structure.
1280 * @data: the buffer that the data will be read into
1281 * @data_size: the number of requested bytes
1282 * @seq: is the packet's 64-bit sequence number. Should have space for 8 bytes.
1284 * This function is the same as gnutls_record_recv(), except that
1285 * it returns in addition to data, the sequence number of the data.
1286 * This is useful in DTLS where record packets might be received
1287 * out-of-order. The returned 8-byte sequence number is an
1288 * integer in big-endian format and should be
1289 * treated as a unique message identification.
1291 * Returns: The number of bytes received and zero on EOF. A negative
1292 * error code is returned in case of an error. The number of bytes
1293 * received might be less than @data_size.
1295 * Since: 3.0
1297 ssize_t
1298 gnutls_record_recv_seq (gnutls_session_t session, void *data, size_t data_size,
1299 unsigned char *seq)
1301 return _gnutls_recv_int (session, GNUTLS_APPLICATION_DATA, -1, data,
1302 data_size, seq);