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.
 
 
 
 
 
 

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