]> git.ipfire.org Git - thirdparty/openssl.git/blame - ssl/d1_both.c
free null cleanup finale
[thirdparty/openssl.git] / ssl / d1_both.c
CommitLineData
36d16f8e 1/* ssl/d1_both.c */
0f113f3e 2/*
36d16f8e 3 * DTLS implementation written by Nagendra Modadugu
0f113f3e 4 * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
36d16f8e
BL
5 */
6/* ====================================================================
7 * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 *
13 * 1. Redistributions of source code must retain the above copyright
0f113f3e 14 * notice, this list of conditions and the following disclaimer.
36d16f8e
BL
15 *
16 * 2. Redistributions in binary form must reproduce the above copyright
90acf770
AP
17 * notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the
19 * distribution.
36d16f8e
BL
20 *
21 * 3. All advertising materials mentioning features or use of this
90acf770
AP
22 * software must display the following acknowledgment:
23 * "This product includes software developed by the OpenSSL Project
24 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
36d16f8e
BL
25 *
26 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
90acf770
AP
27 * endorse or promote products derived from this software without
28 * prior written permission. For written permission, please contact
29 * openssl-core@openssl.org.
36d16f8e
BL
30 *
31 * 5. Products derived from this software may not be called "OpenSSL"
90acf770
AP
32 * nor may "OpenSSL" appear in their names without prior written
33 * permission of the OpenSSL Project.
36d16f8e
BL
34 *
35 * 6. Redistributions of any form whatsoever must retain the following
90acf770
AP
36 * acknowledgment:
37 * "This product includes software developed by the OpenSSL Project
38 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
36d16f8e
BL
39 *
40 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
44 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51 * OF THE POSSIBILITY OF SUCH DAMAGE.
52 * ====================================================================
53 *
54 * This product includes cryptographic software written by Eric Young
55 * (eay@cryptsoft.com). This product includes software written by Tim
56 * Hudson (tjh@cryptsoft.com).
57 *
58 */
59/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60 * All rights reserved.
61 *
62 * This package is an SSL implementation written
63 * by Eric Young (eay@cryptsoft.com).
64 * The implementation was written so as to conform with Netscapes SSL.
0f113f3e 65 *
36d16f8e
BL
66 * This library is free for commercial and non-commercial use as long as
67 * the following conditions are aheared to. The following conditions
68 * apply to all code found in this distribution, be it the RC4, RSA,
69 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
70 * included with this distribution is covered by the same copyright terms
71 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
0f113f3e 72 *
36d16f8e
BL
73 * Copyright remains Eric Young's, and as such any Copyright notices in
74 * the code are not to be removed.
75 * If this package is used in a product, Eric Young should be given attribution
76 * as the author of the parts of the library used.
77 * This can be in the form of a textual message at program startup or
78 * in documentation (online or textual) provided with the package.
0f113f3e 79 *
36d16f8e
BL
80 * Redistribution and use in source and binary forms, with or without
81 * modification, are permitted provided that the following conditions
82 * are met:
83 * 1. Redistributions of source code must retain the copyright
90acf770 84 * notice, this list of conditions and the following disclaimer.
36d16f8e 85 * 2. Redistributions in binary form must reproduce the above copyright
90acf770
AP
86 * notice, this list of conditions and the following disclaimer in the
87 * documentation and/or other materials provided with the distribution.
36d16f8e 88 * 3. All advertising materials mentioning features or use of this software
90acf770
AP
89 * must display the following acknowledgement:
90 * "This product includes cryptographic software written by
91 * Eric Young (eay@cryptsoft.com)"
92 * The word 'cryptographic' can be left out if the rouines from the library
93 * being used are not cryptographic related :-).
0f113f3e 94 * 4. If you include any Windows specific code (or a derivative thereof) from
90acf770
AP
95 * the apps directory (application code) you must include an acknowledgement:
96 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
0f113f3e 97 *
36d16f8e
BL
98 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108 * SUCH DAMAGE.
0f113f3e 109 *
36d16f8e
BL
110 * The licence and distribution terms for any publically available version or
111 * derivative of this code cannot be changed. i.e. this code cannot simply be
112 * copied and put under another distribution licence
113 * [including the GNU Public Licence.]
114 */
115
116#include <limits.h>
117#include <string.h>
118#include <stdio.h>
119#include "ssl_locl.h"
120#include <openssl/buffer.h>
121#include <openssl/rand.h>
122#include <openssl/objects.h>
123#include <openssl/evp.h>
124#include <openssl/x509.h>
125
934e22e8
DSH
126#define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
127
128#define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
0f113f3e
MC
129 if ((end) - (start) <= 8) { \
130 long ii; \
131 for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
132 } else { \
133 long ii; \
134 bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
135 for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
136 bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
137 } }
934e22e8
DSH
138
139#define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
0f113f3e
MC
140 long ii; \
141 OPENSSL_assert((msg_len) > 0); \
142 is_complete = 1; \
143 if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
144 if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
145 if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
934e22e8 146
0f113f3e
MC
147static unsigned char bitmask_start_values[] =
148 { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
149static unsigned char bitmask_end_values[] =
150 { 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f };
36d16f8e
BL
151
152/* XDTLS: figure out the right values */
0f113f3e 153static const unsigned int g_probable_mtu[] = { 1500, 512, 256 };
36d16f8e 154
0f113f3e
MC
155static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
156 unsigned long frag_len);
157static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
36d16f8e 158static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
0f113f3e
MC
159 unsigned long len,
160 unsigned short seq_num,
161 unsigned long frag_off,
162 unsigned long frag_len);
163static long dtls1_get_message_fragment(SSL *s, int st1, int stn, long max,
164 int *ok);
165
166static hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len,
167 int reassembly)
168{
169 hm_fragment *frag = NULL;
170 unsigned char *buf = NULL;
171 unsigned char *bitmask = NULL;
172
b196e7d9 173 frag = OPENSSL_malloc(sizeof(hm_fragment));
0f113f3e
MC
174 if (frag == NULL)
175 return NULL;
176
177 if (frag_len) {
b196e7d9 178 buf = OPENSSL_malloc(frag_len);
0f113f3e
MC
179 if (buf == NULL) {
180 OPENSSL_free(frag);
181 return NULL;
182 }
183 }
184
185 /* zero length fragment gets zero frag->fragment */
186 frag->fragment = buf;
187
188 /* Initialize reassembly bitmask if necessary */
189 if (reassembly) {
b196e7d9 190 bitmask = OPENSSL_malloc(RSMBLY_BITMASK_SIZE(frag_len));
0f113f3e 191 if (bitmask == NULL) {
b548a1f1 192 OPENSSL_free(buf);
0f113f3e
MC
193 OPENSSL_free(frag);
194 return NULL;
195 }
196 memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
197 }
198
199 frag->reassembly = bitmask;
200
201 return frag;
202}
36d16f8e 203
8a35dbb6 204void dtls1_hm_fragment_free(hm_fragment *frag)
0f113f3e
MC
205{
206
207 if (frag->msg_header.is_ccs) {
208 EVP_CIPHER_CTX_free(frag->msg_header.
209 saved_retransmit_state.enc_write_ctx);
210 EVP_MD_CTX_destroy(frag->msg_header.
211 saved_retransmit_state.write_hash);
212 }
b548a1f1
RS
213 OPENSSL_free(frag->fragment);
214 OPENSSL_free(frag->reassembly);
0f113f3e
MC
215 OPENSSL_free(frag);
216}
36d16f8e 217
1620a2e4 218static int dtls1_query_mtu(SSL *s)
6abb0d1f 219{
0f113f3e
MC
220 if (s->d1->link_mtu) {
221 s->d1->mtu =
222 s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
223 s->d1->link_mtu = 0;
224 }
225
226 /* AHA! Figure out the MTU, and stick to the right size */
227 if (s->d1->mtu < dtls1_min_mtu(s)) {
228 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
229 s->d1->mtu =
230 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
231
232 /*
233 * I've seen the kernel return bogus numbers when it doesn't know
234 * (initial write), so just make sure we have a reasonable number
235 */
236 if (s->d1->mtu < dtls1_min_mtu(s)) {
237 /* Set to min mtu */
238 s->d1->mtu = dtls1_min_mtu(s);
239 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
240 s->d1->mtu, NULL);
241 }
242 } else
243 return 0;
244 }
245 return 1;
6abb0d1f
MC
246}
247
0f113f3e
MC
248/*
249 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
250 * SSL3_RT_CHANGE_CIPHER_SPEC)
251 */
6abb0d1f 252int dtls1_do_write(SSL *s, int type)
0f113f3e
MC
253{
254 int ret;
255 unsigned int curr_mtu;
256 int retry = 1;
257 unsigned int len, frag_off, mac_size, blocksize, used_len;
258
259 if (!dtls1_query_mtu(s))
260 return -1;
261
262 OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu(s)); /* should have something
263 * reasonable now */
264
265 if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
266 OPENSSL_assert(s->init_num ==
267 (int)s->d1->w_msg_hdr.msg_len +
268 DTLS1_HM_HEADER_LENGTH);
269
270 if (s->write_hash) {
271 if (s->enc_write_ctx
272 && EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_GCM_MODE)
273 mac_size = 0;
274 else
275 mac_size = EVP_MD_CTX_size(s->write_hash);
276 } else
277 mac_size = 0;
278
279 if (s->enc_write_ctx &&
280 (EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_CBC_MODE))
281 blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
282 else
283 blocksize = 0;
284
285 frag_off = 0;
286 /* s->init_num shouldn't ever be < 0...but just in case */
287 while (s->init_num > 0) {
288 used_len = BIO_wpending(SSL_get_wbio(s)) + DTLS1_RT_HEADER_LENGTH
289 + mac_size + blocksize;
290 if (s->d1->mtu > used_len)
291 curr_mtu = s->d1->mtu - used_len;
292 else
293 curr_mtu = 0;
294
295 if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
296 /*
297 * grr.. we could get an error if MTU picked was wrong
298 */
299 ret = BIO_flush(SSL_get_wbio(s));
300 if (ret <= 0)
301 return ret;
302 used_len = DTLS1_RT_HEADER_LENGTH + mac_size + blocksize;
303 if (s->d1->mtu > used_len + DTLS1_HM_HEADER_LENGTH) {
304 curr_mtu = s->d1->mtu - used_len;
305 } else {
306 /* Shouldn't happen */
307 return -1;
308 }
309 }
310
311 /*
312 * We just checked that s->init_num > 0 so this cast should be safe
313 */
314 if (((unsigned int)s->init_num) > curr_mtu)
315 len = curr_mtu;
316 else
317 len = s->init_num;
318
319 /* Shouldn't ever happen */
320 if (len > INT_MAX)
321 len = INT_MAX;
322
323 /*
324 * XDTLS: this function is too long. split out the CCS part
325 */
326 if (type == SSL3_RT_HANDSHAKE) {
327 if (s->init_off != 0) {
328 OPENSSL_assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
329 s->init_off -= DTLS1_HM_HEADER_LENGTH;
330 s->init_num += DTLS1_HM_HEADER_LENGTH;
331
332 /*
333 * We just checked that s->init_num > 0 so this cast should
334 * be safe
335 */
336 if (((unsigned int)s->init_num) > curr_mtu)
337 len = curr_mtu;
338 else
339 len = s->init_num;
340 }
341
342 /* Shouldn't ever happen */
343 if (len > INT_MAX)
344 len = INT_MAX;
345
346 if (len < DTLS1_HM_HEADER_LENGTH) {
347 /*
348 * len is so small that we really can't do anything sensible
349 * so fail
350 */
351 return -1;
352 }
353 dtls1_fix_message_header(s, frag_off,
354 len - DTLS1_HM_HEADER_LENGTH);
355
356 dtls1_write_message_header(s,
357 (unsigned char *)&s->init_buf->
358 data[s->init_off]);
359 }
360
361 ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off],
362 len);
363 if (ret < 0) {
364 /*
365 * might need to update MTU here, but we don't know which
366 * previous packet caused the failure -- so can't really
367 * retransmit anything. continue as if everything is fine and
368 * wait for an alert to handle the retransmit
369 */
370 if (retry && BIO_ctrl(SSL_get_wbio(s),
371 BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
372 if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
373 if (!dtls1_query_mtu(s))
374 return -1;
375 /* Have one more go */
376 retry = 0;
377 } else
378 return -1;
379 } else {
380 return (-1);
381 }
382 } else {
383
384 /*
385 * bad if this assert fails, only part of the handshake message
386 * got sent. but why would this happen?
387 */
388 OPENSSL_assert(len == (unsigned int)ret);
389
390 if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
391 /*
392 * should not be done for 'Hello Request's, but in that case
393 * we'll ignore the result anyway
394 */
395 unsigned char *p =
396 (unsigned char *)&s->init_buf->data[s->init_off];
397 const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
398 int xlen;
399
400 if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
401 /*
402 * reconstruct message header is if it is being sent in
403 * single fragment
404 */
405 *p++ = msg_hdr->type;
406 l2n3(msg_hdr->msg_len, p);
407 s2n(msg_hdr->seq, p);
408 l2n3(0, p);
409 l2n3(msg_hdr->msg_len, p);
410 p -= DTLS1_HM_HEADER_LENGTH;
411 xlen = ret;
412 } else {
413 p += DTLS1_HM_HEADER_LENGTH;
414 xlen = ret - DTLS1_HM_HEADER_LENGTH;
415 }
416
417 ssl3_finish_mac(s, p, xlen);
418 }
419
420 if (ret == s->init_num) {
421 if (s->msg_callback)
422 s->msg_callback(1, s->version, type, s->init_buf->data,
423 (size_t)(s->init_off + s->init_num), s,
424 s->msg_callback_arg);
425
426 s->init_off = 0; /* done writing this message */
427 s->init_num = 0;
428
429 return (1);
430 }
431 s->init_off += ret;
432 s->init_num -= ret;
433 frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
434 }
435 }
436 return (0);
437}
438
439/*
440 * Obtain handshake message of message type 'mt' (any if mt == -1), maximum
441 * acceptable body length 'max'. Read an entire handshake message. Handshake
442 * messages arrive in fragments.
36d16f8e 443 */
beb056b3 444long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
0f113f3e
MC
445{
446 int i, al;
447 struct hm_header_st *msg_hdr;
448 unsigned char *p;
449 unsigned long msg_len;
450
451 /*
452 * s3->tmp is used to store messages that are unexpected, caused by the
453 * absence of an optional handshake message
454 */
455 if (s->s3->tmp.reuse_message) {
456 s->s3->tmp.reuse_message = 0;
457 if ((mt >= 0) && (s->s3->tmp.message_type != mt)) {
458 al = SSL_AD_UNEXPECTED_MESSAGE;
459 SSLerr(SSL_F_DTLS1_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
460 goto f_err;
461 }
462 *ok = 1;
463 s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
464 s->init_num = (int)s->s3->tmp.message_size;
465 return s->init_num;
466 }
467
468 msg_hdr = &s->d1->r_msg_hdr;
469 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
470
471 again:
472 i = dtls1_get_message_fragment(s, st1, stn, max, ok);
473 if (i == DTLS1_HM_BAD_FRAGMENT || i == DTLS1_HM_FRAGMENT_RETRY) {
474 /* bad fragment received */
475 goto again;
476 } else if (i <= 0 && !*ok) {
477 return i;
478 }
479
480 p = (unsigned char *)s->init_buf->data;
481 msg_len = msg_hdr->msg_len;
482
483 /* reconstruct message header */
484 *(p++) = msg_hdr->type;
485 l2n3(msg_len, p);
486 s2n(msg_hdr->seq, p);
487 l2n3(0, p);
488 l2n3(msg_len, p);
489 if (s->version != DTLS1_BAD_VER) {
490 p -= DTLS1_HM_HEADER_LENGTH;
491 msg_len += DTLS1_HM_HEADER_LENGTH;
492 }
493
494 ssl3_finish_mac(s, p, msg_len);
495 if (s->msg_callback)
496 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
497 p, msg_len, s, s->msg_callback_arg);
498
499 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
500
501 /* Don't change sequence numbers while listening */
502 if (!s->d1->listen)
503 s->d1->handshake_read_seq++;
504
505 s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
506 return s->init_num;
507
508 f_err:
509 ssl3_send_alert(s, SSL3_AL_FATAL, al);
510 *ok = 0;
511 return -1;
512}
90acf770 513
0f113f3e
MC
514static int dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr,
515 int max)
516{
517 size_t frag_off, frag_len, msg_len;
518
519 msg_len = msg_hdr->msg_len;
520 frag_off = msg_hdr->frag_off;
521 frag_len = msg_hdr->frag_len;
522
523 /* sanity checking */
524 if ((frag_off + frag_len) > msg_len) {
525 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
526 return SSL_AD_ILLEGAL_PARAMETER;
527 }
528
529 if ((frag_off + frag_len) > (unsigned long)max) {
530 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
531 return SSL_AD_ILLEGAL_PARAMETER;
532 }
533
534 if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
535 /*
536 * msg_len is limited to 2^24, but is effectively checked against max
537 * above
538 */
539 if (!BUF_MEM_grow_clean
540 (s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
541 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, ERR_R_BUF_LIB);
542 return SSL_AD_INTERNAL_ERROR;
543 }
544
545 s->s3->tmp.message_size = msg_len;
546 s->d1->r_msg_hdr.msg_len = msg_len;
547 s->s3->tmp.message_type = msg_hdr->type;
548 s->d1->r_msg_hdr.type = msg_hdr->type;
549 s->d1->r_msg_hdr.seq = msg_hdr->seq;
550 } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
551 /*
552 * They must be playing with us! BTW, failure to enforce upper limit
553 * would open possibility for buffer overrun.
554 */
555 SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
556 return SSL_AD_ILLEGAL_PARAMETER;
557 }
558
559 return 0; /* no error */
560}
90acf770 561
0f113f3e
MC
562static int dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
563{
50e735f9
MC
564 /*-
565 * (0) check whether the desired fragment is available
566 * if so:
567 * (1) copy over the fragment to s->init_buf->data[]
568 * (2) update s->init_num
569 */
0f113f3e
MC
570 pitem *item;
571 hm_fragment *frag;
572 int al;
573
574 *ok = 0;
575 item = pqueue_peek(s->d1->buffered_messages);
576 if (item == NULL)
577 return 0;
578
579 frag = (hm_fragment *)item->data;
580
581 /* Don't return if reassembly still in progress */
582 if (frag->reassembly != NULL)
583 return 0;
584
585 if (s->d1->handshake_read_seq == frag->msg_header.seq) {
586 unsigned long frag_len = frag->msg_header.frag_len;
587 pqueue_pop(s->d1->buffered_messages);
588
589 al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
590
591 if (al == 0) { /* no alert */
592 unsigned char *p =
593 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
594 memcpy(&p[frag->msg_header.frag_off], frag->fragment,
595 frag->msg_header.frag_len);
596 }
597
598 dtls1_hm_fragment_free(frag);
599 pitem_free(item);
600
601 if (al == 0) {
602 *ok = 1;
603 return frag_len;
604 }
605
606 ssl3_send_alert(s, SSL3_AL_FATAL, al);
607 s->init_num = 0;
608 *ok = 0;
609 return -1;
610 } else
611 return 0;
612}
613
614/*
615 * dtls1_max_handshake_message_len returns the maximum number of bytes
616 * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
617 * may be greater if the maximum certificate list size requires it.
618 */
1250f126 619static unsigned long dtls1_max_handshake_message_len(const SSL *s)
0f113f3e
MC
620{
621 unsigned long max_len =
622 DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
623 if (max_len < (unsigned long)s->max_cert_list)
624 return s->max_cert_list;
625 return max_len;
626}
36d16f8e 627
934e22e8 628static int
0f113f3e
MC
629dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
630{
631 hm_fragment *frag = NULL;
632 pitem *item = NULL;
633 int i = -1, is_complete;
634 unsigned char seq64be[8];
635 unsigned long frag_len = msg_hdr->frag_len;
636
637 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
638 msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
639 goto err;
640
641 if (frag_len == 0)
642 return DTLS1_HM_FRAGMENT_RETRY;
643
644 /* Try to find item in queue */
645 memset(seq64be, 0, sizeof(seq64be));
646 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
647 seq64be[7] = (unsigned char)msg_hdr->seq;
648 item = pqueue_find(s->d1->buffered_messages, seq64be);
649
650 if (item == NULL) {
651 frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
652 if (frag == NULL)
653 goto err;
654 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
655 frag->msg_header.frag_len = frag->msg_header.msg_len;
656 frag->msg_header.frag_off = 0;
657 } else {
658 frag = (hm_fragment *)item->data;
659 if (frag->msg_header.msg_len != msg_hdr->msg_len) {
660 item = NULL;
661 frag = NULL;
662 goto err;
663 }
664 }
665
666 /*
667 * If message is already reassembled, this must be a retransmit and can
668 * be dropped. In this case item != NULL and so frag does not need to be
669 * freed.
670 */
671 if (frag->reassembly == NULL) {
672 unsigned char devnull[256];
673
674 while (frag_len) {
675 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
676 devnull,
677 frag_len >
678 sizeof(devnull) ? sizeof(devnull) :
679 frag_len, 0);
680 if (i <= 0)
681 goto err;
682 frag_len -= i;
683 }
684 return DTLS1_HM_FRAGMENT_RETRY;
685 }
686
687 /* read the body of the fragment (header has already been read */
688 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
689 frag->fragment + msg_hdr->frag_off,
690 frag_len, 0);
691 if ((unsigned long)i != frag_len)
692 i = -1;
693 if (i <= 0)
694 goto err;
695
696 RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
697 (long)(msg_hdr->frag_off + frag_len));
698
699 RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
700 is_complete);
701
702 if (is_complete) {
703 OPENSSL_free(frag->reassembly);
704 frag->reassembly = NULL;
705 }
706
707 if (item == NULL) {
708 item = pitem_new(seq64be, frag);
709 if (item == NULL) {
710 i = -1;
711 goto err;
712 }
713
714 item = pqueue_insert(s->d1->buffered_messages, item);
715 /*
716 * pqueue_insert fails iff a duplicate item is inserted. However,
717 * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
718 * would have returned it and control would never have reached this
719 * branch.
720 */
721 OPENSSL_assert(item != NULL);
722 }
723
724 return DTLS1_HM_FRAGMENT_RETRY;
725
726 err:
727 if (frag != NULL && item == NULL)
728 dtls1_hm_fragment_free(frag);
729 *ok = 0;
730 return i;
731}
934e22e8 732
36d16f8e 733static int
0f113f3e
MC
734dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
735 int *ok)
36d16f8e 736{
0f113f3e
MC
737 int i = -1;
738 hm_fragment *frag = NULL;
739 pitem *item = NULL;
740 unsigned char seq64be[8];
741 unsigned long frag_len = msg_hdr->frag_len;
742
743 if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
744 goto err;
745
746 /* Try to find item in queue, to prevent duplicate entries */
747 memset(seq64be, 0, sizeof(seq64be));
748 seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
749 seq64be[7] = (unsigned char)msg_hdr->seq;
750 item = pqueue_find(s->d1->buffered_messages, seq64be);
751
752 /*
753 * If we already have an entry and this one is a fragment, don't discard
754 * it and rather try to reassemble it.
755 */
756 if (item != NULL && frag_len != msg_hdr->msg_len)
757 item = NULL;
758
759 /*
760 * Discard the message if sequence number was already there, is too far
761 * in the future, already in the queue or if we received a FINISHED
762 * before the SERVER_HELLO, which then must be a stale retransmit.
763 */
764 if (msg_hdr->seq <= s->d1->handshake_read_seq ||
765 msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
766 (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
767 {
768 unsigned char devnull[256];
769
770 while (frag_len) {
771 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
772 devnull,
773 frag_len >
774 sizeof(devnull) ? sizeof(devnull) :
775 frag_len, 0);
776 if (i <= 0)
777 goto err;
778 frag_len -= i;
779 }
780 } else {
781 if (frag_len != msg_hdr->msg_len)
782 return dtls1_reassemble_fragment(s, msg_hdr, ok);
783
784 if (frag_len > dtls1_max_handshake_message_len(s))
785 goto err;
786
787 frag = dtls1_hm_fragment_new(frag_len, 0);
788 if (frag == NULL)
789 goto err;
790
791 memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
792
793 if (frag_len) {
794 /*
795 * read the body of the fragment (header has already been read
796 */
797 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
798 frag->fragment, frag_len, 0);
799 if ((unsigned long)i != frag_len)
800 i = -1;
801 if (i <= 0)
802 goto err;
803 }
804
805 item = pitem_new(seq64be, frag);
806 if (item == NULL)
807 goto err;
808
809 item = pqueue_insert(s->d1->buffered_messages, item);
810 /*
811 * pqueue_insert fails iff a duplicate item is inserted. However,
812 * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
813 * would have returned it. Then, either |frag_len| !=
814 * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
815 * have been processed with |dtls1_reassemble_fragment|, above, or
816 * the record will have been discarded.
817 */
818 OPENSSL_assert(item != NULL);
819 }
820
821 return DTLS1_HM_FRAGMENT_RETRY;
822
823 err:
824 if (frag != NULL && item == NULL)
825 dtls1_hm_fragment_free(frag);
826 *ok = 0;
827 return i;
828}
36d16f8e 829
beb056b3 830static long
36d16f8e 831dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
0f113f3e
MC
832{
833 unsigned char wire[DTLS1_HM_HEADER_LENGTH];
834 unsigned long len, frag_off, frag_len;
835 int i, al;
836 struct hm_header_st msg_hdr;
837
838 redo:
839 /* see if we have the required fragment already */
840 if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
841 if (*ok)
842 s->init_num = frag_len;
843 return frag_len;
844 }
845
846 /* read handshake message header */
847 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
848 DTLS1_HM_HEADER_LENGTH, 0);
849 if (i <= 0) { /* nbio, or an error */
850 s->rwstate = SSL_READING;
851 *ok = 0;
852 return i;
853 }
854 /* Handshake fails if message header is incomplete */
855 if (i != DTLS1_HM_HEADER_LENGTH) {
856 al = SSL_AD_UNEXPECTED_MESSAGE;
857 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_UNEXPECTED_MESSAGE);
858 goto f_err;
859 }
860
861 /* parse the message fragment header */
862 dtls1_get_message_header(wire, &msg_hdr);
863
864 /*
865 * if this is a future (or stale) message it gets buffered
866 * (or dropped)--no further processing at this time
867 * While listening, we accept seq 1 (ClientHello with cookie)
868 * although we're still expecting seq 0 (ClientHello)
869 */
870 if (msg_hdr.seq != s->d1->handshake_read_seq
871 && !(s->d1->listen && msg_hdr.seq == 1))
872 return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
873
874 len = msg_hdr.msg_len;
875 frag_off = msg_hdr.frag_off;
876 frag_len = msg_hdr.frag_len;
877
878 if (frag_len && frag_len < len)
879 return dtls1_reassemble_fragment(s, &msg_hdr, ok);
880
881 if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
882 wire[0] == SSL3_MT_HELLO_REQUEST) {
883 /*
884 * The server may always send 'Hello Request' messages -- we are
885 * doing a handshake anyway now, so ignore them if their format is
886 * correct. Does not count for 'Finished' MAC.
887 */
888 if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
889 if (s->msg_callback)
890 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
891 wire, DTLS1_HM_HEADER_LENGTH, s,
892 s->msg_callback_arg);
893
894 s->init_num = 0;
895 goto redo;
896 } else { /* Incorrectly formated Hello request */
897
898 al = SSL_AD_UNEXPECTED_MESSAGE;
899 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
900 SSL_R_UNEXPECTED_MESSAGE);
901 goto f_err;
902 }
903 }
904
905 if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
906 goto f_err;
907
908 /* XDTLS: ressurect this when restart is in place */
909 s->state = stn;
910
911 if (frag_len > 0) {
912 unsigned char *p =
913 (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
914
915 i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
916 &p[frag_off], frag_len, 0);
917 /*
918 * XDTLS: fix this--message fragments cannot span multiple packets
919 */
920 if (i <= 0) {
921 s->rwstate = SSL_READING;
922 *ok = 0;
923 return i;
924 }
925 } else
926 i = 0;
927
928 /*
929 * XDTLS: an incorrectly formatted fragment should cause the handshake
930 * to fail
931 */
932 if (i != (int)frag_len) {
933 al = SSL3_AD_ILLEGAL_PARAMETER;
934 SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL3_AD_ILLEGAL_PARAMETER);
935 goto f_err;
936 }
937
938 *ok = 1;
939
940 /*
941 * Note that s->init_num is *not* used as current offset in
942 * s->init_buf->data, but as a counter summing up fragments' lengths: as
943 * soon as they sum up to handshake packet length, we assume we have got
944 * all the fragments.
945 */
946 s->init_num = frag_len;
947 return frag_len;
948
949 f_err:
950 ssl3_send_alert(s, SSL3_AL_FATAL, al);
951 s->init_num = 0;
952
953 *ok = 0;
954 return (-1);
955}
36d16f8e 956
1d97c843
TH
957/*-
958 * for these 2 messages, we need to
0f113f3e 959 * ssl->enc_read_ctx re-init
de07f311 960 * ssl->rlayer.read_sequence zero
0f113f3e
MC
961 * ssl->s3->read_mac_secret re-init
962 * ssl->session->read_sym_enc assign
963 * ssl->session->read_compression assign
964 * ssl->session->read_hash assign
36d16f8e
BL
965 */
966int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
0f113f3e
MC
967{
968 unsigned char *p;
36d16f8e 969
0f113f3e
MC
970 if (s->state == a) {
971 p = (unsigned char *)s->init_buf->data;
972 *p++ = SSL3_MT_CCS;
973 s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
974 s->init_num = DTLS1_CCS_HEADER_LENGTH;
8711efb4 975
0f113f3e
MC
976 if (s->version == DTLS1_BAD_VER) {
977 s->d1->next_handshake_write_seq++;
978 s2n(s->d1->handshake_write_seq, p);
979 s->init_num += 2;
980 }
8711efb4 981
0f113f3e 982 s->init_off = 0;
36d16f8e 983
0f113f3e
MC
984 dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
985 s->d1->handshake_write_seq, 0, 0);
36d16f8e 986
0f113f3e 987 /* buffer the message to handle re-xmits */
61986d32 988 if (!dtls1_buffer_message(s, 1)) {
69f68237
MC
989 SSLerr(SSL_F_DTLS1_SEND_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
990 return -1;
991 }
36d16f8e 992
0f113f3e
MC
993 s->state = b;
994 }
36d16f8e 995
0f113f3e
MC
996 /* SSL3_ST_CW_CHANGE_B */
997 return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
998}
36d16f8e 999
36d16f8e 1000int dtls1_read_failed(SSL *s, int code)
0f113f3e
MC
1001{
1002 if (code > 0) {
1003 fprintf(stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
1004 return 1;
1005 }
1006
1007 if (!dtls1_is_timer_expired(s)) {
1008 /*
1009 * not a timeout, none of our business, let higher layers handle
1010 * this. in fact it's probably an error
1011 */
1012 return code;
1013 }
4817504d 1014#ifndef OPENSSL_NO_HEARTBEATS
0f113f3e
MC
1015 /* done, no need to send a retransmit */
1016 if (!SSL_in_init(s) && !s->tlsext_hb_pending)
4817504d 1017#else
0f113f3e
MC
1018 /* done, no need to send a retransmit */
1019 if (!SSL_in_init(s))
4817504d 1020#endif
0f113f3e
MC
1021 {
1022 BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
1023 return code;
1024 }
36d16f8e 1025
0f113f3e
MC
1026 return dtls1_handle_timeout(s);
1027}
36d16f8e 1028
0f113f3e
MC
1029int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1030{
1031 /*
1032 * The index of the retransmission queue actually is the message sequence
1033 * number, since the queue only contains messages of a single handshake.
1034 * However, the ChangeCipherSpec has no message sequence number and so
1035 * using only the sequence will result in the CCS and Finished having the
1036 * same index. To prevent this, the sequence number is multiplied by 2.
1037 * In case of a CCS 1 is subtracted. This does not only differ CSS and
1038 * Finished, it also maintains the order of the index (important for
1039 * priority queues) and fits in the unsigned short variable.
1040 */
1041 return seq * 2 - is_ccs;
1042}
36d16f8e 1043
0f113f3e
MC
1044int dtls1_retransmit_buffered_messages(SSL *s)
1045{
1046 pqueue sent = s->d1->sent_messages;
1047 piterator iter;
1048 pitem *item;
1049 hm_fragment *frag;
1050 int found = 0;
1051
1052 iter = pqueue_iterator(sent);
1053
1054 for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1055 frag = (hm_fragment *)item->data;
1056 if (dtls1_retransmit_message(s, (unsigned short)
1057 dtls1_get_queue_priority
1058 (frag->msg_header.seq,
1059 frag->msg_header.is_ccs), 0,
1060 &found) <= 0 && found) {
1061 fprintf(stderr, "dtls1_retransmit_message() failed\n");
1062 return -1;
1063 }
1064 }
1065
1066 return 1;
1067}
36d16f8e 1068
0f113f3e
MC
1069int dtls1_buffer_message(SSL *s, int is_ccs)
1070{
1071 pitem *item;
1072 hm_fragment *frag;
1073 unsigned char seq64be[8];
1074
1075 /*
1076 * this function is called immediately after a message has been
1077 * serialized
1078 */
1079 OPENSSL_assert(s->init_off == 0);
1080
1081 frag = dtls1_hm_fragment_new(s->init_num, 0);
1082 if (!frag)
1083 return 0;
1084
1085 memcpy(frag->fragment, s->init_buf->data, s->init_num);
1086
1087 if (is_ccs) {
5178a16c 1088 /* For DTLS1_BAD_VER the header length is non-standard */
0f113f3e 1089 OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
5178a16c
MC
1090 ((s->version==DTLS1_BAD_VER)?3:DTLS1_CCS_HEADER_LENGTH)
1091 == (unsigned int)s->init_num);
0f113f3e
MC
1092 } else {
1093 OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
1094 DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
1095 }
1096
1097 frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1098 frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1099 frag->msg_header.type = s->d1->w_msg_hdr.type;
1100 frag->msg_header.frag_off = 0;
1101 frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1102 frag->msg_header.is_ccs = is_ccs;
1103
1104 /* save current state */
1105 frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
1106 frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
1107 frag->msg_header.saved_retransmit_state.compress = s->compress;
1108 frag->msg_header.saved_retransmit_state.session = s->session;
78a39fe7
MC
1109 frag->msg_header.saved_retransmit_state.epoch =
1110 DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer);
0f113f3e
MC
1111
1112 memset(seq64be, 0, sizeof(seq64be));
1113 seq64be[6] =
1114 (unsigned
1115 char)(dtls1_get_queue_priority(frag->msg_header.seq,
1116 frag->msg_header.is_ccs) >> 8);
1117 seq64be[7] =
1118 (unsigned
1119 char)(dtls1_get_queue_priority(frag->msg_header.seq,
1120 frag->msg_header.is_ccs));
1121
1122 item = pitem_new(seq64be, frag);
1123 if (item == NULL) {
1124 dtls1_hm_fragment_free(frag);
1125 return 0;
1126 }
36d16f8e 1127
0f113f3e
MC
1128 pqueue_insert(s->d1->sent_messages, item);
1129 return 1;
1130}
36d16f8e
BL
1131
1132int
1133dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
0f113f3e
MC
1134 int *found)
1135{
1136 int ret;
1137 /* XDTLS: for now assuming that read/writes are blocking */
1138 pitem *item;
1139 hm_fragment *frag;
1140 unsigned long header_length;
1141 unsigned char seq64be[8];
1142 struct dtls1_retransmit_state saved_state;
0f113f3e 1143
50e735f9
MC
1144 /*-
1145 OPENSSL_assert(s->init_num == 0);
1146 OPENSSL_assert(s->init_off == 0);
1147 */
0f113f3e
MC
1148
1149 /* XDTLS: the requested message ought to be found, otherwise error */
1150 memset(seq64be, 0, sizeof(seq64be));
1151 seq64be[6] = (unsigned char)(seq >> 8);
1152 seq64be[7] = (unsigned char)seq;
1153
1154 item = pqueue_find(s->d1->sent_messages, seq64be);
1155 if (item == NULL) {
1156 fprintf(stderr, "retransmit: message %d non-existant\n", seq);
1157 *found = 0;
1158 return 0;
1159 }
1160
1161 *found = 1;
1162 frag = (hm_fragment *)item->data;
1163
1164 if (frag->msg_header.is_ccs)
1165 header_length = DTLS1_CCS_HEADER_LENGTH;
1166 else
1167 header_length = DTLS1_HM_HEADER_LENGTH;
1168
1169 memcpy(s->init_buf->data, frag->fragment,
1170 frag->msg_header.msg_len + header_length);
1171 s->init_num = frag->msg_header.msg_len + header_length;
1172
1173 dtls1_set_message_header_int(s, frag->msg_header.type,
1174 frag->msg_header.msg_len,
1175 frag->msg_header.seq, 0,
1176 frag->msg_header.frag_len);
1177
1178 /* save current state */
1179 saved_state.enc_write_ctx = s->enc_write_ctx;
1180 saved_state.write_hash = s->write_hash;
1181 saved_state.compress = s->compress;
1182 saved_state.session = s->session;
78a39fe7 1183 saved_state.epoch = DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer);
0f113f3e
MC
1184
1185 s->d1->retransmitting = 1;
1186
1187 /* restore state in which the message was originally sent */
1188 s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
1189 s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
1190 s->compress = frag->msg_header.saved_retransmit_state.compress;
1191 s->session = frag->msg_header.saved_retransmit_state.session;
3bb8f87d 1192 DTLS_RECORD_LAYER_set_saved_w_epoch(&s->rlayer,
78a39fe7 1193 frag->msg_header.saved_retransmit_state.epoch);
0f113f3e 1194
0f113f3e
MC
1195 ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
1196 SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1197
1198 /* restore current state */
1199 s->enc_write_ctx = saved_state.enc_write_ctx;
1200 s->write_hash = saved_state.write_hash;
1201 s->compress = saved_state.compress;
1202 s->session = saved_state.session;
3bb8f87d 1203 DTLS_RECORD_LAYER_set_saved_w_epoch(&s->rlayer, saved_state.epoch);
0f113f3e
MC
1204
1205 s->d1->retransmitting = 0;
1206
1207 (void)BIO_flush(SSL_get_wbio(s));
1208 return ret;
1209}
36d16f8e
BL
1210
1211/* call this function when the buffered messages are no longer needed */
0f113f3e
MC
1212void dtls1_clear_record_buffer(SSL *s)
1213{
1214 pitem *item;
36d16f8e 1215
0f113f3e
MC
1216 for (item = pqueue_pop(s->d1->sent_messages);
1217 item != NULL; item = pqueue_pop(s->d1->sent_messages)) {
1218 dtls1_hm_fragment_free((hm_fragment *)item->data);
1219 pitem_free(item);
1220 }
1221}
54ef01b5 1222
69f68237 1223void dtls1_set_message_header(SSL *s, unsigned char *p,
0f113f3e
MC
1224 unsigned char mt, unsigned long len,
1225 unsigned long frag_off,
1226 unsigned long frag_len)
1227{
1228 /* Don't change sequence numbers while listening */
1229 if (frag_off == 0 && !s->d1->listen) {
1230 s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1231 s->d1->next_handshake_write_seq++;
1232 }
54ef01b5 1233
0f113f3e
MC
1234 dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1235 frag_off, frag_len);
0f113f3e 1236}
36d16f8e
BL
1237
1238/* don't actually do the writing, wait till the MTU has been retrieved */
1239static void
1240dtls1_set_message_header_int(SSL *s, unsigned char mt,
0f113f3e
MC
1241 unsigned long len, unsigned short seq_num,
1242 unsigned long frag_off, unsigned long frag_len)
1243{
1244 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1245
1246 msg_hdr->type = mt;
1247 msg_hdr->msg_len = len;
1248 msg_hdr->seq = seq_num;
1249 msg_hdr->frag_off = frag_off;
1250 msg_hdr->frag_len = frag_len;
1251}
36d16f8e
BL
1252
1253static void
1254dtls1_fix_message_header(SSL *s, unsigned long frag_off,
0f113f3e
MC
1255 unsigned long frag_len)
1256{
1257 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
36d16f8e 1258
0f113f3e
MC
1259 msg_hdr->frag_off = frag_off;
1260 msg_hdr->frag_len = frag_len;
1261}
54ef01b5 1262
0f113f3e
MC
1263static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p)
1264{
1265 struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
54ef01b5 1266
0f113f3e
MC
1267 *p++ = msg_hdr->type;
1268 l2n3(msg_hdr->msg_len, p);
54ef01b5 1269
0f113f3e
MC
1270 s2n(msg_hdr->seq, p);
1271 l2n3(msg_hdr->frag_off, p);
1272 l2n3(msg_hdr->frag_len, p);
36d16f8e 1273
0f113f3e
MC
1274 return p;
1275}
36d16f8e 1276
0f113f3e
MC
1277unsigned int dtls1_link_min_mtu(void)
1278{
1279 return (g_probable_mtu[(sizeof(g_probable_mtu) /
1280 sizeof(g_probable_mtu[0])) - 1]);
1281}
36d16f8e 1282
0f113f3e
MC
1283unsigned int dtls1_min_mtu(SSL *s)
1284{
1285 return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
1286}
36d16f8e
BL
1287
1288void
1289dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
0f113f3e
MC
1290{
1291 memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
1292 msg_hdr->type = *(data++);
1293 n2l3(data, msg_hdr->msg_len);
54ef01b5 1294
0f113f3e
MC
1295 n2s(data, msg_hdr->seq);
1296 n2l3(data, msg_hdr->frag_off);
1297 n2l3(data, msg_hdr->frag_len);
1298}
36d16f8e 1299
0f113f3e
MC
1300void dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
1301{
1302 memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
54ef01b5 1303
0f113f3e
MC
1304 ccs_hdr->type = *(data++);
1305}
7e159e01
DSH
1306
1307int dtls1_shutdown(SSL *s)
0f113f3e
MC
1308{
1309 int ret;
7e159e01 1310#ifndef OPENSSL_NO_SCTP
0f113f3e
MC
1311 if (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
1312 !(s->shutdown & SSL_SENT_SHUTDOWN)) {
1313 ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s));
1314 if (ret < 0)
1315 return -1;
1316
1317 if (ret == 0)
1318 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
1319 NULL);
1320 }
7e159e01 1321#endif
0f113f3e 1322 ret = ssl3_shutdown(s);
7e159e01 1323#ifndef OPENSSL_NO_SCTP
0f113f3e 1324 BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
7e159e01 1325#endif
0f113f3e
MC
1326 return ret;
1327}
4817504d
DSH
1328
1329#ifndef OPENSSL_NO_HEARTBEATS
2c60ed04 1330int dtls1_process_heartbeat(SSL *s, unsigned char *p, unsigned int length)
0f113f3e 1331{
2c60ed04 1332 unsigned char *pl;
0f113f3e
MC
1333 unsigned short hbtype;
1334 unsigned int payload;
1335 unsigned int padding = 16; /* Use minimum padding */
1336
1337 if (s->msg_callback)
1338 s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
258f8721 1339 p, length, s, s->msg_callback_arg);
0f113f3e
MC
1340
1341 /* Read type and payload length first */
258f8721 1342 if (1 + 2 + 16 > length)
0f113f3e 1343 return 0; /* silently discard */
258f8721 1344 if (length > SSL3_RT_MAX_PLAIN_LENGTH)
0f113f3e
MC
1345 return 0; /* silently discard per RFC 6520 sec. 4 */
1346
1347 hbtype = *p++;
1348 n2s(p, payload);
258f8721 1349 if (1 + 2 + payload + 16 > length)
0f113f3e
MC
1350 return 0; /* silently discard per RFC 6520 sec. 4 */
1351 pl = p;
1352
1353 if (hbtype == TLS1_HB_REQUEST) {
1354 unsigned char *buffer, *bp;
1355 unsigned int write_length = 1 /* heartbeat type */ +
1356 2 /* heartbeat length */ +
1357 payload + padding;
1358 int r;
1359
1360 if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
1361 return 0;
1362
1363 /*
1364 * Allocate memory for the response, size is 1 byte message type,
1365 * plus 2 bytes payload length, plus payload, plus padding
1366 */
1367 buffer = OPENSSL_malloc(write_length);
1368 if (buffer == NULL)
1369 return -1;
1370 bp = buffer;
1371
1372 /* Enter response type, length and copy payload */
1373 *bp++ = TLS1_HB_RESPONSE;
1374 s2n(payload, bp);
1375 memcpy(bp, pl, payload);
1376 bp += payload;
1377 /* Random padding */
266483d2
MC
1378 if (RAND_bytes(bp, padding) <= 0) {
1379 OPENSSL_free(buffer);
1380 return -1;
1381 }
0f113f3e
MC
1382
1383 r = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, write_length);
1384
1385 if (r >= 0 && s->msg_callback)
1386 s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
1387 buffer, write_length, s, s->msg_callback_arg);
1388
1389 OPENSSL_free(buffer);
1390
1391 if (r < 0)
1392 return r;
1393 } else if (hbtype == TLS1_HB_RESPONSE) {
1394 unsigned int seq;
1395
1396 /*
1397 * We only send sequence numbers (2 bytes unsigned int), and 16
1398 * random bytes, so we just try to read the sequence number
1399 */
1400 n2s(pl, seq);
1401
1402 if (payload == 18 && seq == s->tlsext_hb_seq) {
1403 dtls1_stop_timer(s);
1404 s->tlsext_hb_seq++;
1405 s->tlsext_hb_pending = 0;
1406 }
1407 }
1408
1409 return 0;
1410}
4817504d 1411
0f113f3e
MC
1412int dtls1_heartbeat(SSL *s)
1413{
1414 unsigned char *buf, *p;
266483d2 1415 int ret = -1;
0f113f3e
MC
1416 unsigned int payload = 18; /* Sequence number + random bytes */
1417 unsigned int padding = 16; /* Use minimum padding */
1418
1419 /* Only send if peer supports and accepts HB requests... */
1420 if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
1421 s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
1422 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
1423 return -1;
1424 }
1425
1426 /* ...and there is none in flight yet... */
1427 if (s->tlsext_hb_pending) {
1428 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
1429 return -1;
1430 }
1431
1432 /* ...and no handshake in progress. */
1433 if (SSL_in_init(s) || s->in_handshake) {
1434 SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
1435 return -1;
1436 }
1437
1438 /*
1439 * Check if padding is too long, payload and padding must not exceed 2^14
1440 * - 3 = 16381 bytes in total.
1441 */
1442 OPENSSL_assert(payload + padding <= 16381);
1443
50e735f9
MC
1444 /*-
1445 * Create HeartBeat message, we just use a sequence number
1446 * as payload to distuingish different messages and add
1447 * some random stuff.
1448 * - Message Type, 1 byte
1449 * - Payload Length, 2 bytes (unsigned int)
1450 * - Payload, the sequence number (2 bytes uint)
1451 * - Payload, random bytes (16 bytes uint)
1452 * - Padding
1453 */
0f113f3e
MC
1454 buf = OPENSSL_malloc(1 + 2 + payload + padding);
1455 if (buf == NULL) {
1456 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_MALLOC_FAILURE);
1457 return -1;
1458 }
1459 p = buf;
1460 /* Message Type */
1461 *p++ = TLS1_HB_REQUEST;
1462 /* Payload length (18 bytes here) */
1463 s2n(payload, p);
1464 /* Sequence number */
1465 s2n(s->tlsext_hb_seq, p);
1466 /* 16 random bytes */
266483d2
MC
1467 if (RAND_bytes(p, 16) <= 0) {
1468 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1469 goto err;
1470 }
0f113f3e
MC
1471 p += 16;
1472 /* Random padding */
266483d2
MC
1473 if (RAND_bytes(p, padding) <= 0) {
1474 SSLerr(SSL_F_DTLS1_HEARTBEAT, ERR_R_INTERNAL_ERROR);
1475 goto err;
1476 }
0f113f3e
MC
1477
1478 ret = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
1479 if (ret >= 0) {
1480 if (s->msg_callback)
1481 s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
1482 buf, 3 + payload + padding,
1483 s, s->msg_callback_arg);
1484
1485 dtls1_start_timer(s);
1486 s->tlsext_hb_pending = 1;
1487 }
1488
266483d2 1489 err:
0f113f3e
MC
1490 OPENSSL_free(buf);
1491
1492 return ret;
1493}
4817504d 1494#endif