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