certtool is able to set certificate policies via a template
[gnutls.git] / lib / gnutls_dtls.c
blob78e21fbf74a261393a3caef0ae6ab6efa2be8643
1 /*
2 * Copyright (C) 2009-2012 Free Software Foundation, Inc.
4 * Authors: Jonathan Bastien-Filiatrault
5 * Nikos Mavrogiannopoulos
7 * This file is part of GNUTLS.
9 * The GNUTLS library 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 3 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 relate to DTLS retransmission and reassembly.
27 #include "gnutls_int.h"
28 #include "gnutls_errors.h"
29 #include "debug.h"
30 #include "gnutls_dtls.h"
31 #include "gnutls_record.h"
32 #include <gnutls_mbuffers.h>
33 #include <gnutls_buffers.h>
34 #include <gnutls_constate.h>
35 #include <gnutls_state.h>
36 #include <gnutls/dtls.h>
37 #include <timespec.h>
38 #include <algorithms.h>
40 /* returns a-b in ms */
41 unsigned int
42 _dtls_timespec_sub_ms (struct timespec *a, struct timespec *b)
44 return (a->tv_sec * 1000 + a->tv_nsec / (1000 * 1000) -
45 (b->tv_sec * 1000 + b->tv_nsec / (1000 * 1000)));
48 void
49 _dtls_async_timer_delete (gnutls_session_t session)
51 if (session->internals.dtls.async_term != 0)
53 _gnutls_dtls_log ("DTLS[%p]: Deinitializing previous handshake state.\n", session);
54 session->internals.dtls.async_term = 0; /* turn off "timer" */
56 _dtls_reset_hsk_state(session);
57 _gnutls_handshake_io_buffer_clear (session);
58 _gnutls_epoch_gc(session);
62 /* This function fragments and transmits a previously buffered
63 * outgoing message. It accepts mtu_data which is a buffer to
64 * be reused (should be set to NULL initially).
66 static inline int
67 transmit_message (gnutls_session_t session,
68 mbuffer_st *bufel, uint8_t **buf)
70 uint8_t *data, *mtu_data;
71 int ret = 0;
72 unsigned int offset, frag_len, data_size;
73 const unsigned int mtu = gnutls_dtls_get_data_mtu(session) - DTLS_HANDSHAKE_HEADER_SIZE;
75 if (bufel->type == GNUTLS_CHANGE_CIPHER_SPEC)
77 _gnutls_dtls_log ("DTLS[%p]: Sending Packet[%u] fragment %s(%d)\n",
78 session, bufel->handshake_sequence,
79 _gnutls_handshake2str (bufel->htype),
80 bufel->htype);
82 return _gnutls_send_int (session, bufel->type, -1,
83 bufel->epoch,
84 _mbuffer_get_uhead_ptr(bufel),
85 _mbuffer_get_uhead_size(bufel), 0);
88 if (*buf == NULL) *buf = gnutls_malloc(mtu + DTLS_HANDSHAKE_HEADER_SIZE);
89 if (*buf == NULL)
90 return gnutls_assert_val(GNUTLS_E_MEMORY_ERROR);
92 mtu_data = *buf;
94 data = _mbuffer_get_udata_ptr( bufel);
95 data_size = _mbuffer_get_udata_size(bufel);
97 /* Write fixed headers
100 /* Handshake type */
101 mtu_data[0] = (uint8_t) bufel->htype;
103 /* Total length */
104 _gnutls_write_uint24 (data_size, &mtu_data[1]);
106 /* Handshake sequence */
107 _gnutls_write_uint16 (bufel->handshake_sequence, &mtu_data[4]);
109 /* Chop up and send handshake message into mtu-size pieces. */
110 for (offset=0; offset <= data_size; offset += mtu)
112 /* Calculate fragment length */
113 if(offset + mtu > data_size)
114 frag_len = data_size - offset;
115 else
116 frag_len = mtu;
118 /* Fragment offset */
119 _gnutls_write_uint24 (offset, &mtu_data[6]);
121 /* Fragment length */
122 _gnutls_write_uint24 (frag_len, &mtu_data[9]);
124 memcpy (&mtu_data[DTLS_HANDSHAKE_HEADER_SIZE], data+offset, frag_len);
126 _gnutls_dtls_log ("DTLS[%p]: Sending Packet[%u] fragment %s(%d) with "
127 "length: %u, offset: %u, fragment length: %u\n",
128 session, bufel->handshake_sequence,
129 _gnutls_handshake2str (bufel->htype),
130 bufel->htype, data_size, offset, frag_len);
132 ret = _gnutls_send_int (session, bufel->type, bufel->htype,
133 bufel->epoch, mtu_data, DTLS_HANDSHAKE_HEADER_SIZE + frag_len, 0);
134 if (ret < 0)
136 gnutls_assert();
137 break;
141 return ret;
144 static int drop_usage_count(gnutls_session_t session, mbuffer_head_st *const send_buffer)
146 int ret;
147 mbuffer_st *cur;
149 for (cur = send_buffer->head;
150 cur != NULL; cur = cur->next)
152 ret = _gnutls_epoch_refcount_dec(session, cur->epoch);
153 if (ret < 0)
154 return gnutls_assert_val(ret);
157 return 0;
161 /* Checks whether the received packet contains a handshake
162 * packet with sequence higher that the previously received.
163 * It must be called only when an actual packet has been
164 * received.
166 * Returns: 0 if expected, negative value otherwise.
168 static int is_next_hpacket_expected(gnutls_session_t session)
170 int ret;
172 /* htype is arbitrary */
173 ret = _gnutls_recv_in_buffers(session, GNUTLS_HANDSHAKE, GNUTLS_HANDSHAKE_FINISHED, 0);
174 if (ret < 0)
175 return gnutls_assert_val(ret);
177 ret = _gnutls_parse_record_buffered_msgs(session);
178 if (ret < 0)
179 return gnutls_assert_val(ret);
181 if (session->internals.handshake_recv_buffer_size > 0)
182 return 0;
183 else
184 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET);
187 void _dtls_reset_hsk_state(gnutls_session_t session)
189 session->internals.dtls.flight_init = 0;
190 drop_usage_count(session, &session->internals.handshake_send_buffer);
191 _mbuffer_head_clear(&session->internals.handshake_send_buffer);
195 #define UPDATE_TIMER { \
196 session->internals.dtls.actual_retrans_timeout_ms *= 2; \
197 session->internals.dtls.actual_retrans_timeout_ms %= MAX_DTLS_TIMEOUT; \
200 #define RESET_TIMER \
201 session->internals.dtls.actual_retrans_timeout_ms = session->internals.dtls.retrans_timeout_ms
203 #define TIMER_WINDOW session->internals.dtls.actual_retrans_timeout_ms
205 /* This function transmits the flight that has been previously
206 * buffered.
208 * This function is called from the handshake layer and calls the
209 * record layer.
212 _dtls_transmit (gnutls_session_t session)
214 int ret;
215 uint8_t* buf = NULL;
216 unsigned int timeout;
218 /* PREPARING -> SENDING state transition */
219 mbuffer_head_st *const send_buffer =
220 &session->internals.handshake_send_buffer;
221 mbuffer_st *cur;
222 gnutls_handshake_description_t last_type = 0;
223 unsigned int diff;
224 struct timespec now;
226 gettime(&now);
228 /* If we have already sent a flight and we are operating in a
229 * non blocking way, check if it is time to retransmit or just
230 * return.
232 if (session->internals.dtls.flight_init != 0 && session->internals.dtls.blocking == 0)
234 /* just in case previous run was interrupted */
235 ret = _gnutls_io_write_flush (session);
236 if (ret < 0)
238 gnutls_assert();
239 goto cleanup;
242 if (session->internals.dtls.last_flight == 0 || !_dtls_is_async(session))
244 /* check for ACK */
245 ret = _gnutls_io_check_recv(session, 0);
246 if (ret == GNUTLS_E_TIMEDOUT)
248 /* if no retransmission is required yet just return
250 if (_dtls_timespec_sub_ms(&now, &session->internals.dtls.last_retransmit) < TIMER_WINDOW)
252 gnutls_assert();
253 goto nb_timeout;
256 else /* received something */
258 if (ret == 0)
260 ret = is_next_hpacket_expected(session);
261 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
262 goto nb_timeout;
263 if (ret < 0 && ret != GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET)
265 gnutls_assert();
266 goto cleanup;
268 if (ret == 0) goto end_flight;
269 /* if ret == GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET retransmit */
271 else
272 goto nb_timeout;
279 timeout = TIMER_WINDOW;
281 diff = _dtls_timespec_sub_ms(&now, &session->internals.dtls.handshake_start_time);
282 if (diff >= session->internals.dtls.total_timeout_ms)
284 _gnutls_dtls_log("Session timeout: %u ms\n", diff);
285 ret = gnutls_assert_val(GNUTLS_E_TIMEDOUT);
286 goto end_flight;
289 diff = _dtls_timespec_sub_ms(&now, &session->internals.dtls.last_retransmit);
290 if (session->internals.dtls.flight_init == 0 || diff >= TIMER_WINDOW)
292 _gnutls_dtls_log ("DTLS[%p]: %sStart of flight transmission.\n", session, (session->internals.dtls.flight_init == 0)?"":"re-");
293 for (cur = send_buffer->head;
294 cur != NULL; cur = cur->next)
296 ret = transmit_message (session, cur, &buf);
297 if (ret < 0)
299 gnutls_assert();
300 goto end_flight;
303 last_type = cur->htype;
305 gettime(&session->internals.dtls.last_retransmit);
307 if (session->internals.dtls.flight_init == 0)
309 session->internals.dtls.flight_init = 1;
310 RESET_TIMER;
311 timeout = TIMER_WINDOW;
313 if (last_type == GNUTLS_HANDSHAKE_FINISHED)
315 /* On the last flight we cannot ensure retransmission
316 * from here. _dtls_wait_and_retransmit() is being called
317 * by handshake.
319 session->internals.dtls.last_flight = 1;
321 else
322 session->internals.dtls.last_flight = 0;
324 else
326 UPDATE_TIMER;
330 ret = _gnutls_io_write_flush (session);
331 if (ret < 0)
333 ret = gnutls_assert_val(ret);
334 goto cleanup;
337 /* last message in handshake -> no ack */
338 if (session->internals.dtls.last_flight != 0)
340 /* we don't wait here. We just return 0 and
341 * if a retransmission occurs because peer didn't receive it
342 * we rely on the record or handshake
343 * layer calling this function again.
345 ret = 0;
346 goto cleanup;
348 else /* all other messages -> implicit ack (receive of next flight) */
350 if (session->internals.dtls.blocking != 0)
351 ret = _gnutls_io_check_recv(session, timeout);
352 else
354 ret = _gnutls_io_check_recv(session, 0);
355 if (ret == GNUTLS_E_TIMEDOUT)
357 goto nb_timeout;
361 if (ret == 0)
363 ret = is_next_hpacket_expected(session);
364 if (ret == GNUTLS_E_AGAIN || ret == GNUTLS_E_INTERRUPTED)
365 goto nb_timeout;
367 if (ret == GNUTLS_E_UNEXPECTED_HANDSHAKE_PACKET)
369 ret = GNUTLS_E_TIMEDOUT;
370 goto keep_up;
372 if (ret < 0)
374 gnutls_assert();
375 goto cleanup;
377 goto end_flight;
381 keep_up:
382 gettime(&now);
383 } while(ret == GNUTLS_E_TIMEDOUT);
385 if (ret < 0)
387 ret = gnutls_assert_val(ret);
388 goto end_flight;
391 ret = 0;
393 end_flight:
394 _gnutls_dtls_log ("DTLS[%p]: End of flight transmission.\n", session);
395 _dtls_reset_hsk_state(session);
397 cleanup:
398 if (buf != NULL)
399 gnutls_free(buf);
401 /* SENDING -> WAITING state transition */
402 return ret;
404 nb_timeout:
405 if (buf != NULL)
406 gnutls_free(buf);
408 RETURN_DTLS_EAGAIN_OR_TIMEOUT(session, ret);
411 /* Waits for the last flight or retransmits
412 * the previous on timeout. Returns 0 on success.
414 int _dtls_wait_and_retransmit(gnutls_session_t session)
416 int ret;
418 if (session->internals.dtls.blocking != 0)
419 ret = _gnutls_io_check_recv(session, TIMER_WINDOW);
420 else
421 ret = _gnutls_io_check_recv(session, 0);
423 if (ret == GNUTLS_E_TIMEDOUT)
425 ret = _dtls_retransmit(session);
426 if (ret == 0)
428 RETURN_DTLS_EAGAIN_OR_TIMEOUT(session, 0);
430 else
431 return gnutls_assert_val(ret);
434 RESET_TIMER;
435 return 0;
439 #define window_table rp->record_sw
440 #define window_size rp->record_sw_size
442 /* FIXME: could we modify that code to avoid using
443 * uint64_t?
446 static void rot_window(struct record_parameters_st * rp, int places)
448 window_size -= places;
449 memmove(window_table, &window_table[places], window_size*sizeof(window_table[0]));
452 #define MOVE_SIZE 20
453 /* Checks if a sequence number is not replayed. If replayed
454 * returns a negative error code, otherwise zero.
456 int _dtls_record_check(struct record_parameters_st *rp, uint64 * _seq)
458 uint64_t seq = 0, diff;
459 unsigned int i, offset = 0;
461 for (i=2;i<8;i++)
463 seq <<= 8;
464 seq |= _seq->i[i] & 0xff;
467 if (window_size == 0)
469 window_size = 1;
470 window_table[0] = seq;
471 return 0;
474 if (seq <= window_table[0])
476 return -1;
479 if (window_size == DTLS_RECORD_WINDOW_SIZE)
481 rot_window(rp, MOVE_SIZE);
484 if (seq < window_table[window_size-1])
486 /* is between first and last */
487 diff = window_table[window_size-1] - seq;
489 if (diff >= window_size)
490 return -1;
492 offset = window_size-1-diff;
494 if (window_table[offset] == seq)
495 return -1;
496 else
497 window_table[offset] = seq;
499 else /* seq >= last */
501 if (seq == window_table[window_size-1])
503 return -1;
506 diff = seq - window_table[window_size-1];
507 if (diff <= DTLS_RECORD_WINDOW_SIZE - window_size)
508 { /* fits in our empty space */
509 offset = diff + window_size-1;
511 window_table[offset] = seq;
512 window_size = offset + 1;
514 else
516 if (diff > DTLS_RECORD_WINDOW_SIZE/2)
517 { /* difference is too big */
518 window_table[DTLS_RECORD_WINDOW_SIZE-1] = seq;
519 window_size = DTLS_RECORD_WINDOW_SIZE;
521 else
523 rot_window(rp, diff);
524 offset = diff + window_size-1;
525 window_table[offset] = seq;
526 window_size = offset + 1;
530 return 0;
535 * gnutls_dtls_set_timeouts:
536 * @session: is a #gnutls_session_t structure.
537 * @retrans_timeout: The time at which a retransmission will occur in milliseconds
538 * @total_timeout: The time at which the connection will be aborted, in milliseconds.
540 * This function will set the timeouts required for the DTLS handshake
541 * protocol. The retransmission timeout is the time after which a
542 * message from the peer is not received, the previous messages will
543 * be retransmitted. The total timeout is the time after which the
544 * handshake will be aborted with %GNUTLS_E_TIMEDOUT.
546 * The DTLS protocol recommends the values of 1 sec and 60 seconds
547 * respectively.
549 * If the retransmission timeout is zero then the handshake will operate
550 * in a non-blocking way, i.e., return %GNUTLS_E_AGAIN.
552 * Since: 3.0
554 void gnutls_dtls_set_timeouts (gnutls_session_t session, unsigned int retrans_timeout,
555 unsigned int total_timeout)
557 session->internals.dtls.retrans_timeout_ms = retrans_timeout;
558 session->internals.dtls.total_timeout_ms = total_timeout;
562 * gnutls_dtls_set_mtu:
563 * @session: is a #gnutls_session_t structure.
564 * @mtu: The maximum transfer unit of the transport
566 * This function will set the maximum transfer unit of the transport
567 * that DTLS packets are sent over. Note that this should exclude
568 * the IP (or IPv6) and UDP headers. So for DTLS over IPv6 on an
569 * Ethenet device with MTU 1500, the DTLS MTU set with this function
570 * would be 1500 - 40 (IPV6 header) - 8 (UDP header) = 1452.
572 * Since: 3.0
574 void gnutls_dtls_set_mtu (gnutls_session_t session, unsigned int mtu)
576 session->internals.dtls.mtu = mtu;
579 /* returns overhead imposed by the record layer (encryption/compression)
580 * etc. It does not include the record layer headers, since the caller
581 * needs to cope with rounding to multiples of blocksize, and the header
582 * is outside that.
584 * blocksize: will contain the block size when padding may be required or 1
586 * It may return a negative error code on error.
588 static int record_overhead_rt(gnutls_session_t session, unsigned int *blocksize)
590 record_parameters_st *params;
591 int total = 0, ret, iv_size;
593 if (session->internals.initial_negotiation_completed == 0)
594 return GNUTLS_E_INVALID_REQUEST;
596 ret = _gnutls_epoch_get (session, EPOCH_WRITE_CURRENT, &params);
597 if (ret < 0)
598 return gnutls_assert_val(ret);
600 /* requires padding */
601 iv_size = _gnutls_cipher_get_iv_size(params->cipher_algorithm);
603 if (_gnutls_cipher_is_block (params->cipher_algorithm) == CIPHER_BLOCK)
605 *blocksize = iv_size;
607 total += iv_size; /* iv_size == block_size in DTLS */
609 /* We always pad with at least one byte; never 0. */
610 total++;
612 else
614 *blocksize = 1;
617 if (params->mac_algorithm == GNUTLS_MAC_AEAD)
618 total += _gnutls_cipher_get_tag_size(params->cipher_algorithm);
619 else
621 ret = _gnutls_hmac_get_algo_len(params->mac_algorithm);
622 if (ret < 0)
623 return gnutls_assert_val(ret);
624 total+=ret;
627 if (params->compression_algorithm != GNUTLS_COMP_NULL)
628 total += EXTRA_COMP_SIZE;
630 return total;
634 * gnutls_dtls_get_data_mtu:
635 * @session: is a #gnutls_session_t structure.
637 * This function will return the actual maximum transfer unit for
638 * application data. I.e. DTLS headers are subtracted from the
639 * actual MTU.
641 * Returns: the maximum allowed transfer unit.
643 * Since: 3.0
645 unsigned int gnutls_dtls_get_data_mtu (gnutls_session_t session)
647 int mtu = session->internals.dtls.mtu;
648 unsigned int blocksize = 1;
649 int overhead;
651 mtu -= RECORD_HEADER_SIZE(session);
653 overhead = record_overhead_rt(session, &blocksize);
654 if (overhead < 0)
655 return mtu;
657 if (blocksize)
658 mtu -= mtu % blocksize;
660 return mtu - overhead;
664 * gnutls_dtls_set_data_mtu:
665 * @session: is a #gnutls_session_t structure.
666 * @mtu: The maximum unencrypted transfer unit of the session
668 * This function will set the maximum size of the *unencrypted* records
669 * which will be sent over a DTLS session. It is equivalent to calculating
670 * the DTLS packet overhead with the current encryption parameters, and
671 * calling gnutls_dtls_set_mtu() with that value. In particular, this means
672 * that you may need to call this function again after any negotiation or
673 * renegotiation, in order to ensure that the MTU is still sufficient to
674 * account for the new protocol overhead.
676 * Returns: %GNUTLS_E_SUCCESS (0) on success, or a negative error code.
678 * Since: 3.1
680 int gnutls_dtls_set_data_mtu (gnutls_session_t session, unsigned int mtu)
682 unsigned int blocksize;
683 int overhead = record_overhead_rt(session, &blocksize);
685 /* You can't call this until the session is actually running */
686 if (overhead < 0)
687 return GNUTLS_E_INVALID_SESSION;
689 /* Add the overhead inside the encrypted part */
690 mtu += overhead;
692 /* Round it up to the next multiple of blocksize */
693 mtu += blocksize - 1;
694 mtu -= mtu % blocksize;
696 /* Add the *unencrypted header size */
697 mtu += RECORD_HEADER_SIZE(session);
699 gnutls_dtls_set_mtu(session, mtu);
700 return GNUTLS_E_SUCCESS;
704 * gnutls_dtls_get_mtu:
705 * @session: is a #gnutls_session_t structure.
707 * This function will return the MTU size as set with
708 * gnutls_dtls_set_mtu(). This is not the actual MTU
709 * of data you can transmit. Use gnutls_dtls_get_data_mtu()
710 * for that reason.
712 * Returns: the set maximum transfer unit.
714 * Since: 3.0
716 unsigned int gnutls_dtls_get_mtu (gnutls_session_t session)
718 return session->internals.dtls.mtu;
722 * gnutls_dtls_get_timeout:
723 * @session: is a #gnutls_session_t structure.
725 * This function will return the milliseconds remaining
726 * for a retransmission of the previously sent handshake
727 * message. This function is useful when DTLS is used in
728 * non-blocking mode, to estimate when to call gnutls_handshake()
729 * if no packets have been received.
731 * Returns: the remaining time in milliseconds.
733 * Since: 3.0
735 unsigned int gnutls_dtls_get_timeout (gnutls_session_t session)
737 struct timespec now;
738 unsigned int diff;
740 gettime(&now);
742 diff = _dtls_timespec_sub_ms(&now, &session->internals.dtls.last_retransmit);
743 if (diff >= TIMER_WINDOW)
744 return 0;
745 else
746 return TIMER_WINDOW - diff;
749 #define COOKIE_SIZE 16
750 #define COOKIE_MAC_SIZE 16
752 /* MAC
753 * 16 bytes
755 * total 19 bytes
758 #define C_HASH GNUTLS_MAC_SHA1
759 #define C_HASH_SIZE 20
762 * gnutls_dtls_cookie_send:
763 * @key: is a random key to be used at cookie generation
764 * @client_data: contains data identifying the client (i.e. address)
765 * @client_data_size: The size of client's data
766 * @prestate: The previous cookie returned by gnutls_dtls_cookie_verify()
767 * @ptr: A transport pointer to be used by @push_func
768 * @push_func: A function that will be used to reply
770 * This function can be used to prevent denial of service
771 * attacks to a DTLS server by requiring the client to
772 * reply using a cookie sent by this function. That way
773 * it can be ensured that a client we allocated resources
774 * for (i.e. #gnutls_session_t) is the one that the
775 * original incoming packet was originated from.
777 * Returns: the number of bytes sent, or a negative error code.
779 * Since: 3.0
781 int gnutls_dtls_cookie_send(gnutls_datum_t* key, void* client_data, size_t client_data_size,
782 gnutls_dtls_prestate_st* prestate,
783 gnutls_transport_ptr_t ptr, gnutls_push_func push_func)
785 uint8_t hvr[20+DTLS_HANDSHAKE_HEADER_SIZE+COOKIE_SIZE];
786 int hvr_size = 0, ret;
787 uint8_t digest[C_HASH_SIZE];
789 if (key == NULL || key->data == NULL || key->size == 0)
790 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
792 /* send
793 * struct {
794 * ContentType type - 1 byte GNUTLS_HANDSHAKE;
795 * ProtocolVersion version; - 2 bytes (254,255)
796 * uint16 epoch; - 2 bytes (0, 0)
797 * uint48 sequence_number; - 4 bytes (0,0,0,0)
798 * uint16 length; - 2 bytes (COOKIE_SIZE+1+2)+DTLS_HANDSHAKE_HEADER_SIZE
799 * uint8_t fragment[DTLSPlaintext.length];
800 * } DTLSPlaintext;
803 * struct {
804 * HandshakeType msg_type; 1 byte - GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST
805 * uint24 length; - COOKIE_SIZE+3
806 * uint16 message_seq; - 2 bytes (0,0)
807 * uint24 fragment_offset; - 3 bytes (0,0,0)
808 * uint24 fragment_length; - same as length
811 * struct {
812 * ProtocolVersion server_version;
813 * uint8_t cookie<0..32>;
814 * } HelloVerifyRequest;
817 hvr[hvr_size++] = GNUTLS_HANDSHAKE;
818 /* version */
819 hvr[hvr_size++] = 254;
820 hvr[hvr_size++] = 255;
822 /* epoch + seq */
823 memset(&hvr[hvr_size], 0, 8);
824 hvr_size += 7;
825 hvr[hvr_size++] = prestate->record_seq;
827 /* length */
828 _gnutls_write_uint16(DTLS_HANDSHAKE_HEADER_SIZE+COOKIE_SIZE+3, &hvr[hvr_size]);
829 hvr_size += 2;
831 /* now handshake headers */
832 hvr[hvr_size++] = GNUTLS_HANDSHAKE_HELLO_VERIFY_REQUEST;
833 _gnutls_write_uint24(COOKIE_SIZE+3, &hvr[hvr_size]);
834 hvr_size += 3;
836 /* handshake seq */
837 hvr[hvr_size++] = 0;
838 hvr[hvr_size++] = prestate->hsk_write_seq;
840 _gnutls_write_uint24(0, &hvr[hvr_size]);
841 hvr_size += 3;
843 _gnutls_write_uint24(COOKIE_SIZE+3, &hvr[hvr_size]);
844 hvr_size += 3;
846 /* version */
847 hvr[hvr_size++] = 254;
848 hvr[hvr_size++] = 255;
849 hvr[hvr_size++] = COOKIE_SIZE;
851 ret = _gnutls_hmac_fast(C_HASH, key->data, key->size, client_data, client_data_size, digest);
852 if (ret < 0)
853 return gnutls_assert_val(ret);
855 memcpy(&hvr[hvr_size], digest, COOKIE_MAC_SIZE);
856 hvr_size+= COOKIE_MAC_SIZE;
858 ret = push_func(ptr, hvr, hvr_size);
859 if (ret < 0)
860 ret = GNUTLS_E_PUSH_ERROR;
862 return ret;
866 * gnutls_dtls_cookie_verify:
867 * @key: is a random key to be used at cookie generation
868 * @client_data: contains data identifying the client (i.e. address)
869 * @client_data_size: The size of client's data
870 * @_msg: An incoming message that initiates a connection.
871 * @msg_size: The size of the message.
872 * @prestate: The cookie of this client.
874 * This function will verify an incoming message for
875 * a valid cookie. If a valid cookie is returned then
876 * it should be associated with the session using
877 * gnutls_dtls_prestate_set();
879 * Returns: %GNUTLS_E_SUCCESS (0) on success, or a negative error code.
881 * Since: 3.0
883 int gnutls_dtls_cookie_verify(gnutls_datum_t* key,
884 void* client_data, size_t client_data_size,
885 void* _msg, size_t msg_size, gnutls_dtls_prestate_st* prestate)
887 gnutls_datum_t cookie;
888 int ret;
889 unsigned int pos, sid_size;
890 uint8_t * msg = _msg;
891 uint8_t digest[C_HASH_SIZE];
893 if (key == NULL || key->data == NULL || key->size == 0)
894 return gnutls_assert_val(GNUTLS_E_INVALID_REQUEST);
896 /* format:
897 * version - 2 bytes
898 * random - 32 bytes
899 * session_id - 1 byte length + content
900 * cookie - 1 byte length + content
903 pos = 34+DTLS_RECORD_HEADER_SIZE+DTLS_HANDSHAKE_HEADER_SIZE;
905 if (msg_size < pos+1)
906 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
908 sid_size = msg[pos++];
910 if (sid_size > 32 || msg_size < pos+sid_size+1)
911 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
913 pos += sid_size;
914 cookie.size = msg[pos++];
916 if (msg_size < pos+cookie.size+1)
917 return gnutls_assert_val(GNUTLS_E_UNEXPECTED_PACKET_LENGTH);
919 cookie.data = &msg[pos];
920 if (cookie.size != COOKIE_SIZE)
922 if (cookie.size > 0) _gnutls_audit_log(NULL, "Received cookie with illegal size %d. Expected %d\n", (int)cookie.size, COOKIE_SIZE);
923 return gnutls_assert_val(GNUTLS_E_BAD_COOKIE);
926 ret = _gnutls_hmac_fast(C_HASH, key->data, key->size, client_data, client_data_size, digest);
927 if (ret < 0)
928 return gnutls_assert_val(ret);
930 if (memcmp(digest, cookie.data, COOKIE_MAC_SIZE) != 0)
931 return gnutls_assert_val(GNUTLS_E_BAD_COOKIE);
933 prestate->record_seq = msg[10]; /* client's record seq */
934 prestate->hsk_read_seq = msg[DTLS_RECORD_HEADER_SIZE+5]; /* client's hsk seq */
935 prestate->hsk_write_seq = 0;/* we always send zero for this msg */
937 return 0;
941 * gnutls_dtls_prestate_set:
942 * @session: a new session
943 * @prestate: contains the client's prestate
945 * This function will associate the prestate acquired by
946 * the cookie authentication with the client, with the newly
947 * established session.
949 * Since: 3.0
951 void gnutls_dtls_prestate_set(gnutls_session_t session, gnutls_dtls_prestate_st* prestate)
953 record_parameters_st *params;
954 int ret;
956 if (prestate == NULL)
957 return;
959 /* we do not care about read_params, since we accept anything
960 * the peer sends.
962 ret = _gnutls_epoch_get (session, EPOCH_WRITE_CURRENT, &params);
963 if (ret < 0)
964 return;
966 params->write.sequence_number.i[7] = prestate->record_seq;
968 session->internals.dtls.hsk_read_seq = prestate->hsk_read_seq;
969 session->internals.dtls.hsk_write_seq = prestate->hsk_write_seq + 1;
973 * gnutls_record_get_discarded:
974 * @session: is a #gnutls_session_t structure.
976 * Returns the number of discarded packets in a
977 * DTLS connection.
979 * Returns: The number of discarded packets.
981 * Since: 3.0
983 unsigned int gnutls_record_get_discarded (gnutls_session_t session)
985 return session->internals.dtls.packets_dropped;