Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

926 Zeilen
31 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) {
  238. int ret;
  239. int curr_mtu;
  240. unsigned int len, frag_off;
  241. size_t max_overhead = 0;
  242. /* AHA! Figure out the MTU, and stick to the right size */
  243. if (s->d1->mtu < dtls1_min_mtu() &&
  244. !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
  245. long mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  246. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  247. s->d1->mtu = (unsigned)mtu;
  248. } else {
  249. s->d1->mtu = kDefaultMTU;
  250. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, s->d1->mtu, NULL);
  251. }
  252. }
  253. /* should have something reasonable now */
  254. assert(s->d1->mtu >= dtls1_min_mtu());
  255. if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {
  256. assert(s->init_num ==
  257. (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
  258. }
  259. /* Determine the maximum overhead of the current cipher. */
  260. if (s->aead_write_ctx != NULL) {
  261. max_overhead = EVP_AEAD_max_overhead(s->aead_write_ctx->ctx.aead);
  262. if (s->aead_write_ctx->variable_nonce_included_in_record) {
  263. max_overhead += s->aead_write_ctx->variable_nonce_len;
  264. }
  265. }
  266. frag_off = 0;
  267. while (s->init_num) {
  268. /* Account for data in the buffering BIO; multiple records may be packed
  269. * into a single packet during the handshake.
  270. *
  271. * TODO(davidben): This is buggy; if the MTU is larger than the buffer size,
  272. * the large record will be split across two packets. Moreover, in that
  273. * case, the |dtls1_write_bytes| call may not return synchronously. This
  274. * will break on retry as the |s->init_off| and |s->init_num| adjustment
  275. * will run a second time. */
  276. curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
  277. DTLS1_RT_HEADER_LENGTH - max_overhead;
  278. if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
  279. /* Flush the buffer and continue with a fresh packet.
  280. *
  281. * TODO(davidben): If |BIO_flush| is not synchronous and requires multiple
  282. * calls to |dtls1_do_write|, |frag_off| will be wrong. */
  283. ret = BIO_flush(SSL_get_wbio(s));
  284. if (ret <= 0) {
  285. return ret;
  286. }
  287. assert(BIO_wpending(SSL_get_wbio(s)) == 0);
  288. curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH - max_overhead;
  289. }
  290. /* XDTLS: this function is too long. split out the CCS part */
  291. if (type == SSL3_RT_HANDSHAKE) {
  292. /* If this isn't the first fragment, reserve space to prepend a new
  293. * fragment header. This will override the body of a previous fragment. */
  294. if (s->init_off != 0) {
  295. assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
  296. s->init_off -= DTLS1_HM_HEADER_LENGTH;
  297. s->init_num += DTLS1_HM_HEADER_LENGTH;
  298. }
  299. if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
  300. /* To make forward progress, the MTU must, at minimum, fit the handshake
  301. * header and one byte of handshake body. */
  302. OPENSSL_PUT_ERROR(SSL, dtls1_do_write, SSL_R_MTU_TOO_SMALL);
  303. return -1;
  304. }
  305. if (s->init_num > curr_mtu) {
  306. len = curr_mtu;
  307. } else {
  308. len = s->init_num;
  309. }
  310. assert(len >= DTLS1_HM_HEADER_LENGTH);
  311. dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH);
  312. dtls1_write_message_header(
  313. s, (uint8_t *)&s->init_buf->data[s->init_off]);
  314. } else {
  315. assert(type == SSL3_RT_CHANGE_CIPHER_SPEC);
  316. /* ChangeCipherSpec cannot be fragmented. */
  317. if (s->init_num > curr_mtu) {
  318. OPENSSL_PUT_ERROR(SSL, dtls1_do_write, SSL_R_MTU_TOO_SMALL);
  319. return -1;
  320. }
  321. len = s->init_num;
  322. }
  323. ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len);
  324. if (ret < 0) {
  325. return -1;
  326. }
  327. /* bad if this assert fails, only part of the handshake message got sent.
  328. * But why would this happen? */
  329. assert(len == (unsigned int)ret);
  330. if (ret == s->init_num) {
  331. if (s->msg_callback) {
  332. s->msg_callback(1, s->version, type, s->init_buf->data,
  333. (size_t)(s->init_off + s->init_num), s,
  334. s->msg_callback_arg);
  335. }
  336. s->init_off = 0; /* done writing this message */
  337. s->init_num = 0;
  338. return 1;
  339. }
  340. s->init_off += ret;
  341. s->init_num -= ret;
  342. frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
  343. }
  344. return 0;
  345. }
  346. /* dtls1_is_next_message_complete returns one if the next handshake message is
  347. * complete and zero otherwise. */
  348. static int dtls1_is_next_message_complete(SSL *s) {
  349. pitem *item = pqueue_peek(s->d1->buffered_messages);
  350. if (item == NULL) {
  351. return 0;
  352. }
  353. hm_fragment *frag = (hm_fragment *)item->data;
  354. assert(s->d1->handshake_read_seq <= frag->msg_header.seq);
  355. return s->d1->handshake_read_seq == frag->msg_header.seq &&
  356. frag->reassembly == NULL;
  357. }
  358. /* dtls1_discard_fragment_body discards a handshake fragment body of length
  359. * |frag_len|. It returns one on success and zero on error.
  360. *
  361. * TODO(davidben): This function will go away when ssl_read_bytes is gone from
  362. * the DTLS side. */
  363. static int dtls1_discard_fragment_body(SSL *s, size_t frag_len) {
  364. uint8_t discard[256];
  365. while (frag_len > 0) {
  366. size_t chunk = frag_len < sizeof(discard) ? frag_len : sizeof(discard);
  367. int ret = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, discard, chunk,
  368. 0);
  369. if (ret != chunk) {
  370. return 0;
  371. }
  372. frag_len -= chunk;
  373. }
  374. return 1;
  375. }
  376. /* dtls1_get_buffered_message returns the buffered message corresponding to
  377. * |msg_hdr|. If none exists, it creates a new one and inserts it in the
  378. * queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
  379. * returns NULL on failure. The caller does not take ownership of the result. */
  380. static hm_fragment *dtls1_get_buffered_message(
  381. SSL *s, const struct hm_header_st *msg_hdr) {
  382. uint8_t seq64be[8];
  383. memset(seq64be, 0, sizeof(seq64be));
  384. seq64be[6] = (uint8_t)(msg_hdr->seq >> 8);
  385. seq64be[7] = (uint8_t)msg_hdr->seq;
  386. pitem *item = pqueue_find(s->d1->buffered_messages, seq64be);
  387. hm_fragment *frag;
  388. if (item == NULL) {
  389. /* This is the first fragment from this message. */
  390. frag = dtls1_hm_fragment_new(msg_hdr->msg_len,
  391. 1 /* reassembly buffer needed */);
  392. if (frag == NULL) {
  393. return NULL;
  394. }
  395. memcpy(&frag->msg_header, msg_hdr, sizeof(*msg_hdr));
  396. item = pitem_new(seq64be, frag);
  397. if (item == NULL) {
  398. dtls1_hm_fragment_free(frag);
  399. return NULL;
  400. }
  401. item = pqueue_insert(s->d1->buffered_messages, item);
  402. /* |pqueue_insert| fails iff a duplicate item is inserted, but |item| cannot
  403. * be a duplicate. */
  404. assert(item != NULL);
  405. } else {
  406. frag = item->data;
  407. assert(frag->msg_header.seq == msg_hdr->seq);
  408. if (frag->msg_header.type != msg_hdr->type ||
  409. frag->msg_header.msg_len != msg_hdr->msg_len) {
  410. /* The new fragment must be compatible with the previous fragments from
  411. * this message. */
  412. OPENSSL_PUT_ERROR(SSL, dtls1_get_buffered_message,
  413. SSL_R_FRAGMENT_MISMATCH);
  414. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  415. return NULL;
  416. }
  417. }
  418. return frag;
  419. }
  420. /* dtls1_max_handshake_message_len returns the maximum number of bytes
  421. * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but may
  422. * be greater if the maximum certificate list size requires it. */
  423. static size_t dtls1_max_handshake_message_len(const SSL *s) {
  424. size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
  425. if (max_len < s->max_cert_list) {
  426. return s->max_cert_list;
  427. }
  428. return max_len;
  429. }
  430. /* dtls1_process_fragment reads a handshake fragment and processes it. It
  431. * returns one if a fragment was successfully processed and 0 or -1 on error. */
  432. static int dtls1_process_fragment(SSL *s) {
  433. /* Read handshake message header.
  434. *
  435. * TODO(davidben): ssl_read_bytes allows splitting the fragment header and
  436. * body across two records. Change this interface to consume the fragment in
  437. * one pass. */
  438. uint8_t header[DTLS1_HM_HEADER_LENGTH];
  439. int ret = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, header,
  440. DTLS1_HM_HEADER_LENGTH, 0);
  441. if (ret <= 0) {
  442. return ret;
  443. }
  444. if (ret != DTLS1_HM_HEADER_LENGTH) {
  445. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment, SSL_R_UNEXPECTED_MESSAGE);
  446. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  447. return -1;
  448. }
  449. /* Parse the message fragment header. */
  450. struct hm_header_st msg_hdr;
  451. dtls1_get_message_header(header, &msg_hdr);
  452. const size_t frag_off = msg_hdr.frag_off;
  453. const size_t frag_len = msg_hdr.frag_len;
  454. const size_t msg_len = msg_hdr.msg_len;
  455. if (frag_off > msg_len || frag_off + frag_len < frag_off ||
  456. frag_off + frag_len > msg_len ||
  457. msg_len > dtls1_max_handshake_message_len(s)) {
  458. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment,
  459. SSL_R_EXCESSIVE_MESSAGE_SIZE);
  460. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  461. return -1;
  462. }
  463. if (msg_hdr.seq < s->d1->handshake_read_seq ||
  464. msg_hdr.seq > (unsigned)s->d1->handshake_read_seq +
  465. kHandshakeBufferSize) {
  466. /* Ignore fragments from the past, or ones too far in the future. */
  467. if (!dtls1_discard_fragment_body(s, frag_len)) {
  468. return -1;
  469. }
  470. return 1;
  471. }
  472. hm_fragment *frag = dtls1_get_buffered_message(s, &msg_hdr);
  473. if (frag == NULL) {
  474. return -1;
  475. }
  476. assert(frag->msg_header.msg_len == msg_len);
  477. if (frag->reassembly == NULL) {
  478. /* The message is already assembled. */
  479. if (!dtls1_discard_fragment_body(s, frag_len)) {
  480. return -1;
  481. }
  482. return 1;
  483. }
  484. assert(msg_len > 0);
  485. /* Read the body of the fragment. */
  486. ret = s->method->ssl_read_bytes(
  487. s, SSL3_RT_HANDSHAKE, frag->fragment + frag_off, frag_len, 0);
  488. if (ret != frag_len) {
  489. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment, SSL_R_UNEXPECTED_MESSAGE);
  490. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  491. return -1;
  492. }
  493. dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
  494. return 1;
  495. }
  496. /* dtls1_get_message reads a handshake message of message type |msg_type| (any
  497. * if |msg_type| == -1), maximum acceptable body length |max|. Read an entire
  498. * handshake message. Handshake messages arrive in fragments. */
  499. long dtls1_get_message(SSL *s, int st1, int stn, int msg_type, long max,
  500. enum ssl_hash_message_t hash_message, int *ok) {
  501. pitem *item = NULL;
  502. hm_fragment *frag = NULL;
  503. int al;
  504. /* s3->tmp is used to store messages that are unexpected, caused
  505. * by the absence of an optional handshake message */
  506. if (s->s3->tmp.reuse_message) {
  507. /* A ssl_dont_hash_message call cannot be combined with reuse_message; the
  508. * ssl_dont_hash_message would have to have been applied to the previous
  509. * call. */
  510. assert(hash_message == ssl_hash_message);
  511. s->s3->tmp.reuse_message = 0;
  512. if (msg_type >= 0 && s->s3->tmp.message_type != msg_type) {
  513. al = SSL_AD_UNEXPECTED_MESSAGE;
  514. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_UNEXPECTED_MESSAGE);
  515. goto f_err;
  516. }
  517. *ok = 1;
  518. s->init_msg = (uint8_t *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  519. s->init_num = (int)s->s3->tmp.message_size;
  520. return s->init_num;
  521. }
  522. /* Process fragments until one is found. */
  523. while (!dtls1_is_next_message_complete(s)) {
  524. int ret = dtls1_process_fragment(s);
  525. if (ret <= 0) {
  526. *ok = 0;
  527. return ret;
  528. }
  529. }
  530. /* Read out the next complete handshake message. */
  531. item = pqueue_pop(s->d1->buffered_messages);
  532. assert(item != NULL);
  533. frag = (hm_fragment *)item->data;
  534. assert(s->d1->handshake_read_seq == frag->msg_header.seq);
  535. assert(frag->reassembly == NULL);
  536. if (frag->msg_header.msg_len > (size_t)max) {
  537. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  538. goto err;
  539. }
  540. CBB cbb;
  541. if (!BUF_MEM_grow(s->init_buf,
  542. (size_t)frag->msg_header.msg_len +
  543. DTLS1_HM_HEADER_LENGTH) ||
  544. !CBB_init_fixed(&cbb, (uint8_t *)s->init_buf->data, s->init_buf->max)) {
  545. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, ERR_R_MALLOC_FAILURE);
  546. goto err;
  547. }
  548. /* Reconstruct the assembled message. */
  549. size_t len;
  550. if (!CBB_add_u8(&cbb, frag->msg_header.type) ||
  551. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  552. !CBB_add_u16(&cbb, frag->msg_header.seq) ||
  553. !CBB_add_u24(&cbb, 0 /* frag_off */) ||
  554. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  555. !CBB_add_bytes(&cbb, frag->fragment, frag->msg_header.msg_len) ||
  556. !CBB_finish(&cbb, NULL, &len)) {
  557. CBB_cleanup(&cbb);
  558. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, ERR_R_INTERNAL_ERROR);
  559. goto err;
  560. }
  561. assert(len == (size_t)frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
  562. s->d1->handshake_read_seq++;
  563. /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
  564. * |ssl_get_message| API. */
  565. s->s3->tmp.message_type = frag->msg_header.type;
  566. s->s3->tmp.message_size = frag->msg_header.msg_len;
  567. s->init_msg = (uint8_t *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  568. s->init_num = frag->msg_header.msg_len;
  569. if (msg_type >= 0 && s->s3->tmp.message_type != msg_type) {
  570. al = SSL_AD_UNEXPECTED_MESSAGE;
  571. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_UNEXPECTED_MESSAGE);
  572. goto f_err;
  573. }
  574. if (hash_message == ssl_hash_message && !ssl3_hash_current_message(s)) {
  575. goto err;
  576. }
  577. if (s->msg_callback) {
  578. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
  579. s->init_num + DTLS1_HM_HEADER_LENGTH, s,
  580. s->msg_callback_arg);
  581. }
  582. pitem_free(item);
  583. dtls1_hm_fragment_free(frag);
  584. s->state = stn;
  585. *ok = 1;
  586. return s->init_num;
  587. f_err:
  588. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  589. err:
  590. pitem_free(item);
  591. dtls1_hm_fragment_free(frag);
  592. *ok = 0;
  593. return -1;
  594. }
  595. /* for these 2 messages, we need to
  596. * ssl->enc_read_ctx re-init
  597. * ssl->s3->read_sequence zero
  598. * ssl->s3->read_mac_secret re-init
  599. * ssl->session->read_sym_enc assign
  600. * ssl->session->read_compression assign
  601. * ssl->session->read_hash assign */
  602. int dtls1_send_change_cipher_spec(SSL *s, int a, int b) {
  603. uint8_t *p;
  604. if (s->state == a) {
  605. p = (uint8_t *)s->init_buf->data;
  606. *p++ = SSL3_MT_CCS;
  607. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  608. s->init_num = DTLS1_CCS_HEADER_LENGTH;
  609. s->init_off = 0;
  610. dtls1_set_message_header(s, SSL3_MT_CCS, 0, s->d1->handshake_write_seq, 0,
  611. 0);
  612. /* buffer the message to handle re-xmits */
  613. dtls1_buffer_message(s, 1);
  614. s->state = b;
  615. }
  616. /* SSL3_ST_CW_CHANGE_B */
  617. return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
  618. }
  619. int dtls1_read_failed(SSL *s, int code) {
  620. if (code > 0) {
  621. assert(0);
  622. return 1;
  623. }
  624. if (!dtls1_is_timer_expired(s)) {
  625. /* not a timeout, none of our business, let higher layers handle this. In
  626. * fact, it's probably an error */
  627. return code;
  628. }
  629. if (!SSL_in_init(s)) {
  630. /* done, no need to send a retransmit */
  631. BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
  632. return code;
  633. }
  634. return DTLSv1_handle_timeout(s);
  635. }
  636. int dtls1_get_queue_priority(unsigned short seq, int is_ccs) {
  637. /* The index of the retransmission queue actually is the message sequence
  638. * number, since the queue only contains messages of a single handshake.
  639. * However, the ChangeCipherSpec has no message sequence number and so using
  640. * only the sequence will result in the CCS and Finished having the same
  641. * index. To prevent this, the sequence number is multiplied by 2. In case of
  642. * a CCS 1 is subtracted. This does not only differ CSS and Finished, it also
  643. * maintains the order of the index (important for priority queues) and fits
  644. * in the unsigned short variable. */
  645. return seq * 2 - is_ccs;
  646. }
  647. static int dtls1_retransmit_message(SSL *s, hm_fragment *frag) {
  648. int ret;
  649. /* XDTLS: for now assuming that read/writes are blocking */
  650. unsigned long header_length;
  651. uint8_t save_write_sequence[8];
  652. /* assert(s->init_num == 0);
  653. assert(s->init_off == 0); */
  654. if (frag->msg_header.is_ccs) {
  655. header_length = DTLS1_CCS_HEADER_LENGTH;
  656. } else {
  657. header_length = DTLS1_HM_HEADER_LENGTH;
  658. }
  659. memcpy(s->init_buf->data, frag->fragment,
  660. frag->msg_header.msg_len + header_length);
  661. s->init_num = frag->msg_header.msg_len + header_length;
  662. dtls1_set_message_header(s, frag->msg_header.type,
  663. frag->msg_header.msg_len, frag->msg_header.seq,
  664. 0, frag->msg_header.frag_len);
  665. /* Save current state. */
  666. SSL_AEAD_CTX *aead_write_ctx = s->aead_write_ctx;
  667. uint16_t epoch = s->d1->w_epoch;
  668. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  669. * (negotiated cipher) exist. */
  670. assert(epoch == 0 || epoch == 1);
  671. assert(frag->msg_header.epoch <= epoch);
  672. const int fragment_from_previous_epoch = (epoch == 1 &&
  673. frag->msg_header.epoch == 0);
  674. if (fragment_from_previous_epoch) {
  675. /* Rewind to the previous epoch.
  676. *
  677. * TODO(davidben): Instead of swapping out connection-global state, this
  678. * logic should pass a "use previous epoch" parameter down to lower-level
  679. * functions. */
  680. s->d1->w_epoch = frag->msg_header.epoch;
  681. s->aead_write_ctx = NULL;
  682. memcpy(save_write_sequence, s->s3->write_sequence,
  683. sizeof(s->s3->write_sequence));
  684. memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
  685. sizeof(s->s3->write_sequence));
  686. } else {
  687. /* Otherwise the messages must be from the same epoch. */
  688. assert(frag->msg_header.epoch == epoch);
  689. }
  690. ret = dtls1_do_write(s, frag->msg_header.is_ccs ? SSL3_RT_CHANGE_CIPHER_SPEC
  691. : SSL3_RT_HANDSHAKE);
  692. if (fragment_from_previous_epoch) {
  693. /* Restore the current epoch. */
  694. s->aead_write_ctx = aead_write_ctx;
  695. s->d1->w_epoch = epoch;
  696. memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
  697. sizeof(s->s3->write_sequence));
  698. memcpy(s->s3->write_sequence, save_write_sequence,
  699. sizeof(s->s3->write_sequence));
  700. }
  701. (void)BIO_flush(SSL_get_wbio(s));
  702. return ret;
  703. }
  704. int dtls1_retransmit_buffered_messages(SSL *s) {
  705. pqueue sent = s->d1->sent_messages;
  706. piterator iter = pqueue_iterator(sent);
  707. pitem *item;
  708. for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
  709. hm_fragment *frag = (hm_fragment *)item->data;
  710. if (dtls1_retransmit_message(s, frag) <= 0) {
  711. return -1;
  712. }
  713. }
  714. return 1;
  715. }
  716. int dtls1_buffer_message(SSL *s, int is_ccs) {
  717. pitem *item;
  718. hm_fragment *frag;
  719. uint8_t seq64be[8];
  720. /* this function is called immediately after a message has
  721. * been serialized */
  722. assert(s->init_off == 0);
  723. frag = dtls1_hm_fragment_new(s->init_num, 0);
  724. if (!frag) {
  725. return 0;
  726. }
  727. memcpy(frag->fragment, s->init_buf->data, s->init_num);
  728. if (is_ccs) {
  729. assert(s->d1->w_msg_hdr.msg_len + DTLS1_CCS_HEADER_LENGTH ==
  730. (unsigned int)s->init_num);
  731. } else {
  732. assert(s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH ==
  733. (unsigned int)s->init_num);
  734. }
  735. frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
  736. frag->msg_header.seq = s->d1->w_msg_hdr.seq;
  737. frag->msg_header.type = s->d1->w_msg_hdr.type;
  738. frag->msg_header.frag_off = 0;
  739. frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
  740. frag->msg_header.is_ccs = is_ccs;
  741. frag->msg_header.epoch = s->d1->w_epoch;
  742. memset(seq64be, 0, sizeof(seq64be));
  743. seq64be[6] = (uint8_t)(
  744. dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs) >>
  745. 8);
  746. seq64be[7] = (uint8_t)(
  747. dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs));
  748. item = pitem_new(seq64be, frag);
  749. if (item == NULL) {
  750. dtls1_hm_fragment_free(frag);
  751. return 0;
  752. }
  753. pqueue_insert(s->d1->sent_messages, item);
  754. return 1;
  755. }
  756. /* call this function when the buffered messages are no longer needed */
  757. void dtls1_clear_record_buffer(SSL *s) {
  758. pitem *item;
  759. for (item = pqueue_pop(s->d1->sent_messages); item != NULL;
  760. item = pqueue_pop(s->d1->sent_messages)) {
  761. dtls1_hm_fragment_free((hm_fragment *)item->data);
  762. pitem_free(item);
  763. }
  764. }
  765. /* don't actually do the writing, wait till the MTU has been retrieved */
  766. void dtls1_set_message_header(SSL *s, uint8_t mt, unsigned long len,
  767. unsigned short seq_num, unsigned long frag_off,
  768. unsigned long frag_len) {
  769. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  770. msg_hdr->type = mt;
  771. msg_hdr->msg_len = len;
  772. msg_hdr->seq = seq_num;
  773. msg_hdr->frag_off = frag_off;
  774. msg_hdr->frag_len = frag_len;
  775. }
  776. static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  777. unsigned long frag_len) {
  778. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  779. msg_hdr->frag_off = frag_off;
  780. msg_hdr->frag_len = frag_len;
  781. }
  782. static uint8_t *dtls1_write_message_header(SSL *s, uint8_t *p) {
  783. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  784. *p++ = msg_hdr->type;
  785. l2n3(msg_hdr->msg_len, p);
  786. s2n(msg_hdr->seq, p);
  787. l2n3(msg_hdr->frag_off, p);
  788. l2n3(msg_hdr->frag_len, p);
  789. return p;
  790. }
  791. unsigned int dtls1_min_mtu(void) {
  792. return kMinMTU;
  793. }
  794. void dtls1_get_message_header(uint8_t *data,
  795. struct hm_header_st *msg_hdr) {
  796. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  797. msg_hdr->type = *(data++);
  798. n2l3(data, msg_hdr->msg_len);
  799. n2s(data, msg_hdr->seq);
  800. n2l3(data, msg_hdr->frag_off);
  801. n2l3(data, msg_hdr->frag_len);
  802. }
  803. int dtls1_shutdown(SSL *s) {
  804. int ret;
  805. ret = ssl3_shutdown(s);
  806. return ret;
  807. }