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.
 
 
 
 
 
 

815 lines
28 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/type_check.h>
  123. #include "../crypto/internal.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. /* Receiving handshake messages. */
  135. static void dtls1_hm_fragment_free(hm_fragment *frag) {
  136. if (frag == NULL) {
  137. return;
  138. }
  139. OPENSSL_free(frag->data);
  140. OPENSSL_free(frag->reassembly);
  141. OPENSSL_free(frag);
  142. }
  143. static hm_fragment *dtls1_hm_fragment_new(const struct hm_header_st *msg_hdr) {
  144. hm_fragment *frag = OPENSSL_malloc(sizeof(hm_fragment));
  145. if (frag == NULL) {
  146. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  147. return NULL;
  148. }
  149. OPENSSL_memset(frag, 0, sizeof(hm_fragment));
  150. frag->type = msg_hdr->type;
  151. frag->seq = msg_hdr->seq;
  152. frag->msg_len = msg_hdr->msg_len;
  153. /* Allocate space for the reassembled message and fill in the header. */
  154. frag->data = OPENSSL_malloc(DTLS1_HM_HEADER_LENGTH + msg_hdr->msg_len);
  155. if (frag->data == NULL) {
  156. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  157. goto err;
  158. }
  159. CBB cbb;
  160. if (!CBB_init_fixed(&cbb, frag->data, DTLS1_HM_HEADER_LENGTH) ||
  161. !CBB_add_u8(&cbb, msg_hdr->type) ||
  162. !CBB_add_u24(&cbb, msg_hdr->msg_len) ||
  163. !CBB_add_u16(&cbb, msg_hdr->seq) ||
  164. !CBB_add_u24(&cbb, 0 /* frag_off */) ||
  165. !CBB_add_u24(&cbb, msg_hdr->msg_len) ||
  166. !CBB_finish(&cbb, NULL, NULL)) {
  167. CBB_cleanup(&cbb);
  168. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  169. goto err;
  170. }
  171. /* If the handshake message is empty, |frag->reassembly| is NULL. */
  172. if (msg_hdr->msg_len > 0) {
  173. /* Initialize reassembly bitmask. */
  174. if (msg_hdr->msg_len + 7 < msg_hdr->msg_len) {
  175. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  176. goto err;
  177. }
  178. size_t bitmask_len = (msg_hdr->msg_len + 7) / 8;
  179. frag->reassembly = OPENSSL_malloc(bitmask_len);
  180. if (frag->reassembly == NULL) {
  181. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  182. goto err;
  183. }
  184. OPENSSL_memset(frag->reassembly, 0, bitmask_len);
  185. }
  186. return frag;
  187. err:
  188. dtls1_hm_fragment_free(frag);
  189. return NULL;
  190. }
  191. /* bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
  192. * exclusive, set. */
  193. static uint8_t bit_range(size_t start, size_t end) {
  194. return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
  195. }
  196. /* dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
  197. * as received in |frag|. If |frag| becomes complete, it clears
  198. * |frag->reassembly|. The range must be within the bounds of |frag|'s message
  199. * and |frag->reassembly| must not be NULL. */
  200. static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
  201. size_t end) {
  202. size_t msg_len = frag->msg_len;
  203. if (frag->reassembly == NULL || start > end || end > msg_len) {
  204. assert(0);
  205. return;
  206. }
  207. /* A zero-length message will never have a pending reassembly. */
  208. assert(msg_len > 0);
  209. if ((start >> 3) == (end >> 3)) {
  210. frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
  211. } else {
  212. frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
  213. for (size_t i = (start >> 3) + 1; i < (end >> 3); i++) {
  214. frag->reassembly[i] = 0xff;
  215. }
  216. if ((end & 7) != 0) {
  217. frag->reassembly[end >> 3] |= bit_range(0, end & 7);
  218. }
  219. }
  220. /* Check if the fragment is complete. */
  221. for (size_t i = 0; i < (msg_len >> 3); i++) {
  222. if (frag->reassembly[i] != 0xff) {
  223. return;
  224. }
  225. }
  226. if ((msg_len & 7) != 0 &&
  227. frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
  228. return;
  229. }
  230. OPENSSL_free(frag->reassembly);
  231. frag->reassembly = NULL;
  232. }
  233. /* dtls1_is_current_message_complete returns one if the current handshake
  234. * message is complete and zero otherwise. */
  235. static int dtls1_is_current_message_complete(const SSL *ssl) {
  236. hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
  237. SSL_MAX_HANDSHAKE_FLIGHT];
  238. return frag != NULL && frag->reassembly == NULL;
  239. }
  240. /* dtls1_get_incoming_message returns the incoming message corresponding to
  241. * |msg_hdr|. If none exists, it creates a new one and inserts it in the
  242. * queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
  243. * returns NULL on failure. The caller does not take ownership of the result. */
  244. static hm_fragment *dtls1_get_incoming_message(
  245. SSL *ssl, const struct hm_header_st *msg_hdr) {
  246. if (msg_hdr->seq < ssl->d1->handshake_read_seq ||
  247. msg_hdr->seq - ssl->d1->handshake_read_seq >= SSL_MAX_HANDSHAKE_FLIGHT) {
  248. return NULL;
  249. }
  250. size_t idx = msg_hdr->seq % SSL_MAX_HANDSHAKE_FLIGHT;
  251. hm_fragment *frag = ssl->d1->incoming_messages[idx];
  252. if (frag != NULL) {
  253. assert(frag->seq == msg_hdr->seq);
  254. /* The new fragment must be compatible with the previous fragments from this
  255. * message. */
  256. if (frag->type != msg_hdr->type ||
  257. frag->msg_len != msg_hdr->msg_len) {
  258. OPENSSL_PUT_ERROR(SSL, SSL_R_FRAGMENT_MISMATCH);
  259. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  260. return NULL;
  261. }
  262. return frag;
  263. }
  264. /* This is the first fragment from this message. */
  265. frag = dtls1_hm_fragment_new(msg_hdr);
  266. if (frag == NULL) {
  267. return NULL;
  268. }
  269. ssl->d1->incoming_messages[idx] = frag;
  270. return frag;
  271. }
  272. /* dtls1_process_handshake_record reads a handshake record and processes it. It
  273. * returns one if the record was successfully processed and 0 or -1 on error. */
  274. static int dtls1_process_handshake_record(SSL *ssl) {
  275. SSL3_RECORD *rr = &ssl->s3->rrec;
  276. start:
  277. if (rr->length == 0) {
  278. int ret = dtls1_get_record(ssl);
  279. if (ret <= 0) {
  280. return ret;
  281. }
  282. }
  283. /* Cross-epoch records are discarded, but we may receive out-of-order
  284. * application data between ChangeCipherSpec and Finished or a
  285. * ChangeCipherSpec before the appropriate point in the handshake. Those must
  286. * be silently discarded.
  287. *
  288. * However, only allow the out-of-order records in the correct epoch.
  289. * Application data must come in the encrypted epoch, and ChangeCipherSpec in
  290. * the unencrypted epoch (we never renegotiate). Other cases fall through and
  291. * fail with a fatal error. */
  292. if ((rr->type == SSL3_RT_APPLICATION_DATA &&
  293. ssl->s3->aead_read_ctx != NULL) ||
  294. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC &&
  295. ssl->s3->aead_read_ctx == NULL)) {
  296. rr->length = 0;
  297. goto start;
  298. }
  299. if (rr->type != SSL3_RT_HANDSHAKE) {
  300. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  301. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  302. return -1;
  303. }
  304. CBS cbs;
  305. CBS_init(&cbs, rr->data, rr->length);
  306. while (CBS_len(&cbs) > 0) {
  307. /* Read a handshake fragment. */
  308. struct hm_header_st msg_hdr;
  309. CBS body;
  310. if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
  311. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
  312. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  313. return -1;
  314. }
  315. const size_t frag_off = msg_hdr.frag_off;
  316. const size_t frag_len = msg_hdr.frag_len;
  317. const size_t msg_len = msg_hdr.msg_len;
  318. if (frag_off > msg_len || frag_off + frag_len < frag_off ||
  319. frag_off + frag_len > msg_len ||
  320. msg_len > ssl_max_handshake_message_len(ssl)) {
  321. OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  322. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  323. return -1;
  324. }
  325. /* The encrypted epoch in DTLS has only one handshake message. */
  326. if (ssl->d1->r_epoch == 1 && msg_hdr.seq != ssl->d1->handshake_read_seq) {
  327. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  328. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  329. return -1;
  330. }
  331. if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
  332. msg_hdr.seq >
  333. (unsigned)ssl->d1->handshake_read_seq + SSL_MAX_HANDSHAKE_FLIGHT) {
  334. /* Ignore fragments from the past, or ones too far in the future. */
  335. continue;
  336. }
  337. hm_fragment *frag = dtls1_get_incoming_message(ssl, &msg_hdr);
  338. if (frag == NULL) {
  339. return -1;
  340. }
  341. assert(frag->msg_len == msg_len);
  342. if (frag->reassembly == NULL) {
  343. /* The message is already assembled. */
  344. continue;
  345. }
  346. assert(msg_len > 0);
  347. /* Copy the body into the fragment. */
  348. OPENSSL_memcpy(frag->data + DTLS1_HM_HEADER_LENGTH + frag_off,
  349. CBS_data(&body), CBS_len(&body));
  350. dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
  351. }
  352. rr->length = 0;
  353. ssl_read_buffer_discard(ssl);
  354. return 1;
  355. }
  356. int dtls1_get_message(SSL *ssl) {
  357. if (ssl->s3->tmp.reuse_message) {
  358. /* There must be a current message. */
  359. assert(ssl->init_msg != NULL);
  360. ssl->s3->tmp.reuse_message = 0;
  361. } else {
  362. dtls1_release_current_message(ssl, 0 /* don't free buffer */);
  363. }
  364. /* Process handshake records until the current message is ready. */
  365. while (!dtls1_is_current_message_complete(ssl)) {
  366. int ret = dtls1_process_handshake_record(ssl);
  367. if (ret <= 0) {
  368. return ret;
  369. }
  370. }
  371. hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
  372. SSL_MAX_HANDSHAKE_FLIGHT];
  373. assert(frag != NULL);
  374. assert(frag->reassembly == NULL);
  375. assert(ssl->d1->handshake_read_seq == frag->seq);
  376. /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
  377. * |ssl_get_message| API. */
  378. ssl->s3->tmp.message_type = frag->type;
  379. ssl->init_msg = frag->data + DTLS1_HM_HEADER_LENGTH;
  380. ssl->init_num = frag->msg_len;
  381. ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HANDSHAKE, frag->data,
  382. ssl->init_num + DTLS1_HM_HEADER_LENGTH);
  383. return 1;
  384. }
  385. void dtls1_get_current_message(const SSL *ssl, CBS *out) {
  386. assert(dtls1_is_current_message_complete(ssl));
  387. hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
  388. SSL_MAX_HANDSHAKE_FLIGHT];
  389. CBS_init(out, frag->data, DTLS1_HM_HEADER_LENGTH + frag->msg_len);
  390. }
  391. void dtls1_release_current_message(SSL *ssl, int free_buffer) {
  392. if (ssl->init_msg == NULL) {
  393. return;
  394. }
  395. assert(dtls1_is_current_message_complete(ssl));
  396. size_t index = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  397. dtls1_hm_fragment_free(ssl->d1->incoming_messages[index]);
  398. ssl->d1->incoming_messages[index] = NULL;
  399. ssl->d1->handshake_read_seq++;
  400. ssl->init_msg = NULL;
  401. ssl->init_num = 0;
  402. }
  403. void dtls_clear_incoming_messages(SSL *ssl) {
  404. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  405. dtls1_hm_fragment_free(ssl->d1->incoming_messages[i]);
  406. ssl->d1->incoming_messages[i] = NULL;
  407. }
  408. }
  409. int dtls_has_incoming_messages(const SSL *ssl) {
  410. size_t current = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  411. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  412. /* Skip the current message. */
  413. if (ssl->init_msg != NULL && i == current) {
  414. assert(dtls1_is_current_message_complete(ssl));
  415. continue;
  416. }
  417. if (ssl->d1->incoming_messages[i] != NULL) {
  418. return 1;
  419. }
  420. }
  421. return 0;
  422. }
  423. int dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
  424. CBS *out_body) {
  425. OPENSSL_memset(out_hdr, 0x00, sizeof(struct hm_header_st));
  426. if (!CBS_get_u8(cbs, &out_hdr->type) ||
  427. !CBS_get_u24(cbs, &out_hdr->msg_len) ||
  428. !CBS_get_u16(cbs, &out_hdr->seq) ||
  429. !CBS_get_u24(cbs, &out_hdr->frag_off) ||
  430. !CBS_get_u24(cbs, &out_hdr->frag_len) ||
  431. !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
  432. return 0;
  433. }
  434. return 1;
  435. }
  436. /* Sending handshake messages. */
  437. void dtls_clear_outgoing_messages(SSL *ssl) {
  438. for (size_t i = 0; i < ssl->d1->outgoing_messages_len; i++) {
  439. OPENSSL_free(ssl->d1->outgoing_messages[i].data);
  440. ssl->d1->outgoing_messages[i].data = NULL;
  441. }
  442. ssl->d1->outgoing_messages_len = 0;
  443. ssl->d1->outgoing_written = 0;
  444. ssl->d1->outgoing_offset = 0;
  445. }
  446. int dtls1_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
  447. /* Pick a modest size hint to save most of the |realloc| calls. */
  448. if (!CBB_init(cbb, 64) ||
  449. !CBB_add_u8(cbb, type) ||
  450. !CBB_add_u24(cbb, 0 /* length (filled in later) */) ||
  451. !CBB_add_u16(cbb, ssl->d1->handshake_write_seq) ||
  452. !CBB_add_u24(cbb, 0 /* offset */) ||
  453. !CBB_add_u24_length_prefixed(cbb, body)) {
  454. return 0;
  455. }
  456. return 1;
  457. }
  458. int dtls1_finish_message(SSL *ssl, CBB *cbb, uint8_t **out_msg,
  459. size_t *out_len) {
  460. *out_msg = NULL;
  461. if (!CBB_finish(cbb, out_msg, out_len) ||
  462. *out_len < DTLS1_HM_HEADER_LENGTH) {
  463. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  464. OPENSSL_free(*out_msg);
  465. return 0;
  466. }
  467. /* Fix up the header. Copy the fragment length into the total message
  468. * length. */
  469. OPENSSL_memcpy(*out_msg + 1, *out_msg + DTLS1_HM_HEADER_LENGTH - 3, 3);
  470. return 1;
  471. }
  472. /* add_outgoing adds a new handshake message or ChangeCipherSpec to the current
  473. * outgoing flight. It returns one on success and zero on error. In both cases,
  474. * it takes ownership of |data| and releases it with |OPENSSL_free| when
  475. * done. */
  476. static int add_outgoing(SSL *ssl, int is_ccs, uint8_t *data, size_t len) {
  477. OPENSSL_COMPILE_ASSERT(SSL_MAX_HANDSHAKE_FLIGHT <
  478. (1 << 8 * sizeof(ssl->d1->outgoing_messages_len)),
  479. outgoing_messages_len_is_too_small);
  480. if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
  481. assert(0);
  482. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  483. OPENSSL_free(data);
  484. return 0;
  485. }
  486. if (!is_ccs) {
  487. /* TODO(svaldez): Move this up a layer to fix abstraction for SSL_TRANSCRIPT
  488. * on hs. */
  489. if (ssl->s3->hs != NULL &&
  490. !SSL_TRANSCRIPT_update(&ssl->s3->hs->transcript, data, len)) {
  491. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  492. OPENSSL_free(data);
  493. return 0;
  494. }
  495. ssl->d1->handshake_write_seq++;
  496. }
  497. DTLS_OUTGOING_MESSAGE *msg =
  498. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
  499. msg->data = data;
  500. msg->len = len;
  501. msg->epoch = ssl->d1->w_epoch;
  502. msg->is_ccs = is_ccs;
  503. ssl->d1->outgoing_messages_len++;
  504. return 1;
  505. }
  506. int dtls1_add_message(SSL *ssl, uint8_t *data, size_t len) {
  507. return add_outgoing(ssl, 0 /* handshake */, data, len);
  508. }
  509. int dtls1_add_change_cipher_spec(SSL *ssl) {
  510. return add_outgoing(ssl, 1 /* ChangeCipherSpec */, NULL, 0);
  511. }
  512. int dtls1_add_alert(SSL *ssl, uint8_t level, uint8_t desc) {
  513. /* The |add_alert| path is only used for warning alerts for now, which DTLS
  514. * never sends. This will be implemented later once closure alerts are
  515. * converted. */
  516. assert(0);
  517. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  518. return 0;
  519. }
  520. /* dtls1_update_mtu updates the current MTU from the BIO, ensuring it is above
  521. * the minimum. */
  522. static void dtls1_update_mtu(SSL *ssl) {
  523. /* TODO(davidben): No consumer implements |BIO_CTRL_DGRAM_SET_MTU| and the
  524. * only |BIO_CTRL_DGRAM_QUERY_MTU| implementation could use
  525. * |SSL_set_mtu|. Does this need to be so complex? */
  526. if (ssl->d1->mtu < dtls1_min_mtu() &&
  527. !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
  528. long mtu = BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  529. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  530. ssl->d1->mtu = (unsigned)mtu;
  531. } else {
  532. ssl->d1->mtu = kDefaultMTU;
  533. BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
  534. }
  535. }
  536. /* The MTU should be above the minimum now. */
  537. assert(ssl->d1->mtu >= dtls1_min_mtu());
  538. }
  539. enum seal_result_t {
  540. seal_error,
  541. seal_no_progress,
  542. seal_partial,
  543. seal_success,
  544. };
  545. /* seal_next_message seals |msg|, which must be the next message, to |out|. If
  546. * progress was made, it returns |seal_partial| or |seal_success| and sets
  547. * |*out_len| to the number of bytes written. */
  548. static enum seal_result_t seal_next_message(SSL *ssl, uint8_t *out,
  549. size_t *out_len, size_t max_out,
  550. const DTLS_OUTGOING_MESSAGE *msg) {
  551. assert(ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len);
  552. assert(msg == &ssl->d1->outgoing_messages[ssl->d1->outgoing_written]);
  553. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  554. * (negotiated cipher) exist. */
  555. assert(ssl->d1->w_epoch == 0 || ssl->d1->w_epoch == 1);
  556. assert(msg->epoch <= ssl->d1->w_epoch);
  557. enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
  558. if (ssl->d1->w_epoch == 1 && msg->epoch == 0) {
  559. use_epoch = dtls1_use_previous_epoch;
  560. }
  561. size_t overhead = dtls_max_seal_overhead(ssl, use_epoch);
  562. size_t prefix = dtls_seal_prefix_len(ssl, use_epoch);
  563. if (msg->is_ccs) {
  564. /* Check there is room for the ChangeCipherSpec. */
  565. static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
  566. if (max_out < sizeof(kChangeCipherSpec) + overhead) {
  567. return seal_no_progress;
  568. }
  569. if (!dtls_seal_record(ssl, out, out_len, max_out,
  570. SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  571. sizeof(kChangeCipherSpec), use_epoch)) {
  572. return seal_error;
  573. }
  574. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_CHANGE_CIPHER_SPEC,
  575. kChangeCipherSpec, sizeof(kChangeCipherSpec));
  576. return seal_success;
  577. }
  578. /* DTLS messages are serialized as a single fragment in |msg|. */
  579. CBS cbs, body;
  580. struct hm_header_st hdr;
  581. CBS_init(&cbs, msg->data, msg->len);
  582. if (!dtls1_parse_fragment(&cbs, &hdr, &body) ||
  583. hdr.frag_off != 0 ||
  584. hdr.frag_len != CBS_len(&body) ||
  585. hdr.msg_len != CBS_len(&body) ||
  586. !CBS_skip(&body, ssl->d1->outgoing_offset) ||
  587. CBS_len(&cbs) != 0) {
  588. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  589. return seal_error;
  590. }
  591. /* Determine how much progress can be made. */
  592. if (max_out < DTLS1_HM_HEADER_LENGTH + 1 + overhead || max_out < prefix) {
  593. return seal_no_progress;
  594. }
  595. size_t todo = CBS_len(&body);
  596. if (todo > max_out - DTLS1_HM_HEADER_LENGTH - overhead) {
  597. todo = max_out - DTLS1_HM_HEADER_LENGTH - overhead;
  598. }
  599. /* Assemble a fragment, to be sealed in-place. */
  600. CBB cbb;
  601. uint8_t *frag = out + prefix;
  602. size_t max_frag = max_out - prefix, frag_len;
  603. if (!CBB_init_fixed(&cbb, frag, max_frag) ||
  604. !CBB_add_u8(&cbb, hdr.type) ||
  605. !CBB_add_u24(&cbb, hdr.msg_len) ||
  606. !CBB_add_u16(&cbb, hdr.seq) ||
  607. !CBB_add_u24(&cbb, ssl->d1->outgoing_offset) ||
  608. !CBB_add_u24(&cbb, todo) ||
  609. !CBB_add_bytes(&cbb, CBS_data(&body), todo) ||
  610. !CBB_finish(&cbb, NULL, &frag_len)) {
  611. CBB_cleanup(&cbb);
  612. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  613. return seal_error;
  614. }
  615. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_HANDSHAKE, frag, frag_len);
  616. if (!dtls_seal_record(ssl, out, out_len, max_out, SSL3_RT_HANDSHAKE,
  617. out + prefix, frag_len, use_epoch)) {
  618. return seal_error;
  619. }
  620. if (todo == CBS_len(&body)) {
  621. /* The next message is complete. */
  622. ssl->d1->outgoing_offset = 0;
  623. return seal_success;
  624. }
  625. ssl->d1->outgoing_offset += todo;
  626. return seal_partial;
  627. }
  628. /* seal_next_packet writes as much of the next flight as possible to |out| and
  629. * advances |ssl->d1->outgoing_written| and |ssl->d1->outgoing_offset| as
  630. * appropriate. */
  631. static int seal_next_packet(SSL *ssl, uint8_t *out, size_t *out_len,
  632. size_t max_out) {
  633. int made_progress = 0;
  634. size_t total = 0;
  635. assert(ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len);
  636. for (; ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len;
  637. ssl->d1->outgoing_written++) {
  638. const DTLS_OUTGOING_MESSAGE *msg =
  639. &ssl->d1->outgoing_messages[ssl->d1->outgoing_written];
  640. size_t len;
  641. enum seal_result_t ret = seal_next_message(ssl, out, &len, max_out, msg);
  642. switch (ret) {
  643. case seal_error:
  644. return 0;
  645. case seal_no_progress:
  646. goto packet_full;
  647. case seal_partial:
  648. case seal_success:
  649. out += len;
  650. max_out -= len;
  651. total += len;
  652. made_progress = 1;
  653. if (ret == seal_partial) {
  654. goto packet_full;
  655. }
  656. break;
  657. }
  658. }
  659. packet_full:
  660. /* The MTU was too small to make any progress. */
  661. if (!made_progress) {
  662. OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
  663. return 0;
  664. }
  665. *out_len = total;
  666. return 1;
  667. }
  668. int dtls1_flush_flight(SSL *ssl) {
  669. dtls1_update_mtu(ssl);
  670. int ret = -1;
  671. uint8_t *packet = OPENSSL_malloc(ssl->d1->mtu);
  672. if (packet == NULL) {
  673. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  674. goto err;
  675. }
  676. while (ssl->d1->outgoing_written < ssl->d1->outgoing_messages_len) {
  677. uint8_t old_written = ssl->d1->outgoing_written;
  678. uint32_t old_offset = ssl->d1->outgoing_offset;
  679. size_t packet_len;
  680. if (!seal_next_packet(ssl, packet, &packet_len, ssl->d1->mtu)) {
  681. goto err;
  682. }
  683. int bio_ret = BIO_write(ssl->wbio, packet, packet_len);
  684. if (bio_ret <= 0) {
  685. /* Retry this packet the next time around. */
  686. ssl->d1->outgoing_written = old_written;
  687. ssl->d1->outgoing_offset = old_offset;
  688. ssl->rwstate = SSL_WRITING;
  689. ret = bio_ret;
  690. goto err;
  691. }
  692. }
  693. if (BIO_flush(ssl->wbio) <= 0) {
  694. ssl->rwstate = SSL_WRITING;
  695. goto err;
  696. }
  697. ret = 1;
  698. err:
  699. OPENSSL_free(packet);
  700. return ret;
  701. }
  702. int dtls1_retransmit_outgoing_messages(SSL *ssl) {
  703. /* Rewind to the start of the flight and write it again.
  704. *
  705. * TODO(davidben): This does not allow retransmits to be resumed on
  706. * non-blocking write. */
  707. ssl->d1->outgoing_written = 0;
  708. ssl->d1->outgoing_offset = 0;
  709. return dtls1_flush_flight(ssl);
  710. }
  711. unsigned int dtls1_min_mtu(void) {
  712. return kMinMTU;
  713. }