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.
 
 
 
 
 
 

852 line
29 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 <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/rand.h>
  122. #include <openssl/x509.h>
  123. #include "internal.h"
  124. /* TODO(davidben): 28 comes from the size of IP + UDP header. Is this reasonable
  125. * for these values? Notably, why is kMinMTU a function of the transport
  126. * protocol's overhead rather than, say, what's needed to hold a minimally-sized
  127. * handshake fragment plus protocol overhead. */
  128. /* kMinMTU is the minimum acceptable MTU value. */
  129. static const unsigned int kMinMTU = 256 - 28;
  130. /* kDefaultMTU is the default MTU value to use if neither the user nor
  131. * the underlying BIO supplies one. */
  132. static const unsigned int kDefaultMTU = 1500 - 28;
  133. /* kMaxHandshakeBuffer is the maximum number of handshake messages ahead of the
  134. * current one to buffer. */
  135. static const unsigned int kHandshakeBufferSize = 10;
  136. static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly) {
  137. hm_fragment *frag = OPENSSL_malloc(sizeof(hm_fragment));
  138. if (frag == NULL) {
  139. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  140. return NULL;
  141. }
  142. memset(frag, 0, sizeof(hm_fragment));
  143. /* If the handshake message is empty, |frag->fragment| and |frag->reassembly|
  144. * are NULL. */
  145. if (frag_len > 0) {
  146. frag->fragment = OPENSSL_malloc(frag_len);
  147. if (frag->fragment == NULL) {
  148. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  149. goto err;
  150. }
  151. if (reassembly) {
  152. /* Initialize reassembly bitmask. */
  153. if (frag_len + 7 < frag_len) {
  154. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  155. goto err;
  156. }
  157. size_t bitmask_len = (frag_len + 7) / 8;
  158. frag->reassembly = OPENSSL_malloc(bitmask_len);
  159. if (frag->reassembly == NULL) {
  160. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  161. goto err;
  162. }
  163. memset(frag->reassembly, 0, bitmask_len);
  164. }
  165. }
  166. return frag;
  167. err:
  168. dtls1_hm_fragment_free(frag);
  169. return NULL;
  170. }
  171. void dtls1_hm_fragment_free(hm_fragment *frag) {
  172. if (frag == NULL) {
  173. return;
  174. }
  175. OPENSSL_free(frag->fragment);
  176. OPENSSL_free(frag->reassembly);
  177. OPENSSL_free(frag);
  178. }
  179. #if !defined(inline)
  180. #define inline __inline
  181. #endif
  182. /* bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
  183. * exclusive, set. */
  184. static inline uint8_t bit_range(size_t start, size_t end) {
  185. return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
  186. }
  187. /* dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
  188. * as received in |frag|. If |frag| becomes complete, it clears
  189. * |frag->reassembly|. The range must be within the bounds of |frag|'s message
  190. * and |frag->reassembly| must not be NULL. */
  191. static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
  192. size_t end) {
  193. size_t i;
  194. size_t msg_len = frag->msg_header.msg_len;
  195. if (frag->reassembly == NULL || start > end || end > msg_len) {
  196. assert(0);
  197. return;
  198. }
  199. /* A zero-length message will never have a pending reassembly. */
  200. assert(msg_len > 0);
  201. if ((start >> 3) == (end >> 3)) {
  202. frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
  203. } else {
  204. frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
  205. for (i = (start >> 3) + 1; i < (end >> 3); i++) {
  206. frag->reassembly[i] = 0xff;
  207. }
  208. if ((end & 7) != 0) {
  209. frag->reassembly[end >> 3] |= bit_range(0, end & 7);
  210. }
  211. }
  212. /* Check if the fragment is complete. */
  213. for (i = 0; i < (msg_len >> 3); i++) {
  214. if (frag->reassembly[i] != 0xff) {
  215. return;
  216. }
  217. }
  218. if ((msg_len & 7) != 0 &&
  219. frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
  220. return;
  221. }
  222. OPENSSL_free(frag->reassembly);
  223. frag->reassembly = NULL;
  224. }
  225. static void dtls1_update_mtu(SSL *ssl) {
  226. /* TODO(davidben): What is this code doing and do we need it? */
  227. if (ssl->d1->mtu < dtls1_min_mtu() &&
  228. !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
  229. long mtu = BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  230. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  231. ssl->d1->mtu = (unsigned)mtu;
  232. } else {
  233. ssl->d1->mtu = kDefaultMTU;
  234. BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
  235. }
  236. }
  237. /* The MTU should be above the minimum now. */
  238. assert(ssl->d1->mtu >= dtls1_min_mtu());
  239. }
  240. /* dtls1_max_record_size returns the maximum record body length that may be
  241. * written without exceeding the MTU. It accounts for any buffering installed on
  242. * the write BIO. If no record may be written, it returns zero. */
  243. static size_t dtls1_max_record_size(SSL *ssl) {
  244. size_t ret = ssl->d1->mtu;
  245. size_t overhead = ssl_max_seal_overhead(ssl);
  246. if (ret <= overhead) {
  247. return 0;
  248. }
  249. ret -= overhead;
  250. size_t pending = BIO_wpending(ssl->wbio);
  251. if (ret <= pending) {
  252. return 0;
  253. }
  254. ret -= pending;
  255. return ret;
  256. }
  257. static int dtls1_write_change_cipher_spec(SSL *ssl,
  258. enum dtls1_use_epoch_t use_epoch) {
  259. dtls1_update_mtu(ssl);
  260. /* During the handshake, wbio is buffered to pack messages together. Flush the
  261. * buffer if the ChangeCipherSpec would not fit in a packet. */
  262. if (dtls1_max_record_size(ssl) == 0) {
  263. int ret = BIO_flush(ssl->wbio);
  264. if (ret <= 0) {
  265. ssl->rwstate = SSL_WRITING;
  266. return ret;
  267. }
  268. }
  269. static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
  270. int ret =
  271. dtls1_write_record(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  272. sizeof(kChangeCipherSpec), use_epoch);
  273. if (ret <= 0) {
  274. return ret;
  275. }
  276. ssl_do_msg_callback(ssl, 1 /* write */, ssl->version,
  277. SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  278. sizeof(kChangeCipherSpec));
  279. return 1;
  280. }
  281. int dtls1_do_handshake_write(SSL *ssl, enum dtls1_use_epoch_t use_epoch) {
  282. dtls1_update_mtu(ssl);
  283. int ret = -1;
  284. CBB cbb;
  285. CBB_zero(&cbb);
  286. /* Allocate a temporary buffer to hold the message fragments to avoid
  287. * clobbering the message. */
  288. uint8_t *buf = OPENSSL_malloc(ssl->d1->mtu);
  289. if (buf == NULL) {
  290. goto err;
  291. }
  292. /* Consume the message header. Fragments will have different headers
  293. * prepended. */
  294. if (ssl->init_off == 0) {
  295. ssl->init_off += DTLS1_HM_HEADER_LENGTH;
  296. ssl->init_num -= DTLS1_HM_HEADER_LENGTH;
  297. }
  298. assert(ssl->init_off >= DTLS1_HM_HEADER_LENGTH);
  299. do {
  300. /* During the handshake, wbio is buffered to pack messages together. Flush
  301. * the buffer if there isn't enough room to make progress. */
  302. if (dtls1_max_record_size(ssl) < DTLS1_HM_HEADER_LENGTH + 1) {
  303. int flush_ret = BIO_flush(ssl->wbio);
  304. if (flush_ret <= 0) {
  305. ssl->rwstate = SSL_WRITING;
  306. ret = flush_ret;
  307. goto err;
  308. }
  309. assert(BIO_wpending(ssl->wbio) == 0);
  310. }
  311. size_t todo = dtls1_max_record_size(ssl);
  312. if (todo < DTLS1_HM_HEADER_LENGTH + 1) {
  313. /* To make forward progress, the MTU must, at minimum, fit the handshake
  314. * header and one byte of handshake body. */
  315. OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
  316. goto err;
  317. }
  318. todo -= DTLS1_HM_HEADER_LENGTH;
  319. if (todo > (size_t)ssl->init_num) {
  320. todo = ssl->init_num;
  321. }
  322. if (todo >= (1u << 24)) {
  323. todo = (1u << 24) - 1;
  324. }
  325. size_t len;
  326. if (!CBB_init_fixed(&cbb, buf, ssl->d1->mtu) ||
  327. !CBB_add_u8(&cbb, ssl->d1->w_msg_hdr.type) ||
  328. !CBB_add_u24(&cbb, ssl->d1->w_msg_hdr.msg_len) ||
  329. !CBB_add_u16(&cbb, ssl->d1->w_msg_hdr.seq) ||
  330. !CBB_add_u24(&cbb, ssl->init_off - DTLS1_HM_HEADER_LENGTH) ||
  331. !CBB_add_u24(&cbb, todo) ||
  332. !CBB_add_bytes(
  333. &cbb, (const uint8_t *)ssl->init_buf->data + ssl->init_off, todo) ||
  334. !CBB_finish(&cbb, NULL, &len)) {
  335. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  336. goto err;
  337. }
  338. int write_ret =
  339. dtls1_write_record(ssl, SSL3_RT_HANDSHAKE, buf, len, use_epoch);
  340. if (write_ret <= 0) {
  341. ret = write_ret;
  342. goto err;
  343. }
  344. ssl->init_off += todo;
  345. ssl->init_num -= todo;
  346. } while (ssl->init_num > 0);
  347. ssl_do_msg_callback(ssl, 1 /* write */, ssl->version, SSL3_RT_HANDSHAKE,
  348. ssl->init_buf->data,
  349. (size_t)(ssl->init_off + ssl->init_num));
  350. ssl->init_off = 0;
  351. ssl->init_num = 0;
  352. ret = 1;
  353. err:
  354. CBB_cleanup(&cbb);
  355. OPENSSL_free(buf);
  356. return ret;
  357. }
  358. /* dtls1_is_next_message_complete returns one if the next handshake message is
  359. * complete and zero otherwise. */
  360. static int dtls1_is_next_message_complete(SSL *ssl) {
  361. pitem *item = pqueue_peek(ssl->d1->buffered_messages);
  362. if (item == NULL) {
  363. return 0;
  364. }
  365. hm_fragment *frag = (hm_fragment *)item->data;
  366. assert(ssl->d1->handshake_read_seq <= frag->msg_header.seq);
  367. return ssl->d1->handshake_read_seq == frag->msg_header.seq &&
  368. frag->reassembly == NULL;
  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 *ssl, 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(ssl->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(ssl->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, SSL_R_FRAGMENT_MISMATCH);
  407. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  408. return NULL;
  409. }
  410. }
  411. return frag;
  412. }
  413. /* dtls1_process_handshake_record reads a handshake record and processes it. It
  414. * returns one if the record was successfully processed and 0 or -1 on error. */
  415. static int dtls1_process_handshake_record(SSL *ssl) {
  416. SSL3_RECORD *rr = &ssl->s3->rrec;
  417. start:
  418. if (rr->length == 0) {
  419. int ret = dtls1_get_record(ssl);
  420. if (ret <= 0) {
  421. return ret;
  422. }
  423. }
  424. /* Cross-epoch records are discarded, but we may receive out-of-order
  425. * application data between ChangeCipherSpec and Finished or a ChangeCipherSpec
  426. * before the appropriate point in the handshake. Those must be silently
  427. * discarded.
  428. *
  429. * However, only allow the out-of-order records in the correct epoch.
  430. * Application data must come in the encrypted epoch, and ChangeCipherSpec in
  431. * the unencrypted epoch (we never renegotiate). Other cases fall through and
  432. * fail with a fatal error. */
  433. if ((rr->type == SSL3_RT_APPLICATION_DATA &&
  434. ssl->s3->aead_read_ctx != NULL) ||
  435. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC &&
  436. ssl->s3->aead_read_ctx == NULL)) {
  437. rr->length = 0;
  438. goto start;
  439. }
  440. if (rr->type != SSL3_RT_HANDSHAKE) {
  441. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  442. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  443. return -1;
  444. }
  445. CBS cbs;
  446. CBS_init(&cbs, rr->data, rr->length);
  447. while (CBS_len(&cbs) > 0) {
  448. /* Read a handshake fragment. */
  449. struct hm_header_st msg_hdr;
  450. CBS body;
  451. if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
  452. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
  453. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  454. return -1;
  455. }
  456. const size_t frag_off = msg_hdr.frag_off;
  457. const size_t frag_len = msg_hdr.frag_len;
  458. const size_t msg_len = msg_hdr.msg_len;
  459. if (frag_off > msg_len || frag_off + frag_len < frag_off ||
  460. frag_off + frag_len > msg_len ||
  461. msg_len > ssl_max_handshake_message_len(ssl)) {
  462. OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  463. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  464. return -1;
  465. }
  466. if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
  467. msg_hdr.seq >
  468. (unsigned)ssl->d1->handshake_read_seq + kHandshakeBufferSize) {
  469. /* Ignore fragments from the past, or ones too far in the future. */
  470. continue;
  471. }
  472. hm_fragment *frag = dtls1_get_buffered_message(ssl, &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. continue;
  480. }
  481. assert(msg_len > 0);
  482. /* Copy the body into the fragment. */
  483. memcpy(frag->fragment + frag_off, CBS_data(&body), CBS_len(&body));
  484. dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
  485. }
  486. rr->length = 0;
  487. ssl_read_buffer_discard(ssl);
  488. return 1;
  489. }
  490. /* dtls1_get_message reads a handshake message of message type |msg_type| (any
  491. * if |msg_type| == -1). Read an entire handshake message. Handshake messages
  492. * arrive in fragments. */
  493. long dtls1_get_message(SSL *ssl, int msg_type,
  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 (ssl->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. ssl->s3->tmp.reuse_message = 0;
  506. if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
  507. al = SSL_AD_UNEXPECTED_MESSAGE;
  508. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  509. goto f_err;
  510. }
  511. *ok = 1;
  512. assert(ssl->init_buf->length >= DTLS1_HM_HEADER_LENGTH);
  513. ssl->init_msg = (uint8_t *)ssl->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  514. ssl->init_num = (int)ssl->init_buf->length - DTLS1_HM_HEADER_LENGTH;
  515. return ssl->init_num;
  516. }
  517. /* Process handshake records until the next message is ready. */
  518. while (!dtls1_is_next_message_complete(ssl)) {
  519. int ret = dtls1_process_handshake_record(ssl);
  520. if (ret <= 0) {
  521. *ok = 0;
  522. return ret;
  523. }
  524. }
  525. /* Read out the next complete handshake message. */
  526. item = pqueue_pop(ssl->d1->buffered_messages);
  527. assert(item != NULL);
  528. frag = (hm_fragment *)item->data;
  529. assert(ssl->d1->handshake_read_seq == frag->msg_header.seq);
  530. assert(frag->reassembly == NULL);
  531. /* Reconstruct the assembled message. */
  532. CBB cbb;
  533. CBB_zero(&cbb);
  534. if (!BUF_MEM_reserve(ssl->init_buf, (size_t)frag->msg_header.msg_len +
  535. DTLS1_HM_HEADER_LENGTH) ||
  536. !CBB_init_fixed(&cbb, (uint8_t *)ssl->init_buf->data,
  537. ssl->init_buf->max) ||
  538. !CBB_add_u8(&cbb, frag->msg_header.type) ||
  539. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  540. !CBB_add_u16(&cbb, frag->msg_header.seq) ||
  541. !CBB_add_u24(&cbb, 0 /* frag_off */) ||
  542. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  543. !CBB_add_bytes(&cbb, frag->fragment, frag->msg_header.msg_len) ||
  544. !CBB_finish(&cbb, NULL, &ssl->init_buf->length)) {
  545. CBB_cleanup(&cbb);
  546. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  547. goto err;
  548. }
  549. assert(ssl->init_buf->length ==
  550. (size_t)frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
  551. ssl->d1->handshake_read_seq++;
  552. /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
  553. * |ssl_get_message| API. */
  554. ssl->s3->tmp.message_type = frag->msg_header.type;
  555. ssl->init_msg = (uint8_t *)ssl->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  556. ssl->init_num = frag->msg_header.msg_len;
  557. if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
  558. al = SSL_AD_UNEXPECTED_MESSAGE;
  559. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  560. goto f_err;
  561. }
  562. if (hash_message == ssl_hash_message && !ssl3_hash_current_message(ssl)) {
  563. goto err;
  564. }
  565. ssl_do_msg_callback(ssl, 0 /* read */, ssl->version, SSL3_RT_HANDSHAKE,
  566. ssl->init_buf->data,
  567. ssl->init_num + DTLS1_HM_HEADER_LENGTH);
  568. pitem_free(item);
  569. dtls1_hm_fragment_free(frag);
  570. *ok = 1;
  571. return ssl->init_num;
  572. f_err:
  573. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  574. err:
  575. pitem_free(item);
  576. dtls1_hm_fragment_free(frag);
  577. *ok = 0;
  578. return -1;
  579. }
  580. static uint16_t dtls1_get_queue_priority(uint16_t seq, int is_ccs) {
  581. assert(seq * 2 >= seq);
  582. /* The index of the retransmission queue actually is the message sequence
  583. * number, since the queue only contains messages of a single handshake.
  584. * However, the ChangeCipherSpec has no message sequence number and so using
  585. * only the sequence will result in the CCS and Finished having the same
  586. * index. To prevent this, the sequence number is multiplied by 2. In case of
  587. * a CCS 1 is subtracted. This does not only differ CSS and Finished, it also
  588. * maintains the order of the index (important for priority queues) and fits
  589. * in the unsigned short variable. */
  590. return seq * 2 - is_ccs;
  591. }
  592. static int dtls1_retransmit_message(SSL *ssl, hm_fragment *frag) {
  593. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  594. * (negotiated cipher) exist. */
  595. assert(ssl->d1->w_epoch == 0 || ssl->d1->w_epoch == 1);
  596. assert(frag->msg_header.epoch <= ssl->d1->w_epoch);
  597. enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
  598. if (ssl->d1->w_epoch == 1 && frag->msg_header.epoch == 0) {
  599. use_epoch = dtls1_use_previous_epoch;
  600. }
  601. /* TODO(davidben): This cannot handle non-blocking writes. */
  602. int ret;
  603. if (frag->msg_header.is_ccs) {
  604. ret = dtls1_write_change_cipher_spec(ssl, use_epoch);
  605. } else {
  606. /* Restore the message body.
  607. * TODO(davidben): Make this less stateful. */
  608. memcpy(ssl->init_buf->data, frag->fragment,
  609. frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
  610. ssl->init_num = frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH;
  611. dtls1_set_message_header(ssl, frag->msg_header.type,
  612. frag->msg_header.msg_len, frag->msg_header.seq,
  613. 0, frag->msg_header.frag_len);
  614. ret = dtls1_do_handshake_write(ssl, use_epoch);
  615. }
  616. return ret;
  617. }
  618. int dtls1_retransmit_buffered_messages(SSL *ssl) {
  619. /* Ensure we are packing handshake messages. */
  620. const int was_buffered = ssl_is_wbio_buffered(ssl);
  621. assert(was_buffered == SSL_in_init(ssl));
  622. if (!was_buffered && !ssl_init_wbio_buffer(ssl)) {
  623. return -1;
  624. }
  625. assert(ssl_is_wbio_buffered(ssl));
  626. int ret = -1;
  627. piterator iter = pqueue_iterator(ssl->d1->sent_messages);
  628. pitem *item;
  629. for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
  630. hm_fragment *frag = (hm_fragment *)item->data;
  631. if (dtls1_retransmit_message(ssl, frag) <= 0) {
  632. goto err;
  633. }
  634. }
  635. ret = BIO_flush(ssl->wbio);
  636. if (ret <= 0) {
  637. ssl->rwstate = SSL_WRITING;
  638. goto err;
  639. }
  640. err:
  641. if (!was_buffered) {
  642. ssl_free_wbio_buffer(ssl);
  643. }
  644. return ret;
  645. }
  646. /* dtls1_buffer_change_cipher_spec adds a ChangeCipherSpec to the current
  647. * handshake flight, ordered just before the handshake message numbered
  648. * |seq|. */
  649. static int dtls1_buffer_change_cipher_spec(SSL *ssl, uint16_t seq) {
  650. hm_fragment *frag = dtls1_hm_fragment_new(0 /* frag_len */,
  651. 0 /* no reassembly */);
  652. if (frag == NULL) {
  653. return 0;
  654. }
  655. frag->msg_header.is_ccs = 1;
  656. frag->msg_header.epoch = ssl->d1->w_epoch;
  657. uint16_t priority = dtls1_get_queue_priority(seq, 1 /* is_ccs */);
  658. uint8_t seq64be[8];
  659. memset(seq64be, 0, sizeof(seq64be));
  660. seq64be[6] = (uint8_t)(priority >> 8);
  661. seq64be[7] = (uint8_t)priority;
  662. pitem *item = pitem_new(seq64be, frag);
  663. if (item == NULL) {
  664. dtls1_hm_fragment_free(frag);
  665. return 0;
  666. }
  667. pqueue_insert(ssl->d1->sent_messages, item);
  668. return 1;
  669. }
  670. int dtls1_buffer_message(SSL *ssl) {
  671. /* this function is called immediately after a message has
  672. * been serialized */
  673. assert(ssl->init_off == 0);
  674. hm_fragment *frag = dtls1_hm_fragment_new(ssl->init_num, 0);
  675. if (!frag) {
  676. return 0;
  677. }
  678. memcpy(frag->fragment, ssl->init_buf->data, ssl->init_num);
  679. assert(ssl->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH ==
  680. (unsigned int)ssl->init_num);
  681. frag->msg_header.msg_len = ssl->d1->w_msg_hdr.msg_len;
  682. frag->msg_header.seq = ssl->d1->w_msg_hdr.seq;
  683. frag->msg_header.type = ssl->d1->w_msg_hdr.type;
  684. frag->msg_header.frag_off = 0;
  685. frag->msg_header.frag_len = ssl->d1->w_msg_hdr.msg_len;
  686. frag->msg_header.is_ccs = 0;
  687. frag->msg_header.epoch = ssl->d1->w_epoch;
  688. uint16_t priority = dtls1_get_queue_priority(frag->msg_header.seq,
  689. 0 /* handshake */);
  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_send_change_cipher_spec(SSL *ssl, int a, int b) {
  703. if (ssl->state == a) {
  704. /* Buffer the message to handle retransmits. */
  705. ssl->d1->handshake_write_seq = ssl->d1->next_handshake_write_seq;
  706. dtls1_buffer_change_cipher_spec(ssl, ssl->d1->handshake_write_seq);
  707. ssl->state = b;
  708. }
  709. return dtls1_write_change_cipher_spec(ssl, dtls1_use_current_epoch);
  710. }
  711. /* call this function when the buffered messages are no longer needed */
  712. void dtls1_clear_record_buffer(SSL *ssl) {
  713. pitem *item;
  714. for (item = pqueue_pop(ssl->d1->sent_messages); item != NULL;
  715. item = pqueue_pop(ssl->d1->sent_messages)) {
  716. dtls1_hm_fragment_free((hm_fragment *)item->data);
  717. pitem_free(item);
  718. }
  719. }
  720. /* don't actually do the writing, wait till the MTU has been retrieved */
  721. void dtls1_set_message_header(SSL *ssl, uint8_t mt, unsigned long len,
  722. unsigned short seq_num, unsigned long frag_off,
  723. unsigned long frag_len) {
  724. struct hm_header_st *msg_hdr = &ssl->d1->w_msg_hdr;
  725. msg_hdr->type = mt;
  726. msg_hdr->msg_len = len;
  727. msg_hdr->seq = seq_num;
  728. msg_hdr->frag_off = frag_off;
  729. msg_hdr->frag_len = frag_len;
  730. }
  731. unsigned int dtls1_min_mtu(void) {
  732. return kMinMTU;
  733. }
  734. int dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
  735. CBS *out_body) {
  736. memset(out_hdr, 0x00, sizeof(struct hm_header_st));
  737. if (!CBS_get_u8(cbs, &out_hdr->type) ||
  738. !CBS_get_u24(cbs, &out_hdr->msg_len) ||
  739. !CBS_get_u16(cbs, &out_hdr->seq) ||
  740. !CBS_get_u24(cbs, &out_hdr->frag_off) ||
  741. !CBS_get_u24(cbs, &out_hdr->frag_len) ||
  742. !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
  743. return 0;
  744. }
  745. return 1;
  746. }