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.
 
 
 
 
 
 

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