You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1459 line
40 KiB

  1. /*
  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. #include <assert.h>
  114. #include <limits.h>
  115. #include <stdio.h>
  116. #include <string.h>
  117. #include <openssl/buf.h>
  118. #include <openssl/err.h>
  119. #include <openssl/evp.h>
  120. #include <openssl/mem.h>
  121. #include <openssl/obj.h>
  122. #include <openssl/rand.h>
  123. #include <openssl/x509.h>
  124. #include "ssl_locl.h"
  125. #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
  126. #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
  127. if ((end) - (start) <= 8) { \
  128. long ii; \
  129. for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
  130. } else { \
  131. long ii; \
  132. bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
  133. for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
  134. bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
  135. } }
  136. #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
  137. long ii; \
  138. assert((msg_len) > 0); \
  139. is_complete = 1; \
  140. if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
  141. if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
  142. if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
  143. #if 0
  144. #define RSMBLY_BITMASK_PRINT(bitmask, msg_len) { \
  145. long ii; \
  146. printf("bitmask: "); for (ii = 0; ii < (msg_len); ii++) \
  147. printf("%d ", (bitmask[ii >> 3] & (1 << (ii & 7))) >> (ii & 7)); \
  148. printf("\n"); }
  149. #endif
  150. static unsigned char bitmask_start_values[] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80};
  151. static unsigned char bitmask_end_values[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
  152. /* XDTLS: figure out the right values */
  153. static unsigned int g_probable_mtu[] = {1500 - 28, 512 - 28, 256 - 28};
  154. static unsigned int dtls1_guess_mtu(unsigned int curr_mtu);
  155. static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  156. unsigned long frag_len);
  157. static unsigned char *dtls1_write_message_header(SSL *s,
  158. unsigned char *p);
  159. static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
  160. unsigned long len, unsigned short seq_num, unsigned long frag_off,
  161. unsigned long frag_len);
  162. static long dtls1_get_message_fragment(SSL *s, int stn,
  163. long max, int *ok);
  164. static hm_fragment *
  165. dtls1_hm_fragment_new(unsigned long frag_len, int reassembly)
  166. {
  167. hm_fragment *frag = NULL;
  168. unsigned char *buf = NULL;
  169. unsigned char *bitmask = NULL;
  170. frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment));
  171. if ( frag == NULL)
  172. return NULL;
  173. if (frag_len)
  174. {
  175. buf = (unsigned char *)OPENSSL_malloc(frag_len);
  176. if ( buf == NULL)
  177. {
  178. OPENSSL_free(frag);
  179. return NULL;
  180. }
  181. }
  182. /* zero length fragment gets zero frag->fragment */
  183. frag->fragment = buf;
  184. /* Initialize reassembly bitmask if necessary */
  185. if (reassembly)
  186. {
  187. bitmask = (unsigned char *)OPENSSL_malloc(RSMBLY_BITMASK_SIZE(frag_len));
  188. if (bitmask == NULL)
  189. {
  190. if (buf != NULL) OPENSSL_free(buf);
  191. OPENSSL_free(frag);
  192. return NULL;
  193. }
  194. memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
  195. }
  196. frag->reassembly = bitmask;
  197. return frag;
  198. }
  199. static void
  200. dtls1_hm_fragment_free(hm_fragment *frag)
  201. {
  202. if (frag->msg_header.is_ccs)
  203. {
  204. EVP_CIPHER_CTX_free(frag->msg_header.saved_retransmit_state.enc_write_ctx);
  205. EVP_MD_CTX_destroy(frag->msg_header.saved_retransmit_state.write_hash);
  206. }
  207. if (frag->fragment) OPENSSL_free(frag->fragment);
  208. if (frag->reassembly) OPENSSL_free(frag->reassembly);
  209. OPENSSL_free(frag);
  210. }
  211. /* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */
  212. int dtls1_do_write(SSL *s, int type)
  213. {
  214. int ret;
  215. int curr_mtu;
  216. unsigned int len, frag_off, mac_size, blocksize;
  217. /* AHA! Figure out the MTU, and stick to the right size */
  218. if (s->d1->mtu < dtls1_min_mtu() && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU))
  219. {
  220. s->d1->mtu =
  221. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  222. /* I've seen the kernel return bogus numbers when it doesn't know
  223. * (initial write), so just make sure we have a reasonable number */
  224. if (s->d1->mtu < dtls1_min_mtu())
  225. {
  226. s->d1->mtu = 0;
  227. s->d1->mtu = dtls1_guess_mtu(s->d1->mtu);
  228. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
  229. s->d1->mtu, NULL);
  230. }
  231. }
  232. #if 0
  233. mtu = s->d1->mtu;
  234. fprintf(stderr, "using MTU = %d\n", mtu);
  235. mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
  236. curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s));
  237. if ( curr_mtu > 0)
  238. mtu = curr_mtu;
  239. else if ( ( ret = BIO_flush(SSL_get_wbio(s))) <= 0)
  240. return ret;
  241. if ( BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu)
  242. {
  243. ret = BIO_flush(SSL_get_wbio(s));
  244. if ( ret <= 0)
  245. return ret;
  246. mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
  247. }
  248. #endif
  249. assert(s->d1->mtu >= dtls1_min_mtu()); /* should have something reasonable now */
  250. if ( s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
  251. assert(s->init_num ==
  252. (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
  253. if (s->write_hash)
  254. {
  255. if (s->enc_write_ctx && EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_GCM_MODE)
  256. mac_size = 0;
  257. else
  258. mac_size = EVP_MD_CTX_size(s->write_hash);
  259. }
  260. else
  261. mac_size = 0;
  262. if (s->enc_write_ctx &&
  263. (EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_CBC_MODE))
  264. blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
  265. else
  266. blocksize = 0;
  267. frag_off = 0;
  268. while( s->init_num)
  269. {
  270. curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
  271. DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
  272. if ( curr_mtu <= DTLS1_HM_HEADER_LENGTH)
  273. {
  274. /* grr.. we could get an error if MTU picked was wrong */
  275. ret = BIO_flush(SSL_get_wbio(s));
  276. if ( ret <= 0)
  277. return ret;
  278. curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH -
  279. mac_size - blocksize;
  280. }
  281. if ( s->init_num > curr_mtu)
  282. len = curr_mtu;
  283. else
  284. len = s->init_num;
  285. /* XDTLS: this function is too long. split out the CCS part */
  286. if ( type == SSL3_RT_HANDSHAKE)
  287. {
  288. if ( s->init_off != 0)
  289. {
  290. assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
  291. s->init_off -= DTLS1_HM_HEADER_LENGTH;
  292. s->init_num += DTLS1_HM_HEADER_LENGTH;
  293. if ( s->init_num > curr_mtu)
  294. len = curr_mtu;
  295. else
  296. len = s->init_num;
  297. }
  298. dtls1_fix_message_header(s, frag_off,
  299. len - DTLS1_HM_HEADER_LENGTH);
  300. dtls1_write_message_header(s, (unsigned char *)&s->init_buf->data[s->init_off]);
  301. assert(len >= DTLS1_HM_HEADER_LENGTH);
  302. }
  303. ret=dtls1_write_bytes(s,type,&s->init_buf->data[s->init_off],
  304. len);
  305. if (ret < 0)
  306. {
  307. /* might need to update MTU here, but we don't know
  308. * which previous packet caused the failure -- so can't
  309. * really retransmit anything. continue as if everything
  310. * is fine and wait for an alert to handle the
  311. * retransmit
  312. */
  313. if ( BIO_ctrl(SSL_get_wbio(s),
  314. BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0 )
  315. s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
  316. BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  317. else
  318. return(-1);
  319. }
  320. else
  321. {
  322. /* bad if this assert fails, only part of the handshake
  323. * message got sent. but why would this happen? */
  324. assert(len == (unsigned int)ret);
  325. if (type == SSL3_RT_HANDSHAKE && ! s->d1->retransmitting)
  326. {
  327. /* should not be done for 'Hello Request's, but in that case
  328. * we'll ignore the result anyway */
  329. unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];
  330. const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  331. int xlen;
  332. if (frag_off == 0 && s->version != DTLS1_BAD_VER)
  333. {
  334. /* reconstruct message header is if it
  335. * is being sent in single fragment */
  336. *p++ = msg_hdr->type;
  337. l2n3(msg_hdr->msg_len,p);
  338. s2n (msg_hdr->seq,p);
  339. l2n3(0,p);
  340. l2n3(msg_hdr->msg_len,p);
  341. p -= DTLS1_HM_HEADER_LENGTH;
  342. xlen = ret;
  343. }
  344. else
  345. {
  346. p += DTLS1_HM_HEADER_LENGTH;
  347. xlen = ret - DTLS1_HM_HEADER_LENGTH;
  348. }
  349. ssl3_finish_mac(s, p, xlen);
  350. }
  351. if (ret == s->init_num)
  352. {
  353. if (s->msg_callback)
  354. s->msg_callback(1, s->version, type, s->init_buf->data,
  355. (size_t)(s->init_off + s->init_num), s,
  356. s->msg_callback_arg);
  357. s->init_off = 0; /* done writing this message */
  358. s->init_num = 0;
  359. return(1);
  360. }
  361. s->init_off+=ret;
  362. s->init_num-=ret;
  363. frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
  364. }
  365. }
  366. return(0);
  367. }
  368. /* Obtain handshake message of message type 'mt' (any if mt == -1),
  369. * maximum acceptable body length 'max'.
  370. * Read an entire handshake message. Handshake messages arrive in
  371. * fragments.
  372. */
  373. long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
  374. {
  375. int i, al;
  376. struct hm_header_st *msg_hdr;
  377. unsigned char *p;
  378. unsigned long msg_len;
  379. /* s3->tmp is used to store messages that are unexpected, caused
  380. * by the absence of an optional handshake message */
  381. if (s->s3->tmp.reuse_message)
  382. {
  383. s->s3->tmp.reuse_message=0;
  384. if ((mt >= 0) && (s->s3->tmp.message_type != mt))
  385. {
  386. al=SSL_AD_UNEXPECTED_MESSAGE;
  387. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_UNEXPECTED_MESSAGE);
  388. goto f_err;
  389. }
  390. *ok=1;
  391. s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  392. s->init_num = (int)s->s3->tmp.message_size;
  393. return s->init_num;
  394. }
  395. msg_hdr = &s->d1->r_msg_hdr;
  396. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  397. again:
  398. i = dtls1_get_message_fragment(s, stn, max, ok);
  399. if ( i == DTLS1_HM_BAD_FRAGMENT ||
  400. i == DTLS1_HM_FRAGMENT_RETRY) /* bad fragment received */
  401. goto again;
  402. else if ( i <= 0 && !*ok)
  403. return i;
  404. p = (unsigned char *)s->init_buf->data;
  405. msg_len = msg_hdr->msg_len;
  406. /* reconstruct message header */
  407. *(p++) = msg_hdr->type;
  408. l2n3(msg_len,p);
  409. s2n (msg_hdr->seq,p);
  410. l2n3(0,p);
  411. l2n3(msg_len,p);
  412. if (s->version != DTLS1_BAD_VER) {
  413. p -= DTLS1_HM_HEADER_LENGTH;
  414. msg_len += DTLS1_HM_HEADER_LENGTH;
  415. }
  416. ssl3_finish_mac(s, p, msg_len);
  417. if (s->msg_callback)
  418. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  419. p, msg_len,
  420. s, s->msg_callback_arg);
  421. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  422. /* Don't change sequence numbers while listening */
  423. if (!s->d1->listen)
  424. s->d1->handshake_read_seq++;
  425. s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  426. return s->init_num;
  427. f_err:
  428. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  429. *ok = 0;
  430. return -1;
  431. }
  432. static int dtls1_preprocess_fragment(SSL *s,struct hm_header_st *msg_hdr,int max)
  433. {
  434. size_t frag_off,frag_len,msg_len;
  435. msg_len = msg_hdr->msg_len;
  436. frag_off = msg_hdr->frag_off;
  437. frag_len = msg_hdr->frag_len;
  438. /* sanity checking */
  439. if ( (frag_off+frag_len) > msg_len)
  440. {
  441. OPENSSL_PUT_ERROR(SSL, dtls1_preprocess_fragment, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  442. return SSL_AD_ILLEGAL_PARAMETER;
  443. }
  444. if ( (frag_off+frag_len) > (unsigned long)max)
  445. {
  446. OPENSSL_PUT_ERROR(SSL, dtls1_preprocess_fragment, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  447. return SSL_AD_ILLEGAL_PARAMETER;
  448. }
  449. if ( s->d1->r_msg_hdr.frag_off == 0) /* first fragment */
  450. {
  451. /* msg_len is limited to 2^24, but is effectively checked
  452. * against max above */
  453. if (!BUF_MEM_grow_clean(s->init_buf,msg_len+DTLS1_HM_HEADER_LENGTH))
  454. {
  455. OPENSSL_PUT_ERROR(SSL, dtls1_preprocess_fragment, ERR_R_BUF_LIB);
  456. return SSL_AD_INTERNAL_ERROR;
  457. }
  458. s->s3->tmp.message_size = msg_len;
  459. s->d1->r_msg_hdr.msg_len = msg_len;
  460. s->s3->tmp.message_type = msg_hdr->type;
  461. s->d1->r_msg_hdr.type = msg_hdr->type;
  462. s->d1->r_msg_hdr.seq = msg_hdr->seq;
  463. }
  464. else if (msg_len != s->d1->r_msg_hdr.msg_len)
  465. {
  466. /* They must be playing with us! BTW, failure to enforce
  467. * upper limit would open possibility for buffer overrun. */
  468. OPENSSL_PUT_ERROR(SSL, dtls1_preprocess_fragment, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  469. return SSL_AD_ILLEGAL_PARAMETER;
  470. }
  471. return 0; /* no error */
  472. }
  473. static int
  474. dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
  475. {
  476. /* (0) check whether the desired fragment is available
  477. * if so:
  478. * (1) copy over the fragment to s->init_buf->data[]
  479. * (2) update s->init_num
  480. */
  481. pitem *item;
  482. hm_fragment *frag;
  483. int al;
  484. *ok = 0;
  485. item = pqueue_peek(s->d1->buffered_messages);
  486. if ( item == NULL)
  487. return 0;
  488. frag = (hm_fragment *)item->data;
  489. /* Don't return if reassembly still in progress */
  490. if (frag->reassembly != NULL)
  491. return 0;
  492. if ( s->d1->handshake_read_seq == frag->msg_header.seq)
  493. {
  494. unsigned long frag_len = frag->msg_header.frag_len;
  495. pqueue_pop(s->d1->buffered_messages);
  496. al=dtls1_preprocess_fragment(s,&frag->msg_header,max);
  497. if (al==0) /* no alert */
  498. {
  499. unsigned char *p = (unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH;
  500. memcpy(&p[frag->msg_header.frag_off],
  501. frag->fragment,frag->msg_header.frag_len);
  502. }
  503. dtls1_hm_fragment_free(frag);
  504. pitem_free(item);
  505. if (al==0)
  506. {
  507. *ok = 1;
  508. return frag_len;
  509. }
  510. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  511. s->init_num = 0;
  512. *ok = 0;
  513. return -1;
  514. }
  515. else
  516. return 0;
  517. }
  518. static int
  519. dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
  520. {
  521. hm_fragment *frag = NULL;
  522. pitem *item = NULL;
  523. int i = -1, is_complete;
  524. unsigned char seq64be[8];
  525. unsigned long frag_len = msg_hdr->frag_len, max_len;
  526. if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len)
  527. goto err;
  528. /* Determine maximum allowed message size. Depends on (user set)
  529. * maximum certificate length, but 16k is minimum.
  530. */
  531. if (DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH < s->max_cert_list)
  532. max_len = s->max_cert_list;
  533. else
  534. max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
  535. if ((msg_hdr->frag_off+frag_len) > max_len)
  536. goto err;
  537. /* Try to find item in queue */
  538. memset(seq64be,0,sizeof(seq64be));
  539. seq64be[6] = (unsigned char) (msg_hdr->seq>>8);
  540. seq64be[7] = (unsigned char) msg_hdr->seq;
  541. item = pqueue_find(s->d1->buffered_messages, seq64be);
  542. if (item == NULL)
  543. {
  544. frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
  545. if ( frag == NULL)
  546. goto err;
  547. memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
  548. frag->msg_header.frag_len = frag->msg_header.msg_len;
  549. frag->msg_header.frag_off = 0;
  550. }
  551. else
  552. frag = (hm_fragment*) item->data;
  553. /* If message is already reassembled, this must be a
  554. * retransmit and can be dropped.
  555. */
  556. if (frag->reassembly == NULL)
  557. {
  558. unsigned char devnull [256];
  559. while (frag_len)
  560. {
  561. i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  562. devnull,
  563. frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0);
  564. if (i<=0) goto err;
  565. frag_len -= i;
  566. }
  567. return DTLS1_HM_FRAGMENT_RETRY;
  568. }
  569. /* read the body of the fragment (header has already been read */
  570. i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  571. frag->fragment + msg_hdr->frag_off,frag_len,0);
  572. if (i<=0 || (unsigned long)i!=frag_len)
  573. goto err;
  574. RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
  575. (long)(msg_hdr->frag_off + frag_len));
  576. RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
  577. is_complete);
  578. if (is_complete)
  579. {
  580. OPENSSL_free(frag->reassembly);
  581. frag->reassembly = NULL;
  582. }
  583. if (item == NULL)
  584. {
  585. memset(seq64be,0,sizeof(seq64be));
  586. seq64be[6] = (unsigned char)(msg_hdr->seq>>8);
  587. seq64be[7] = (unsigned char)(msg_hdr->seq);
  588. item = pitem_new(seq64be, frag);
  589. if (item == NULL)
  590. {
  591. goto err;
  592. i = -1;
  593. }
  594. pqueue_insert(s->d1->buffered_messages, item);
  595. }
  596. return DTLS1_HM_FRAGMENT_RETRY;
  597. err:
  598. if (frag != NULL) dtls1_hm_fragment_free(frag);
  599. if (item != NULL) OPENSSL_free(item);
  600. *ok = 0;
  601. return i;
  602. }
  603. static int
  604. dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok)
  605. {
  606. int i=-1;
  607. hm_fragment *frag = NULL;
  608. pitem *item = NULL;
  609. unsigned char seq64be[8];
  610. unsigned long frag_len = msg_hdr->frag_len;
  611. if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len)
  612. goto err;
  613. /* Try to find item in queue, to prevent duplicate entries */
  614. memset(seq64be,0,sizeof(seq64be));
  615. seq64be[6] = (unsigned char) (msg_hdr->seq>>8);
  616. seq64be[7] = (unsigned char) msg_hdr->seq;
  617. item = pqueue_find(s->d1->buffered_messages, seq64be);
  618. /* If we already have an entry and this one is a fragment,
  619. * don't discard it and rather try to reassemble it.
  620. */
  621. if (item != NULL && frag_len < msg_hdr->msg_len)
  622. item = NULL;
  623. /* Discard the message if sequence number was already there, is
  624. * too far in the future, already in the queue or if we received
  625. * a FINISHED before the SERVER_HELLO, which then must be a stale
  626. * retransmit.
  627. */
  628. if (msg_hdr->seq <= s->d1->handshake_read_seq ||
  629. msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
  630. (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
  631. {
  632. unsigned char devnull [256];
  633. while (frag_len)
  634. {
  635. i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  636. devnull,
  637. frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0);
  638. if (i<=0) goto err;
  639. frag_len -= i;
  640. }
  641. }
  642. else
  643. {
  644. if (frag_len && frag_len < msg_hdr->msg_len)
  645. return dtls1_reassemble_fragment(s, msg_hdr, ok);
  646. frag = dtls1_hm_fragment_new(frag_len, 0);
  647. if ( frag == NULL)
  648. goto err;
  649. memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
  650. if (frag_len)
  651. {
  652. /* read the body of the fragment (header has already been read */
  653. i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  654. frag->fragment,frag_len,0);
  655. if (i<=0 || (unsigned long)i!=frag_len)
  656. goto err;
  657. }
  658. memset(seq64be,0,sizeof(seq64be));
  659. seq64be[6] = (unsigned char)(msg_hdr->seq>>8);
  660. seq64be[7] = (unsigned char)(msg_hdr->seq);
  661. item = pitem_new(seq64be, frag);
  662. if ( item == NULL)
  663. goto err;
  664. pqueue_insert(s->d1->buffered_messages, item);
  665. }
  666. return DTLS1_HM_FRAGMENT_RETRY;
  667. err:
  668. if ( frag != NULL) dtls1_hm_fragment_free(frag);
  669. if ( item != NULL) OPENSSL_free(item);
  670. *ok = 0;
  671. return i;
  672. }
  673. static long
  674. dtls1_get_message_fragment(SSL *s, int stn, long max, int *ok)
  675. {
  676. unsigned char wire[DTLS1_HM_HEADER_LENGTH];
  677. unsigned long len, frag_off, frag_len;
  678. int i,al;
  679. struct hm_header_st msg_hdr;
  680. /* see if we have the required fragment already */
  681. if ((frag_len = dtls1_retrieve_buffered_fragment(s,max,ok)) || *ok)
  682. {
  683. if (*ok) s->init_num = frag_len;
  684. return frag_len;
  685. }
  686. /* read handshake message header */
  687. i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,wire,
  688. DTLS1_HM_HEADER_LENGTH, 0);
  689. if (i <= 0) /* nbio, or an error */
  690. {
  691. s->rwstate=SSL_READING;
  692. *ok = 0;
  693. return i;
  694. }
  695. /* Handshake fails if message header is incomplete */
  696. if (i != DTLS1_HM_HEADER_LENGTH)
  697. {
  698. al=SSL_AD_UNEXPECTED_MESSAGE;
  699. OPENSSL_PUT_ERROR(SSL, dtls1_get_message_fragment, SSL_R_UNEXPECTED_MESSAGE);
  700. goto f_err;
  701. }
  702. /* parse the message fragment header */
  703. dtls1_get_message_header(wire, &msg_hdr);
  704. /*
  705. * if this is a future (or stale) message it gets buffered
  706. * (or dropped)--no further processing at this time
  707. * While listening, we accept seq 1 (ClientHello with cookie)
  708. * although we're still expecting seq 0 (ClientHello)
  709. */
  710. if (msg_hdr.seq != s->d1->handshake_read_seq && !(s->d1->listen && msg_hdr.seq == 1))
  711. return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
  712. len = msg_hdr.msg_len;
  713. frag_off = msg_hdr.frag_off;
  714. frag_len = msg_hdr.frag_len;
  715. if (frag_len && frag_len < len)
  716. return dtls1_reassemble_fragment(s, &msg_hdr, ok);
  717. if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
  718. wire[0] == SSL3_MT_HELLO_REQUEST)
  719. {
  720. /* The server may always send 'Hello Request' messages --
  721. * we are doing a handshake anyway now, so ignore them
  722. * if their format is correct. Does not count for
  723. * 'Finished' MAC. */
  724. if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0)
  725. {
  726. if (s->msg_callback)
  727. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  728. wire, DTLS1_HM_HEADER_LENGTH, s,
  729. s->msg_callback_arg);
  730. s->init_num = 0;
  731. return dtls1_get_message_fragment(s, stn,
  732. max, ok);
  733. }
  734. else /* Incorrectly formated Hello request */
  735. {
  736. al=SSL_AD_UNEXPECTED_MESSAGE;
  737. OPENSSL_PUT_ERROR(SSL, dtls1_get_message_fragment, SSL_R_UNEXPECTED_MESSAGE);
  738. goto f_err;
  739. }
  740. }
  741. if ((al=dtls1_preprocess_fragment(s,&msg_hdr,max)))
  742. goto f_err;
  743. /* XDTLS: ressurect this when restart is in place */
  744. s->state=stn;
  745. if ( frag_len > 0)
  746. {
  747. unsigned char *p=(unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH;
  748. i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  749. &p[frag_off],frag_len,0);
  750. /* XDTLS: fix this--message fragments cannot span multiple packets */
  751. if (i <= 0)
  752. {
  753. s->rwstate=SSL_READING;
  754. *ok = 0;
  755. return i;
  756. }
  757. }
  758. else
  759. i = 0;
  760. /* XDTLS: an incorrectly formatted fragment should cause the
  761. * handshake to fail */
  762. if (i != (int)frag_len)
  763. {
  764. al=SSL3_AD_ILLEGAL_PARAMETER;
  765. OPENSSL_PUT_ERROR(SSL, dtls1_get_message_fragment, SSL3_AD_ILLEGAL_PARAMETER);
  766. goto f_err;
  767. }
  768. *ok = 1;
  769. /* Note that s->init_num is *not* used as current offset in
  770. * s->init_buf->data, but as a counter summing up fragments'
  771. * lengths: as soon as they sum up to handshake packet
  772. * length, we assume we have got all the fragments. */
  773. s->init_num = frag_len;
  774. return frag_len;
  775. f_err:
  776. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  777. s->init_num = 0;
  778. *ok=0;
  779. return(-1);
  780. }
  781. /* for these 2 messages, we need to
  782. * ssl->enc_read_ctx re-init
  783. * ssl->s3->read_sequence zero
  784. * ssl->s3->read_mac_secret re-init
  785. * ssl->session->read_sym_enc assign
  786. * ssl->session->read_compression assign
  787. * ssl->session->read_hash assign
  788. */
  789. int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
  790. {
  791. unsigned char *p;
  792. if (s->state == a)
  793. {
  794. p=(unsigned char *)s->init_buf->data;
  795. *p++=SSL3_MT_CCS;
  796. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  797. s->init_num=DTLS1_CCS_HEADER_LENGTH;
  798. if (s->version == DTLS1_BAD_VER) {
  799. s->d1->next_handshake_write_seq++;
  800. s2n(s->d1->handshake_write_seq,p);
  801. s->init_num+=2;
  802. }
  803. s->init_off=0;
  804. dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
  805. s->d1->handshake_write_seq, 0, 0);
  806. /* buffer the message to handle re-xmits */
  807. dtls1_buffer_message(s, 1);
  808. s->state=b;
  809. }
  810. /* SSL3_ST_CW_CHANGE_B */
  811. return(dtls1_do_write(s,SSL3_RT_CHANGE_CIPHER_SPEC));
  812. }
  813. int dtls1_read_failed(SSL *s, int code)
  814. {
  815. if ( code > 0)
  816. {
  817. fprintf( stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
  818. return 1;
  819. }
  820. if (!dtls1_is_timer_expired(s))
  821. {
  822. /* not a timeout, none of our business,
  823. let higher layers handle this. in fact it's probably an error */
  824. return code;
  825. }
  826. #ifndef OPENSSL_NO_HEARTBEATS
  827. if (!SSL_in_init(s) && !s->tlsext_hb_pending) /* done, no need to send a retransmit */
  828. #else
  829. if (!SSL_in_init(s)) /* done, no need to send a retransmit */
  830. #endif
  831. {
  832. BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
  833. return code;
  834. }
  835. #if 0 /* for now, each alert contains only one record number */
  836. item = pqueue_peek(state->rcvd_records);
  837. if ( item )
  838. {
  839. /* send an alert immediately for all the missing records */
  840. }
  841. else
  842. #endif
  843. #if 0 /* no more alert sending, just retransmit the last set of messages */
  844. if ( state->timeout.read_timeouts >= DTLS1_TMO_READ_COUNT)
  845. ssl3_send_alert(s,SSL3_AL_WARNING,
  846. DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  847. #endif
  848. return dtls1_handle_timeout(s);
  849. }
  850. int
  851. dtls1_get_queue_priority(unsigned short seq, int is_ccs)
  852. {
  853. /* The index of the retransmission queue actually is the message sequence number,
  854. * since the queue only contains messages of a single handshake. However, the
  855. * ChangeCipherSpec has no message sequence number and so using only the sequence
  856. * will result in the CCS and Finished having the same index. To prevent this,
  857. * the sequence number is multiplied by 2. In case of a CCS 1 is subtracted.
  858. * This does not only differ CSS and Finished, it also maintains the order of the
  859. * index (important for priority queues) and fits in the unsigned short variable.
  860. */
  861. return seq * 2 - is_ccs;
  862. }
  863. int
  864. dtls1_retransmit_buffered_messages(SSL *s)
  865. {
  866. pqueue sent = s->d1->sent_messages;
  867. piterator iter;
  868. pitem *item;
  869. hm_fragment *frag;
  870. int found = 0;
  871. iter = pqueue_iterator(sent);
  872. for ( item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter))
  873. {
  874. frag = (hm_fragment *)item->data;
  875. if ( dtls1_retransmit_message(s,
  876. (unsigned short)dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs),
  877. 0, &found) <= 0 && found)
  878. {
  879. fprintf(stderr, "dtls1_retransmit_message() failed\n");
  880. return -1;
  881. }
  882. }
  883. return 1;
  884. }
  885. int
  886. dtls1_buffer_message(SSL *s, int is_ccs)
  887. {
  888. pitem *item;
  889. hm_fragment *frag;
  890. unsigned char seq64be[8];
  891. /* this function is called immediately after a message has
  892. * been serialized */
  893. assert(s->init_off == 0);
  894. frag = dtls1_hm_fragment_new(s->init_num, 0);
  895. memcpy(frag->fragment, s->init_buf->data, s->init_num);
  896. if ( is_ccs)
  897. {
  898. assert(s->d1->w_msg_hdr.msg_len +
  899. DTLS1_CCS_HEADER_LENGTH == (unsigned int)s->init_num);
  900. }
  901. else
  902. {
  903. assert(s->d1->w_msg_hdr.msg_len +
  904. DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
  905. }
  906. frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
  907. frag->msg_header.seq = s->d1->w_msg_hdr.seq;
  908. frag->msg_header.type = s->d1->w_msg_hdr.type;
  909. frag->msg_header.frag_off = 0;
  910. frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
  911. frag->msg_header.is_ccs = is_ccs;
  912. /* save current state*/
  913. frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
  914. frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
  915. frag->msg_header.saved_retransmit_state.compress = s->compress;
  916. frag->msg_header.saved_retransmit_state.session = s->session;
  917. frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
  918. memset(seq64be,0,sizeof(seq64be));
  919. seq64be[6] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,
  920. frag->msg_header.is_ccs)>>8);
  921. seq64be[7] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,
  922. frag->msg_header.is_ccs));
  923. item = pitem_new(seq64be, frag);
  924. if ( item == NULL)
  925. {
  926. dtls1_hm_fragment_free(frag);
  927. return 0;
  928. }
  929. #if 0
  930. fprintf( stderr, "buffered messge: \ttype = %xx\n", msg_buf->type);
  931. fprintf( stderr, "\t\t\t\t\tlen = %d\n", msg_buf->len);
  932. fprintf( stderr, "\t\t\t\t\tseq_num = %d\n", msg_buf->seq_num);
  933. #endif
  934. pqueue_insert(s->d1->sent_messages, item);
  935. return 1;
  936. }
  937. int
  938. dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
  939. int *found)
  940. {
  941. int ret;
  942. /* XDTLS: for now assuming that read/writes are blocking */
  943. pitem *item;
  944. hm_fragment *frag ;
  945. unsigned long header_length;
  946. unsigned char seq64be[8];
  947. struct dtls1_retransmit_state saved_state;
  948. unsigned char save_write_sequence[8];
  949. /*
  950. assert(s->init_num == 0);
  951. assert(s->init_off == 0);
  952. */
  953. /* XDTLS: the requested message ought to be found, otherwise error */
  954. memset(seq64be,0,sizeof(seq64be));
  955. seq64be[6] = (unsigned char)(seq>>8);
  956. seq64be[7] = (unsigned char)seq;
  957. item = pqueue_find(s->d1->sent_messages, seq64be);
  958. if ( item == NULL)
  959. {
  960. fprintf(stderr, "retransmit: message %d non-existant\n", seq);
  961. *found = 0;
  962. return 0;
  963. }
  964. *found = 1;
  965. frag = (hm_fragment *)item->data;
  966. if ( frag->msg_header.is_ccs)
  967. header_length = DTLS1_CCS_HEADER_LENGTH;
  968. else
  969. header_length = DTLS1_HM_HEADER_LENGTH;
  970. memcpy(s->init_buf->data, frag->fragment,
  971. frag->msg_header.msg_len + header_length);
  972. s->init_num = frag->msg_header.msg_len + header_length;
  973. dtls1_set_message_header_int(s, frag->msg_header.type,
  974. frag->msg_header.msg_len, frag->msg_header.seq, 0,
  975. frag->msg_header.frag_len);
  976. /* save current state */
  977. saved_state.enc_write_ctx = s->enc_write_ctx;
  978. saved_state.write_hash = s->write_hash;
  979. saved_state.compress = s->compress;
  980. saved_state.session = s->session;
  981. saved_state.epoch = s->d1->w_epoch;
  982. saved_state.epoch = s->d1->w_epoch;
  983. s->d1->retransmitting = 1;
  984. /* restore state in which the message was originally sent */
  985. s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
  986. s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
  987. s->compress = frag->msg_header.saved_retransmit_state.compress;
  988. s->session = frag->msg_header.saved_retransmit_state.session;
  989. s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
  990. if (frag->msg_header.saved_retransmit_state.epoch == saved_state.epoch - 1)
  991. {
  992. memcpy(save_write_sequence, s->s3->write_sequence, sizeof(s->s3->write_sequence));
  993. memcpy(s->s3->write_sequence, s->d1->last_write_sequence, sizeof(s->s3->write_sequence));
  994. }
  995. ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
  996. SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
  997. /* restore current state */
  998. s->enc_write_ctx = saved_state.enc_write_ctx;
  999. s->write_hash = saved_state.write_hash;
  1000. s->compress = saved_state.compress;
  1001. s->session = saved_state.session;
  1002. s->d1->w_epoch = saved_state.epoch;
  1003. if (frag->msg_header.saved_retransmit_state.epoch == saved_state.epoch - 1)
  1004. {
  1005. memcpy(s->d1->last_write_sequence, s->s3->write_sequence, sizeof(s->s3->write_sequence));
  1006. memcpy(s->s3->write_sequence, save_write_sequence, sizeof(s->s3->write_sequence));
  1007. }
  1008. s->d1->retransmitting = 0;
  1009. (void)BIO_flush(SSL_get_wbio(s));
  1010. return ret;
  1011. }
  1012. /* call this function when the buffered messages are no longer needed */
  1013. void
  1014. dtls1_clear_record_buffer(SSL *s)
  1015. {
  1016. pitem *item;
  1017. for(item = pqueue_pop(s->d1->sent_messages);
  1018. item != NULL; item = pqueue_pop(s->d1->sent_messages))
  1019. {
  1020. dtls1_hm_fragment_free((hm_fragment *)item->data);
  1021. pitem_free(item);
  1022. }
  1023. }
  1024. unsigned char *
  1025. dtls1_set_message_header(SSL *s, unsigned char *p, unsigned char mt,
  1026. unsigned long len, unsigned long frag_off, unsigned long frag_len)
  1027. {
  1028. /* Don't change sequence numbers while listening */
  1029. if (frag_off == 0 && !s->d1->listen)
  1030. {
  1031. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  1032. s->d1->next_handshake_write_seq++;
  1033. }
  1034. dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
  1035. frag_off, frag_len);
  1036. return p += DTLS1_HM_HEADER_LENGTH;
  1037. }
  1038. /* don't actually do the writing, wait till the MTU has been retrieved */
  1039. static void
  1040. dtls1_set_message_header_int(SSL *s, unsigned char mt,
  1041. unsigned long len, unsigned short seq_num, unsigned long frag_off,
  1042. unsigned long frag_len)
  1043. {
  1044. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1045. msg_hdr->type = mt;
  1046. msg_hdr->msg_len = len;
  1047. msg_hdr->seq = seq_num;
  1048. msg_hdr->frag_off = frag_off;
  1049. msg_hdr->frag_len = frag_len;
  1050. }
  1051. static void
  1052. dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  1053. unsigned long frag_len)
  1054. {
  1055. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1056. msg_hdr->frag_off = frag_off;
  1057. msg_hdr->frag_len = frag_len;
  1058. }
  1059. static unsigned char *
  1060. dtls1_write_message_header(SSL *s, unsigned char *p)
  1061. {
  1062. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1063. *p++ = msg_hdr->type;
  1064. l2n3(msg_hdr->msg_len, p);
  1065. s2n(msg_hdr->seq, p);
  1066. l2n3(msg_hdr->frag_off, p);
  1067. l2n3(msg_hdr->frag_len, p);
  1068. return p;
  1069. }
  1070. unsigned int
  1071. dtls1_min_mtu(void)
  1072. {
  1073. return (g_probable_mtu[(sizeof(g_probable_mtu) /
  1074. sizeof(g_probable_mtu[0])) - 1]);
  1075. }
  1076. static unsigned int
  1077. dtls1_guess_mtu(unsigned int curr_mtu)
  1078. {
  1079. unsigned int i;
  1080. if ( curr_mtu == 0 )
  1081. return g_probable_mtu[0] ;
  1082. for ( i = 0; i < sizeof(g_probable_mtu)/sizeof(g_probable_mtu[0]); i++)
  1083. if ( curr_mtu > g_probable_mtu[i])
  1084. return g_probable_mtu[i];
  1085. return curr_mtu;
  1086. }
  1087. void
  1088. dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
  1089. {
  1090. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  1091. msg_hdr->type = *(data++);
  1092. n2l3(data, msg_hdr->msg_len);
  1093. n2s(data, msg_hdr->seq);
  1094. n2l3(data, msg_hdr->frag_off);
  1095. n2l3(data, msg_hdr->frag_len);
  1096. }
  1097. void
  1098. dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
  1099. {
  1100. memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
  1101. ccs_hdr->type = *(data++);
  1102. }
  1103. int dtls1_shutdown(SSL *s)
  1104. {
  1105. int ret;
  1106. ret = ssl3_shutdown(s);
  1107. return ret;
  1108. }
  1109. #ifndef OPENSSL_NO_HEARTBEATS
  1110. int
  1111. dtls1_process_heartbeat(SSL *s)
  1112. {
  1113. unsigned char *p = &s->s3->rrec.data[0], *pl;
  1114. unsigned short hbtype;
  1115. unsigned int payload;
  1116. unsigned int padding = 16; /* Use minimum padding */
  1117. /* Read type and payload length first */
  1118. hbtype = *p++;
  1119. n2s(p, payload);
  1120. pl = p;
  1121. if (s->msg_callback)
  1122. s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
  1123. &s->s3->rrec.data[0], s->s3->rrec.length,
  1124. s, s->msg_callback_arg);
  1125. if (hbtype == TLS1_HB_REQUEST)
  1126. {
  1127. unsigned char *buffer, *bp;
  1128. int r;
  1129. /* Allocate memory for the response, size is 1 byte
  1130. * message type, plus 2 bytes payload length, plus
  1131. * payload, plus padding
  1132. */
  1133. buffer = OPENSSL_malloc(1 + 2 + payload + padding);
  1134. bp = buffer;
  1135. /* Enter response type, length and copy payload */
  1136. *bp++ = TLS1_HB_RESPONSE;
  1137. s2n(payload, bp);
  1138. memcpy(bp, pl, payload);
  1139. bp += payload;
  1140. /* Random padding */
  1141. RAND_pseudo_bytes(bp, padding);
  1142. r = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload + padding);
  1143. if (r >= 0 && s->msg_callback)
  1144. s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
  1145. buffer, 3 + payload + padding,
  1146. s, s->msg_callback_arg);
  1147. OPENSSL_free(buffer);
  1148. if (r < 0)
  1149. return r;
  1150. }
  1151. else if (hbtype == TLS1_HB_RESPONSE)
  1152. {
  1153. unsigned int seq;
  1154. /* We only send sequence numbers (2 bytes unsigned int),
  1155. * and 16 random bytes, so we just try to read the
  1156. * sequence number */
  1157. n2s(pl, seq);
  1158. if (payload == 18 && seq == s->tlsext_hb_seq)
  1159. {
  1160. dtls1_stop_timer(s);
  1161. s->tlsext_hb_seq++;
  1162. s->tlsext_hb_pending = 0;
  1163. }
  1164. }
  1165. return 0;
  1166. }
  1167. int
  1168. dtls1_heartbeat(SSL *s)
  1169. {
  1170. unsigned char *buf, *p;
  1171. int ret;
  1172. unsigned int payload = 18; /* Sequence number + random bytes */
  1173. unsigned int padding = 16; /* Use minimum padding */
  1174. /* Only send if peer supports and accepts HB requests... */
  1175. if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
  1176. s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
  1177. {
  1178. OPENSSL_PUT_ERROR(SSL, dtls1_heartbeat, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
  1179. return -1;
  1180. }
  1181. /* ...and there is none in flight yet... */
  1182. if (s->tlsext_hb_pending)
  1183. {
  1184. OPENSSL_PUT_ERROR(SSL, dtls1_heartbeat, SSL_R_TLS_HEARTBEAT_PENDING);
  1185. return -1;
  1186. }
  1187. /* ...and no handshake in progress. */
  1188. if (SSL_in_init(s) || s->in_handshake)
  1189. {
  1190. OPENSSL_PUT_ERROR(SSL, dtls1_heartbeat, SSL_R_UNEXPECTED_MESSAGE);
  1191. return -1;
  1192. }
  1193. /* Check if padding is too long, payload and padding
  1194. * must not exceed 2^14 - 3 = 16381 bytes in total.
  1195. */
  1196. assert(payload + padding <= 16381);
  1197. /* Create HeartBeat message, we just use a sequence number
  1198. * as payload to distuingish different messages and add
  1199. * some random stuff.
  1200. * - Message Type, 1 byte
  1201. * - Payload Length, 2 bytes (unsigned int)
  1202. * - Payload, the sequence number (2 bytes uint)
  1203. * - Payload, random bytes (16 bytes uint)
  1204. * - Padding
  1205. */
  1206. buf = OPENSSL_malloc(1 + 2 + payload + padding);
  1207. p = buf;
  1208. /* Message Type */
  1209. *p++ = TLS1_HB_REQUEST;
  1210. /* Payload length (18 bytes here) */
  1211. s2n(payload, p);
  1212. /* Sequence number */
  1213. s2n(s->tlsext_hb_seq, p);
  1214. /* 16 random bytes */
  1215. RAND_pseudo_bytes(p, 16);
  1216. p += 16;
  1217. /* Random padding */
  1218. RAND_pseudo_bytes(p, padding);
  1219. ret = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
  1220. if (ret >= 0)
  1221. {
  1222. if (s->msg_callback)
  1223. s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
  1224. buf, 3 + payload + padding,
  1225. s, s->msg_callback_arg);
  1226. dtls1_start_timer(s);
  1227. s->tlsext_hb_pending = 1;
  1228. }
  1229. OPENSSL_free(buf);
  1230. return ret;
  1231. }
  1232. #endif