Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

851 linhas
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/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. /* Receiving handshake messages. */
  134. static void dtls1_hm_fragment_free(hm_fragment *frag) {
  135. if (frag == NULL) {
  136. return;
  137. }
  138. OPENSSL_free(frag->data);
  139. OPENSSL_free(frag->reassembly);
  140. OPENSSL_free(frag);
  141. }
  142. static hm_fragment *dtls1_hm_fragment_new(const struct hm_header_st *msg_hdr) {
  143. hm_fragment *frag = OPENSSL_malloc(sizeof(hm_fragment));
  144. if (frag == NULL) {
  145. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  146. return NULL;
  147. }
  148. memset(frag, 0, sizeof(hm_fragment));
  149. frag->type = msg_hdr->type;
  150. frag->seq = msg_hdr->seq;
  151. frag->msg_len = msg_hdr->msg_len;
  152. /* Allocate space for the reassembled message and fill in the header. */
  153. frag->data = OPENSSL_malloc(DTLS1_HM_HEADER_LENGTH + msg_hdr->msg_len);
  154. if (frag->data == NULL) {
  155. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  156. goto err;
  157. }
  158. CBB cbb;
  159. if (!CBB_init_fixed(&cbb, frag->data, DTLS1_HM_HEADER_LENGTH) ||
  160. !CBB_add_u8(&cbb, msg_hdr->type) ||
  161. !CBB_add_u24(&cbb, msg_hdr->msg_len) ||
  162. !CBB_add_u16(&cbb, msg_hdr->seq) ||
  163. !CBB_add_u24(&cbb, 0 /* frag_off */) ||
  164. !CBB_add_u24(&cbb, msg_hdr->msg_len) ||
  165. !CBB_finish(&cbb, NULL, NULL)) {
  166. CBB_cleanup(&cbb);
  167. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  168. goto err;
  169. }
  170. /* If the handshake message is empty, |frag->reassembly| is NULL. */
  171. if (msg_hdr->msg_len > 0) {
  172. /* Initialize reassembly bitmask. */
  173. if (msg_hdr->msg_len + 7 < msg_hdr->msg_len) {
  174. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  175. goto err;
  176. }
  177. size_t bitmask_len = (msg_hdr->msg_len + 7) / 8;
  178. frag->reassembly = OPENSSL_malloc(bitmask_len);
  179. if (frag->reassembly == NULL) {
  180. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  181. goto err;
  182. }
  183. memset(frag->reassembly, 0, bitmask_len);
  184. }
  185. return frag;
  186. err:
  187. dtls1_hm_fragment_free(frag);
  188. return NULL;
  189. }
  190. /* bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
  191. * exclusive, set. */
  192. static uint8_t bit_range(size_t start, size_t end) {
  193. return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
  194. }
  195. /* dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
  196. * as received in |frag|. If |frag| becomes complete, it clears
  197. * |frag->reassembly|. The range must be within the bounds of |frag|'s message
  198. * and |frag->reassembly| must not be NULL. */
  199. static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
  200. size_t end) {
  201. size_t i;
  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 (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 (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 ChangeCipherSpec
  285. * before the appropriate point in the handshake. Those must be silently
  286. * 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. memcpy(frag->data + DTLS1_HM_HEADER_LENGTH + frag_off, CBS_data(&body),
  349. 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, int msg_type,
  357. enum ssl_hash_message_t hash_message) {
  358. if (ssl->s3->tmp.reuse_message) {
  359. /* A ssl_dont_hash_message call cannot be combined with reuse_message; the
  360. * ssl_dont_hash_message would have to have been applied to the previous
  361. * call. */
  362. assert(hash_message == ssl_hash_message);
  363. assert(ssl->init_msg != NULL);
  364. ssl->s3->tmp.reuse_message = 0;
  365. hash_message = ssl_dont_hash_message;
  366. } else {
  367. dtls1_release_current_message(ssl, 0 /* don't free buffer */);
  368. }
  369. /* Process handshake records until the current message is ready. */
  370. while (!dtls1_is_current_message_complete(ssl)) {
  371. int ret = dtls1_process_handshake_record(ssl);
  372. if (ret <= 0) {
  373. return ret;
  374. }
  375. }
  376. hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
  377. SSL_MAX_HANDSHAKE_FLIGHT];
  378. assert(frag != NULL);
  379. assert(frag->reassembly == NULL);
  380. assert(ssl->d1->handshake_read_seq == frag->seq);
  381. /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
  382. * |ssl_get_message| API. */
  383. ssl->s3->tmp.message_type = frag->type;
  384. ssl->init_msg = frag->data + DTLS1_HM_HEADER_LENGTH;
  385. ssl->init_num = frag->msg_len;
  386. if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
  387. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  388. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  389. return -1;
  390. }
  391. if (hash_message == ssl_hash_message && !dtls1_hash_current_message(ssl)) {
  392. return -1;
  393. }
  394. ssl_do_msg_callback(ssl, 0 /* read */, ssl->version, SSL3_RT_HANDSHAKE,
  395. frag->data, ssl->init_num + DTLS1_HM_HEADER_LENGTH);
  396. return 1;
  397. }
  398. int dtls1_hash_current_message(SSL *ssl) {
  399. assert(dtls1_is_current_message_complete(ssl));
  400. hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
  401. SSL_MAX_HANDSHAKE_FLIGHT];
  402. return ssl3_update_handshake_hash(ssl, frag->data,
  403. DTLS1_HM_HEADER_LENGTH + frag->msg_len);
  404. }
  405. void dtls1_release_current_message(SSL *ssl, int free_buffer) {
  406. if (ssl->init_msg == NULL) {
  407. return;
  408. }
  409. assert(dtls1_is_current_message_complete(ssl));
  410. size_t index = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  411. dtls1_hm_fragment_free(ssl->d1->incoming_messages[index]);
  412. ssl->d1->incoming_messages[index] = NULL;
  413. ssl->d1->handshake_read_seq++;
  414. ssl->init_msg = NULL;
  415. ssl->init_num = 0;
  416. }
  417. void dtls_clear_incoming_messages(SSL *ssl) {
  418. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  419. dtls1_hm_fragment_free(ssl->d1->incoming_messages[i]);
  420. ssl->d1->incoming_messages[i] = NULL;
  421. }
  422. }
  423. int dtls_has_incoming_messages(const SSL *ssl) {
  424. size_t current = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  425. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  426. /* Skip the current message. */
  427. if (ssl->init_msg != NULL && i == current) {
  428. assert(dtls1_is_current_message_complete(ssl));
  429. continue;
  430. }
  431. if (ssl->d1->incoming_messages[i] != NULL) {
  432. return 1;
  433. }
  434. }
  435. return 0;
  436. }
  437. int dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
  438. CBS *out_body) {
  439. memset(out_hdr, 0x00, sizeof(struct hm_header_st));
  440. if (!CBS_get_u8(cbs, &out_hdr->type) ||
  441. !CBS_get_u24(cbs, &out_hdr->msg_len) ||
  442. !CBS_get_u16(cbs, &out_hdr->seq) ||
  443. !CBS_get_u24(cbs, &out_hdr->frag_off) ||
  444. !CBS_get_u24(cbs, &out_hdr->frag_len) ||
  445. !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
  446. return 0;
  447. }
  448. return 1;
  449. }
  450. /* Sending handshake messages. */
  451. static void dtls1_update_mtu(SSL *ssl) {
  452. /* TODO(davidben): What is this code doing and do we need it? */
  453. if (ssl->d1->mtu < dtls1_min_mtu() &&
  454. !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
  455. long mtu = BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  456. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  457. ssl->d1->mtu = (unsigned)mtu;
  458. } else {
  459. ssl->d1->mtu = kDefaultMTU;
  460. BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
  461. }
  462. }
  463. /* The MTU should be above the minimum now. */
  464. assert(ssl->d1->mtu >= dtls1_min_mtu());
  465. }
  466. /* dtls1_max_record_size returns the maximum record body length that may be
  467. * written without exceeding the MTU. It accounts for any buffering installed on
  468. * the write BIO. If no record may be written, it returns zero. */
  469. static size_t dtls1_max_record_size(SSL *ssl) {
  470. size_t ret = ssl->d1->mtu;
  471. size_t overhead = ssl_max_seal_overhead(ssl);
  472. if (ret <= overhead) {
  473. return 0;
  474. }
  475. ret -= overhead;
  476. size_t pending = BIO_wpending(ssl->wbio);
  477. if (ret <= pending) {
  478. return 0;
  479. }
  480. ret -= pending;
  481. return ret;
  482. }
  483. static int dtls1_write_change_cipher_spec(SSL *ssl,
  484. enum dtls1_use_epoch_t use_epoch) {
  485. dtls1_update_mtu(ssl);
  486. /* During the handshake, wbio is buffered to pack messages together. Flush the
  487. * buffer if the ChangeCipherSpec would not fit in a packet. */
  488. if (dtls1_max_record_size(ssl) == 0) {
  489. int ret = BIO_flush(ssl->wbio);
  490. if (ret <= 0) {
  491. ssl->rwstate = SSL_WRITING;
  492. return ret;
  493. }
  494. }
  495. static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
  496. int ret =
  497. dtls1_write_record(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  498. sizeof(kChangeCipherSpec), use_epoch);
  499. if (ret <= 0) {
  500. return ret;
  501. }
  502. ssl_do_msg_callback(ssl, 1 /* write */, ssl->version,
  503. SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  504. sizeof(kChangeCipherSpec));
  505. return 1;
  506. }
  507. /* dtls1_do_handshake_write writes handshake message |in| using the given epoch,
  508. * starting |offset| bytes into the message body. It returns one on success. On
  509. * error, it returns <= 0 and sets |*out_offset| to the number of bytes of body
  510. * that were successfully written. This may be used to retry the write
  511. * later. |in| must be a reassembled handshake message with the full DTLS
  512. * handshake header. */
  513. static int dtls1_do_handshake_write(SSL *ssl, size_t *out_offset,
  514. const uint8_t *in, size_t offset,
  515. size_t len,
  516. enum dtls1_use_epoch_t use_epoch) {
  517. dtls1_update_mtu(ssl);
  518. int ret = -1;
  519. CBB cbb;
  520. CBB_zero(&cbb);
  521. /* Allocate a temporary buffer to hold the message fragments to avoid
  522. * clobbering the message. */
  523. uint8_t *buf = OPENSSL_malloc(ssl->d1->mtu);
  524. if (buf == NULL) {
  525. goto err;
  526. }
  527. /* Although it may be sent as multiple fragments, a DTLS message must be sent
  528. * serialized as a single fragment for purposes of |ssl_do_msg_callback| and
  529. * the handshake hash. */
  530. CBS cbs, body;
  531. struct hm_header_st hdr;
  532. CBS_init(&cbs, in, len);
  533. if (!dtls1_parse_fragment(&cbs, &hdr, &body) ||
  534. hdr.frag_off != 0 ||
  535. hdr.frag_len != CBS_len(&body) ||
  536. hdr.msg_len != CBS_len(&body) ||
  537. !CBS_skip(&body, offset) ||
  538. CBS_len(&cbs) != 0) {
  539. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  540. goto err;
  541. }
  542. do {
  543. /* During the handshake, wbio is buffered to pack messages together. Flush
  544. * the buffer if there isn't enough room to make progress. */
  545. if (dtls1_max_record_size(ssl) < DTLS1_HM_HEADER_LENGTH + 1) {
  546. int flush_ret = BIO_flush(ssl->wbio);
  547. if (flush_ret <= 0) {
  548. ssl->rwstate = SSL_WRITING;
  549. ret = flush_ret;
  550. goto err;
  551. }
  552. assert(BIO_wpending(ssl->wbio) == 0);
  553. }
  554. size_t todo = dtls1_max_record_size(ssl);
  555. if (todo < DTLS1_HM_HEADER_LENGTH + 1) {
  556. /* To make forward progress, the MTU must, at minimum, fit the handshake
  557. * header and one byte of handshake body. */
  558. OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
  559. goto err;
  560. }
  561. todo -= DTLS1_HM_HEADER_LENGTH;
  562. if (todo > CBS_len(&body)) {
  563. todo = CBS_len(&body);
  564. }
  565. if (todo >= (1u << 24)) {
  566. todo = (1u << 24) - 1;
  567. }
  568. size_t buf_len;
  569. if (!CBB_init_fixed(&cbb, buf, ssl->d1->mtu) ||
  570. !CBB_add_u8(&cbb, hdr.type) ||
  571. !CBB_add_u24(&cbb, hdr.msg_len) ||
  572. !CBB_add_u16(&cbb, hdr.seq) ||
  573. !CBB_add_u24(&cbb, offset) ||
  574. !CBB_add_u24(&cbb, todo) ||
  575. !CBB_add_bytes(&cbb, CBS_data(&body), todo) ||
  576. !CBB_finish(&cbb, NULL, &buf_len)) {
  577. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  578. goto err;
  579. }
  580. int write_ret =
  581. dtls1_write_record(ssl, SSL3_RT_HANDSHAKE, buf, buf_len, use_epoch);
  582. if (write_ret <= 0) {
  583. ret = write_ret;
  584. goto err;
  585. }
  586. if (!CBS_skip(&body, todo)) {
  587. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  588. goto err;
  589. }
  590. offset += todo;
  591. } while (CBS_len(&body) != 0);
  592. ssl_do_msg_callback(ssl, 1 /* write */, ssl->version, SSL3_RT_HANDSHAKE, in,
  593. len);
  594. ret = 1;
  595. err:
  596. *out_offset = offset;
  597. CBB_cleanup(&cbb);
  598. OPENSSL_free(buf);
  599. return ret;
  600. }
  601. void dtls_clear_outgoing_messages(SSL *ssl) {
  602. size_t i;
  603. for (i = 0; i < ssl->d1->outgoing_messages_len; i++) {
  604. OPENSSL_free(ssl->d1->outgoing_messages[i].data);
  605. ssl->d1->outgoing_messages[i].data = NULL;
  606. }
  607. ssl->d1->outgoing_messages_len = 0;
  608. }
  609. /* dtls1_add_change_cipher_spec adds a ChangeCipherSpec to the current
  610. * handshake flight. */
  611. static int dtls1_add_change_cipher_spec(SSL *ssl) {
  612. if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
  613. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  614. return 0;
  615. }
  616. DTLS_OUTGOING_MESSAGE *msg =
  617. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
  618. msg->data = NULL;
  619. msg->len = 0;
  620. msg->epoch = ssl->d1->w_epoch;
  621. msg->is_ccs = 1;
  622. ssl->d1->outgoing_messages_len++;
  623. return 1;
  624. }
  625. static int dtls1_add_message(SSL *ssl, uint8_t *data, size_t len) {
  626. if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
  627. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  628. OPENSSL_free(data);
  629. return 0;
  630. }
  631. DTLS_OUTGOING_MESSAGE *msg =
  632. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
  633. msg->data = data;
  634. msg->len = len;
  635. msg->epoch = ssl->d1->w_epoch;
  636. msg->is_ccs = 0;
  637. ssl->d1->outgoing_messages_len++;
  638. return 1;
  639. }
  640. int dtls1_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
  641. /* Pick a modest size hint to save most of the |realloc| calls. */
  642. if (!CBB_init(cbb, 64) ||
  643. !CBB_add_u8(cbb, type) ||
  644. !CBB_add_u24(cbb, 0 /* length (filled in later) */) ||
  645. !CBB_add_u16(cbb, ssl->d1->handshake_write_seq) ||
  646. !CBB_add_u24(cbb, 0 /* offset */) ||
  647. !CBB_add_u24_length_prefixed(cbb, body)) {
  648. return 0;
  649. }
  650. return 1;
  651. }
  652. int dtls1_finish_message(SSL *ssl, CBB *cbb) {
  653. uint8_t *msg = NULL;
  654. size_t len;
  655. if (!CBB_finish(cbb, &msg, &len) ||
  656. len > 0xffffffffu ||
  657. len < DTLS1_HM_HEADER_LENGTH) {
  658. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  659. OPENSSL_free(msg);
  660. return 0;
  661. }
  662. /* Fix up the header. Copy the fragment length into the total message
  663. * length. */
  664. memcpy(msg + 1, msg + DTLS1_HM_HEADER_LENGTH - 3, 3);
  665. ssl3_update_handshake_hash(ssl, msg, len);
  666. ssl->d1->handshake_write_seq++;
  667. ssl->init_off = 0;
  668. return dtls1_add_message(ssl, msg, len);
  669. }
  670. int dtls1_write_message(SSL *ssl) {
  671. if (ssl->d1->outgoing_messages_len == 0) {
  672. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  673. return -1;
  674. }
  675. const DTLS_OUTGOING_MESSAGE *msg =
  676. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len - 1];
  677. if (msg->is_ccs) {
  678. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  679. return -1;
  680. }
  681. size_t offset = ssl->init_off;
  682. int ret = dtls1_do_handshake_write(ssl, &offset, msg->data, offset, msg->len,
  683. dtls1_use_current_epoch);
  684. ssl->init_off = offset;
  685. return ret;
  686. }
  687. static int dtls1_retransmit_message(SSL *ssl,
  688. const DTLS_OUTGOING_MESSAGE *msg) {
  689. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  690. * (negotiated cipher) exist. */
  691. assert(ssl->d1->w_epoch == 0 || ssl->d1->w_epoch == 1);
  692. assert(msg->epoch <= ssl->d1->w_epoch);
  693. enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
  694. if (ssl->d1->w_epoch == 1 && msg->epoch == 0) {
  695. use_epoch = dtls1_use_previous_epoch;
  696. }
  697. /* TODO(davidben): This cannot handle non-blocking writes. */
  698. int ret;
  699. if (msg->is_ccs) {
  700. ret = dtls1_write_change_cipher_spec(ssl, use_epoch);
  701. } else {
  702. size_t offset = 0;
  703. ret = dtls1_do_handshake_write(ssl, &offset, msg->data, offset, msg->len,
  704. use_epoch);
  705. }
  706. return ret;
  707. }
  708. int dtls1_retransmit_outgoing_messages(SSL *ssl) {
  709. /* Ensure we are packing handshake messages. */
  710. const int was_buffered = ssl_is_wbio_buffered(ssl);
  711. assert(was_buffered == SSL_in_init(ssl));
  712. if (!was_buffered && !ssl_init_wbio_buffer(ssl)) {
  713. return -1;
  714. }
  715. assert(ssl_is_wbio_buffered(ssl));
  716. int ret = -1;
  717. size_t i;
  718. for (i = 0; i < ssl->d1->outgoing_messages_len; i++) {
  719. if (dtls1_retransmit_message(ssl, &ssl->d1->outgoing_messages[i]) <= 0) {
  720. goto err;
  721. }
  722. }
  723. ret = BIO_flush(ssl->wbio);
  724. if (ret <= 0) {
  725. ssl->rwstate = SSL_WRITING;
  726. goto err;
  727. }
  728. err:
  729. if (!was_buffered) {
  730. ssl_free_wbio_buffer(ssl);
  731. }
  732. return ret;
  733. }
  734. int dtls1_send_change_cipher_spec(SSL *ssl) {
  735. int ret = dtls1_write_change_cipher_spec(ssl, dtls1_use_current_epoch);
  736. if (ret <= 0) {
  737. return ret;
  738. }
  739. dtls1_add_change_cipher_spec(ssl);
  740. return 1;
  741. }
  742. unsigned int dtls1_min_mtu(void) {
  743. return kMinMTU;
  744. }