Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

886 строки
30 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 "internal.h"
  125. /* TODO(davidben): 28 comes from the size of IP + UDP header. Is this reasonable
  126. * for these values? Notably, why is kMinMTU a function of the transport
  127. * protocol's overhead rather than, say, what's needed to hold a minimally-sized
  128. * handshake fragment plus protocol overhead. */
  129. /* kMinMTU is the minimum acceptable MTU value. */
  130. static const unsigned int kMinMTU = 256 - 28;
  131. /* kDefaultMTU is the default MTU value to use if neither the user nor
  132. * the underlying BIO supplies one. */
  133. static const unsigned int kDefaultMTU = 1500 - 28;
  134. /* kMaxHandshakeBuffer is the maximum number of handshake messages ahead of the
  135. * current one to buffer. */
  136. static const unsigned int kHandshakeBufferSize = 10;
  137. static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  138. unsigned long frag_len);
  139. static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
  140. static hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len,
  141. int reassembly) {
  142. hm_fragment *frag = NULL;
  143. uint8_t *buf = NULL;
  144. uint8_t *bitmask = NULL;
  145. frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment));
  146. if (frag == NULL) {
  147. OPENSSL_PUT_ERROR(SSL, dtls1_hm_fragment_new, ERR_R_MALLOC_FAILURE);
  148. return NULL;
  149. }
  150. if (frag_len) {
  151. buf = (uint8_t *)OPENSSL_malloc(frag_len);
  152. if (buf == NULL) {
  153. OPENSSL_PUT_ERROR(SSL, dtls1_hm_fragment_new, ERR_R_MALLOC_FAILURE);
  154. OPENSSL_free(frag);
  155. return NULL;
  156. }
  157. }
  158. /* zero length fragment gets zero frag->fragment */
  159. frag->fragment = buf;
  160. /* Initialize reassembly bitmask if necessary */
  161. if (reassembly && frag_len > 0) {
  162. if (frag_len + 7 < frag_len) {
  163. OPENSSL_PUT_ERROR(SSL, dtls1_hm_fragment_new, ERR_R_OVERFLOW);
  164. return NULL;
  165. }
  166. size_t bitmask_len = (frag_len + 7) / 8;
  167. bitmask = (uint8_t *)OPENSSL_malloc(bitmask_len);
  168. if (bitmask == NULL) {
  169. OPENSSL_PUT_ERROR(SSL, dtls1_hm_fragment_new, ERR_R_MALLOC_FAILURE);
  170. if (buf != NULL) {
  171. OPENSSL_free(buf);
  172. }
  173. OPENSSL_free(frag);
  174. return NULL;
  175. }
  176. memset(bitmask, 0, bitmask_len);
  177. }
  178. frag->reassembly = bitmask;
  179. return frag;
  180. }
  181. void dtls1_hm_fragment_free(hm_fragment *frag) {
  182. if (frag == NULL) {
  183. return;
  184. }
  185. OPENSSL_free(frag->fragment);
  186. OPENSSL_free(frag->reassembly);
  187. OPENSSL_free(frag);
  188. }
  189. #if !defined(inline)
  190. #define inline __inline
  191. #endif
  192. /* bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
  193. * exclusive, set. */
  194. static inline uint8_t bit_range(size_t start, size_t end) {
  195. return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
  196. }
  197. /* dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
  198. * as received in |frag|. If |frag| becomes complete, it clears
  199. * |frag->reassembly|. The range must be within the bounds of |frag|'s message
  200. * and |frag->reassembly| must not be NULL. */
  201. static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
  202. size_t end) {
  203. size_t i;
  204. size_t msg_len = frag->msg_header.msg_len;
  205. if (frag->reassembly == NULL || start > end || end > msg_len) {
  206. assert(0);
  207. return;
  208. }
  209. /* A zero-length message will never have a pending reassembly. */
  210. assert(msg_len > 0);
  211. if ((start >> 3) == (end >> 3)) {
  212. frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
  213. } else {
  214. frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
  215. for (i = (start >> 3) + 1; i < (end >> 3); i++) {
  216. frag->reassembly[i] = 0xff;
  217. }
  218. if ((end & 7) != 0) {
  219. frag->reassembly[end >> 3] |= bit_range(0, end & 7);
  220. }
  221. }
  222. /* Check if the fragment is complete. */
  223. for (i = 0; i < (msg_len >> 3); i++) {
  224. if (frag->reassembly[i] != 0xff) {
  225. return;
  226. }
  227. }
  228. if ((msg_len & 7) != 0 &&
  229. frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
  230. return;
  231. }
  232. OPENSSL_free(frag->reassembly);
  233. frag->reassembly = NULL;
  234. }
  235. /* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
  236. * SSL3_RT_CHANGE_CIPHER_SPEC) */
  237. int dtls1_do_write(SSL *s, int type, enum dtls1_use_epoch_t use_epoch) {
  238. int ret;
  239. int curr_mtu;
  240. unsigned int len, frag_off;
  241. /* AHA! Figure out the MTU, and stick to the right size */
  242. if (s->d1->mtu < dtls1_min_mtu() &&
  243. !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
  244. long mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  245. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  246. s->d1->mtu = (unsigned)mtu;
  247. } else {
  248. s->d1->mtu = kDefaultMTU;
  249. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, s->d1->mtu, NULL);
  250. }
  251. }
  252. /* should have something reasonable now */
  253. assert(s->d1->mtu >= dtls1_min_mtu());
  254. if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {
  255. assert(s->init_num ==
  256. (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
  257. }
  258. /* Determine the maximum overhead of the current cipher. */
  259. size_t max_overhead = SSL_AEAD_CTX_max_overhead(s->aead_write_ctx);
  260. frag_off = 0;
  261. while (s->init_num) {
  262. /* Account for data in the buffering BIO; multiple records may be packed
  263. * into a single packet during the handshake.
  264. *
  265. * TODO(davidben): This is buggy; if the MTU is larger than the buffer size,
  266. * the large record will be split across two packets. Moreover, in that
  267. * case, the |dtls1_write_bytes| call may not return synchronously. This
  268. * will break on retry as the |s->init_off| and |s->init_num| adjustment
  269. * will run a second time. */
  270. curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
  271. DTLS1_RT_HEADER_LENGTH - max_overhead;
  272. if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
  273. /* Flush the buffer and continue with a fresh packet.
  274. *
  275. * TODO(davidben): If |BIO_flush| is not synchronous and requires multiple
  276. * calls to |dtls1_do_write|, |frag_off| will be wrong. */
  277. ret = BIO_flush(SSL_get_wbio(s));
  278. if (ret <= 0) {
  279. return ret;
  280. }
  281. assert(BIO_wpending(SSL_get_wbio(s)) == 0);
  282. curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH - max_overhead;
  283. }
  284. /* XDTLS: this function is too long. split out the CCS part */
  285. if (type == SSL3_RT_HANDSHAKE) {
  286. /* If this isn't the first fragment, reserve space to prepend a new
  287. * fragment header. This will override the body of a previous fragment. */
  288. if (s->init_off != 0) {
  289. assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
  290. s->init_off -= DTLS1_HM_HEADER_LENGTH;
  291. s->init_num += DTLS1_HM_HEADER_LENGTH;
  292. }
  293. if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
  294. /* To make forward progress, the MTU must, at minimum, fit the handshake
  295. * header and one byte of handshake body. */
  296. OPENSSL_PUT_ERROR(SSL, dtls1_do_write, SSL_R_MTU_TOO_SMALL);
  297. return -1;
  298. }
  299. if (s->init_num > curr_mtu) {
  300. len = curr_mtu;
  301. } else {
  302. len = s->init_num;
  303. }
  304. assert(len >= DTLS1_HM_HEADER_LENGTH);
  305. dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH);
  306. dtls1_write_message_header(
  307. s, (uint8_t *)&s->init_buf->data[s->init_off]);
  308. } else {
  309. assert(type == SSL3_RT_CHANGE_CIPHER_SPEC);
  310. /* ChangeCipherSpec cannot be fragmented. */
  311. if (s->init_num > curr_mtu) {
  312. OPENSSL_PUT_ERROR(SSL, dtls1_do_write, SSL_R_MTU_TOO_SMALL);
  313. return -1;
  314. }
  315. len = s->init_num;
  316. }
  317. ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len,
  318. use_epoch);
  319. if (ret < 0) {
  320. return -1;
  321. }
  322. /* bad if this assert fails, only part of the handshake message got sent.
  323. * But why would this happen? */
  324. assert(len == (unsigned int)ret);
  325. if (ret == s->init_num) {
  326. if (s->msg_callback) {
  327. s->msg_callback(1, s->version, type, s->init_buf->data,
  328. (size_t)(s->init_off + s->init_num), s,
  329. s->msg_callback_arg);
  330. }
  331. s->init_off = 0; /* done writing this message */
  332. s->init_num = 0;
  333. return 1;
  334. }
  335. s->init_off += ret;
  336. s->init_num -= ret;
  337. frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
  338. }
  339. return 0;
  340. }
  341. /* dtls1_is_next_message_complete returns one if the next handshake message is
  342. * complete and zero otherwise. */
  343. static int dtls1_is_next_message_complete(SSL *s) {
  344. pitem *item = pqueue_peek(s->d1->buffered_messages);
  345. if (item == NULL) {
  346. return 0;
  347. }
  348. hm_fragment *frag = (hm_fragment *)item->data;
  349. assert(s->d1->handshake_read_seq <= frag->msg_header.seq);
  350. return s->d1->handshake_read_seq == frag->msg_header.seq &&
  351. frag->reassembly == NULL;
  352. }
  353. /* dtls1_discard_fragment_body discards a handshake fragment body of length
  354. * |frag_len|. It returns one on success and zero on error.
  355. *
  356. * TODO(davidben): This function will go away when ssl_read_bytes is gone from
  357. * the DTLS side. */
  358. static int dtls1_discard_fragment_body(SSL *s, size_t frag_len) {
  359. uint8_t discard[256];
  360. while (frag_len > 0) {
  361. size_t chunk = frag_len < sizeof(discard) ? frag_len : sizeof(discard);
  362. int ret = dtls1_read_bytes(s, SSL3_RT_HANDSHAKE, discard, chunk, 0);
  363. if (ret != chunk) {
  364. return 0;
  365. }
  366. frag_len -= chunk;
  367. }
  368. return 1;
  369. }
  370. /* dtls1_get_buffered_message returns the buffered message corresponding to
  371. * |msg_hdr|. If none exists, it creates a new one and inserts it in the
  372. * queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
  373. * returns NULL on failure. The caller does not take ownership of the result. */
  374. static hm_fragment *dtls1_get_buffered_message(
  375. SSL *s, const struct hm_header_st *msg_hdr) {
  376. uint8_t seq64be[8];
  377. memset(seq64be, 0, sizeof(seq64be));
  378. seq64be[6] = (uint8_t)(msg_hdr->seq >> 8);
  379. seq64be[7] = (uint8_t)msg_hdr->seq;
  380. pitem *item = pqueue_find(s->d1->buffered_messages, seq64be);
  381. hm_fragment *frag;
  382. if (item == NULL) {
  383. /* This is the first fragment from this message. */
  384. frag = dtls1_hm_fragment_new(msg_hdr->msg_len,
  385. 1 /* reassembly buffer needed */);
  386. if (frag == NULL) {
  387. return NULL;
  388. }
  389. memcpy(&frag->msg_header, msg_hdr, sizeof(*msg_hdr));
  390. item = pitem_new(seq64be, frag);
  391. if (item == NULL) {
  392. dtls1_hm_fragment_free(frag);
  393. return NULL;
  394. }
  395. item = pqueue_insert(s->d1->buffered_messages, item);
  396. /* |pqueue_insert| fails iff a duplicate item is inserted, but |item| cannot
  397. * be a duplicate. */
  398. assert(item != NULL);
  399. } else {
  400. frag = item->data;
  401. assert(frag->msg_header.seq == msg_hdr->seq);
  402. if (frag->msg_header.type != msg_hdr->type ||
  403. frag->msg_header.msg_len != msg_hdr->msg_len) {
  404. /* The new fragment must be compatible with the previous fragments from
  405. * this message. */
  406. OPENSSL_PUT_ERROR(SSL, dtls1_get_buffered_message,
  407. SSL_R_FRAGMENT_MISMATCH);
  408. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  409. return NULL;
  410. }
  411. }
  412. return frag;
  413. }
  414. /* dtls1_max_handshake_message_len returns the maximum number of bytes
  415. * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but may
  416. * be greater if the maximum certificate list size requires it. */
  417. static size_t dtls1_max_handshake_message_len(const SSL *s) {
  418. size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
  419. if (max_len < s->max_cert_list) {
  420. return s->max_cert_list;
  421. }
  422. return max_len;
  423. }
  424. /* dtls1_process_fragment reads a handshake fragment and processes it. It
  425. * returns one if a fragment was successfully processed and 0 or -1 on error. */
  426. static int dtls1_process_fragment(SSL *s) {
  427. /* Read handshake message header.
  428. *
  429. * TODO(davidben): ssl_read_bytes allows splitting the fragment header and
  430. * body across two records. Change this interface to consume the fragment in
  431. * one pass. */
  432. uint8_t header[DTLS1_HM_HEADER_LENGTH];
  433. int ret = dtls1_read_bytes(s, SSL3_RT_HANDSHAKE, header,
  434. DTLS1_HM_HEADER_LENGTH, 0);
  435. if (ret <= 0) {
  436. return ret;
  437. }
  438. if (ret != DTLS1_HM_HEADER_LENGTH) {
  439. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment, SSL_R_UNEXPECTED_MESSAGE);
  440. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  441. return -1;
  442. }
  443. /* Parse the message fragment header. */
  444. struct hm_header_st msg_hdr;
  445. dtls1_get_message_header(header, &msg_hdr);
  446. const size_t frag_off = msg_hdr.frag_off;
  447. const size_t frag_len = msg_hdr.frag_len;
  448. const size_t msg_len = msg_hdr.msg_len;
  449. if (frag_off > msg_len || frag_off + frag_len < frag_off ||
  450. frag_off + frag_len > msg_len ||
  451. msg_len > dtls1_max_handshake_message_len(s)) {
  452. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment,
  453. SSL_R_EXCESSIVE_MESSAGE_SIZE);
  454. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  455. return -1;
  456. }
  457. if (msg_hdr.seq < s->d1->handshake_read_seq ||
  458. msg_hdr.seq > (unsigned)s->d1->handshake_read_seq +
  459. kHandshakeBufferSize) {
  460. /* Ignore fragments from the past, or ones too far in the future. */
  461. if (!dtls1_discard_fragment_body(s, frag_len)) {
  462. return -1;
  463. }
  464. return 1;
  465. }
  466. hm_fragment *frag = dtls1_get_buffered_message(s, &msg_hdr);
  467. if (frag == NULL) {
  468. return -1;
  469. }
  470. assert(frag->msg_header.msg_len == msg_len);
  471. if (frag->reassembly == NULL) {
  472. /* The message is already assembled. */
  473. if (!dtls1_discard_fragment_body(s, frag_len)) {
  474. return -1;
  475. }
  476. return 1;
  477. }
  478. assert(msg_len > 0);
  479. /* Read the body of the fragment. */
  480. ret = dtls1_read_bytes(s, SSL3_RT_HANDSHAKE, frag->fragment + frag_off,
  481. frag_len, 0);
  482. if (ret != frag_len) {
  483. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment, SSL_R_UNEXPECTED_MESSAGE);
  484. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  485. return -1;
  486. }
  487. dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
  488. return 1;
  489. }
  490. /* dtls1_get_message reads a handshake message of message type |msg_type| (any
  491. * if |msg_type| == -1), maximum acceptable body length |max|. Read an entire
  492. * handshake message. Handshake messages arrive in fragments. */
  493. long dtls1_get_message(SSL *s, int st1, int stn, int msg_type, long max,
  494. enum ssl_hash_message_t hash_message, int *ok) {
  495. pitem *item = NULL;
  496. hm_fragment *frag = NULL;
  497. int al;
  498. /* s3->tmp is used to store messages that are unexpected, caused
  499. * by the absence of an optional handshake message */
  500. if (s->s3->tmp.reuse_message) {
  501. /* A ssl_dont_hash_message call cannot be combined with reuse_message; the
  502. * ssl_dont_hash_message would have to have been applied to the previous
  503. * call. */
  504. assert(hash_message == ssl_hash_message);
  505. s->s3->tmp.reuse_message = 0;
  506. if (msg_type >= 0 && s->s3->tmp.message_type != msg_type) {
  507. al = SSL_AD_UNEXPECTED_MESSAGE;
  508. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_UNEXPECTED_MESSAGE);
  509. goto f_err;
  510. }
  511. *ok = 1;
  512. s->init_msg = (uint8_t *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  513. s->init_num = (int)s->s3->tmp.message_size;
  514. return s->init_num;
  515. }
  516. /* Process fragments until one is found. */
  517. while (!dtls1_is_next_message_complete(s)) {
  518. int ret = dtls1_process_fragment(s);
  519. if (ret <= 0) {
  520. *ok = 0;
  521. return ret;
  522. }
  523. }
  524. /* Read out the next complete handshake message. */
  525. item = pqueue_pop(s->d1->buffered_messages);
  526. assert(item != NULL);
  527. frag = (hm_fragment *)item->data;
  528. assert(s->d1->handshake_read_seq == frag->msg_header.seq);
  529. assert(frag->reassembly == NULL);
  530. if (frag->msg_header.msg_len > (size_t)max) {
  531. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  532. goto err;
  533. }
  534. CBB cbb;
  535. if (!BUF_MEM_grow(s->init_buf,
  536. (size_t)frag->msg_header.msg_len +
  537. DTLS1_HM_HEADER_LENGTH) ||
  538. !CBB_init_fixed(&cbb, (uint8_t *)s->init_buf->data, s->init_buf->max)) {
  539. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, ERR_R_MALLOC_FAILURE);
  540. goto err;
  541. }
  542. /* Reconstruct the assembled message. */
  543. size_t len;
  544. if (!CBB_add_u8(&cbb, frag->msg_header.type) ||
  545. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  546. !CBB_add_u16(&cbb, frag->msg_header.seq) ||
  547. !CBB_add_u24(&cbb, 0 /* frag_off */) ||
  548. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  549. !CBB_add_bytes(&cbb, frag->fragment, frag->msg_header.msg_len) ||
  550. !CBB_finish(&cbb, NULL, &len)) {
  551. CBB_cleanup(&cbb);
  552. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, ERR_R_INTERNAL_ERROR);
  553. goto err;
  554. }
  555. assert(len == (size_t)frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
  556. s->d1->handshake_read_seq++;
  557. /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
  558. * |ssl_get_message| API. */
  559. s->s3->tmp.message_type = frag->msg_header.type;
  560. s->s3->tmp.message_size = frag->msg_header.msg_len;
  561. s->init_msg = (uint8_t *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  562. s->init_num = frag->msg_header.msg_len;
  563. if (msg_type >= 0 && s->s3->tmp.message_type != msg_type) {
  564. al = SSL_AD_UNEXPECTED_MESSAGE;
  565. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_UNEXPECTED_MESSAGE);
  566. goto f_err;
  567. }
  568. if (hash_message == ssl_hash_message && !ssl3_hash_current_message(s)) {
  569. goto err;
  570. }
  571. if (s->msg_callback) {
  572. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
  573. s->init_num + DTLS1_HM_HEADER_LENGTH, s,
  574. s->msg_callback_arg);
  575. }
  576. pitem_free(item);
  577. dtls1_hm_fragment_free(frag);
  578. s->state = stn;
  579. *ok = 1;
  580. return s->init_num;
  581. f_err:
  582. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  583. err:
  584. pitem_free(item);
  585. dtls1_hm_fragment_free(frag);
  586. *ok = 0;
  587. return -1;
  588. }
  589. /* for these 2 messages, we need to
  590. * ssl->enc_read_ctx re-init
  591. * ssl->s3->read_sequence zero
  592. * ssl->s3->read_mac_secret re-init
  593. * ssl->session->read_sym_enc assign
  594. * ssl->session->read_compression assign
  595. * ssl->session->read_hash assign */
  596. int dtls1_send_change_cipher_spec(SSL *s, int a, int b) {
  597. uint8_t *p;
  598. if (s->state == a) {
  599. p = (uint8_t *)s->init_buf->data;
  600. *p++ = SSL3_MT_CCS;
  601. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  602. s->init_num = DTLS1_CCS_HEADER_LENGTH;
  603. s->init_off = 0;
  604. dtls1_set_message_header(s, SSL3_MT_CCS, 0, s->d1->handshake_write_seq, 0,
  605. 0);
  606. /* buffer the message to handle re-xmits */
  607. dtls1_buffer_message(s, 1);
  608. s->state = b;
  609. }
  610. /* SSL3_ST_CW_CHANGE_B */
  611. return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC, dtls1_use_current_epoch);
  612. }
  613. int dtls1_read_failed(SSL *s, int code) {
  614. if (code > 0) {
  615. assert(0);
  616. return 1;
  617. }
  618. if (!dtls1_is_timer_expired(s)) {
  619. /* not a timeout, none of our business, let higher layers handle this. In
  620. * fact, it's probably an error */
  621. return code;
  622. }
  623. if (!SSL_in_init(s)) {
  624. /* done, no need to send a retransmit */
  625. BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
  626. return code;
  627. }
  628. return DTLSv1_handle_timeout(s);
  629. }
  630. int dtls1_get_queue_priority(unsigned short seq, int is_ccs) {
  631. /* The index of the retransmission queue actually is the message sequence
  632. * number, since the queue only contains messages of a single handshake.
  633. * However, the ChangeCipherSpec has no message sequence number and so using
  634. * only the sequence will result in the CCS and Finished having the same
  635. * index. To prevent this, the sequence number is multiplied by 2. In case of
  636. * a CCS 1 is subtracted. This does not only differ CSS and Finished, it also
  637. * maintains the order of the index (important for priority queues) and fits
  638. * in the unsigned short variable. */
  639. return seq * 2 - is_ccs;
  640. }
  641. static int dtls1_retransmit_message(SSL *s, hm_fragment *frag) {
  642. int ret;
  643. /* XDTLS: for now assuming that read/writes are blocking */
  644. unsigned long header_length;
  645. /* assert(s->init_num == 0);
  646. assert(s->init_off == 0); */
  647. if (frag->msg_header.is_ccs) {
  648. header_length = DTLS1_CCS_HEADER_LENGTH;
  649. } else {
  650. header_length = DTLS1_HM_HEADER_LENGTH;
  651. }
  652. memcpy(s->init_buf->data, frag->fragment,
  653. frag->msg_header.msg_len + header_length);
  654. s->init_num = frag->msg_header.msg_len + header_length;
  655. dtls1_set_message_header(s, frag->msg_header.type,
  656. frag->msg_header.msg_len, frag->msg_header.seq,
  657. 0, frag->msg_header.frag_len);
  658. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  659. * (negotiated cipher) exist. */
  660. assert(s->d1->w_epoch == 0 || s->d1->w_epoch == 1);
  661. assert(frag->msg_header.epoch <= s->d1->w_epoch);
  662. enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
  663. if (s->d1->w_epoch == 1 && frag->msg_header.epoch == 0) {
  664. use_epoch = dtls1_use_previous_epoch;
  665. }
  666. ret = dtls1_do_write(s, frag->msg_header.is_ccs ? SSL3_RT_CHANGE_CIPHER_SPEC
  667. : SSL3_RT_HANDSHAKE,
  668. use_epoch);
  669. (void)BIO_flush(SSL_get_wbio(s));
  670. return ret;
  671. }
  672. int dtls1_retransmit_buffered_messages(SSL *s) {
  673. pqueue sent = s->d1->sent_messages;
  674. piterator iter = pqueue_iterator(sent);
  675. pitem *item;
  676. for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
  677. hm_fragment *frag = (hm_fragment *)item->data;
  678. if (dtls1_retransmit_message(s, frag) <= 0) {
  679. return -1;
  680. }
  681. }
  682. return 1;
  683. }
  684. int dtls1_buffer_message(SSL *s, int is_ccs) {
  685. pitem *item;
  686. hm_fragment *frag;
  687. uint8_t seq64be[8];
  688. /* this function is called immediately after a message has
  689. * been serialized */
  690. assert(s->init_off == 0);
  691. frag = dtls1_hm_fragment_new(s->init_num, 0);
  692. if (!frag) {
  693. return 0;
  694. }
  695. memcpy(frag->fragment, s->init_buf->data, s->init_num);
  696. if (is_ccs) {
  697. assert(s->d1->w_msg_hdr.msg_len + DTLS1_CCS_HEADER_LENGTH ==
  698. (unsigned int)s->init_num);
  699. } else {
  700. assert(s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH ==
  701. (unsigned int)s->init_num);
  702. }
  703. frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
  704. frag->msg_header.seq = s->d1->w_msg_hdr.seq;
  705. frag->msg_header.type = s->d1->w_msg_hdr.type;
  706. frag->msg_header.frag_off = 0;
  707. frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
  708. frag->msg_header.is_ccs = is_ccs;
  709. frag->msg_header.epoch = s->d1->w_epoch;
  710. memset(seq64be, 0, sizeof(seq64be));
  711. seq64be[6] = (uint8_t)(
  712. dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs) >>
  713. 8);
  714. seq64be[7] = (uint8_t)(
  715. dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs));
  716. item = pitem_new(seq64be, frag);
  717. if (item == NULL) {
  718. dtls1_hm_fragment_free(frag);
  719. return 0;
  720. }
  721. pqueue_insert(s->d1->sent_messages, item);
  722. return 1;
  723. }
  724. /* call this function when the buffered messages are no longer needed */
  725. void dtls1_clear_record_buffer(SSL *s) {
  726. pitem *item;
  727. for (item = pqueue_pop(s->d1->sent_messages); item != NULL;
  728. item = pqueue_pop(s->d1->sent_messages)) {
  729. dtls1_hm_fragment_free((hm_fragment *)item->data);
  730. pitem_free(item);
  731. }
  732. }
  733. /* don't actually do the writing, wait till the MTU has been retrieved */
  734. void dtls1_set_message_header(SSL *s, uint8_t mt, unsigned long len,
  735. unsigned short seq_num, unsigned long frag_off,
  736. unsigned long frag_len) {
  737. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  738. msg_hdr->type = mt;
  739. msg_hdr->msg_len = len;
  740. msg_hdr->seq = seq_num;
  741. msg_hdr->frag_off = frag_off;
  742. msg_hdr->frag_len = frag_len;
  743. }
  744. static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  745. unsigned long frag_len) {
  746. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  747. msg_hdr->frag_off = frag_off;
  748. msg_hdr->frag_len = frag_len;
  749. }
  750. static uint8_t *dtls1_write_message_header(SSL *s, uint8_t *p) {
  751. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  752. *p++ = msg_hdr->type;
  753. l2n3(msg_hdr->msg_len, p);
  754. s2n(msg_hdr->seq, p);
  755. l2n3(msg_hdr->frag_off, p);
  756. l2n3(msg_hdr->frag_len, p);
  757. return p;
  758. }
  759. unsigned int dtls1_min_mtu(void) {
  760. return kMinMTU;
  761. }
  762. void dtls1_get_message_header(uint8_t *data,
  763. struct hm_header_st *msg_hdr) {
  764. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  765. msg_hdr->type = *(data++);
  766. n2l3(data, msg_hdr->msg_len);
  767. n2s(data, msg_hdr->seq);
  768. n2l3(data, msg_hdr->frag_off);
  769. n2l3(data, msg_hdr->frag_len);
  770. }