Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 
 

847 righe
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 msg_len = frag->msg_len;
  202. if (frag->reassembly == NULL || start > end || end > msg_len) {
  203. assert(0);
  204. return;
  205. }
  206. /* A zero-length message will never have a pending reassembly. */
  207. assert(msg_len > 0);
  208. if ((start >> 3) == (end >> 3)) {
  209. frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
  210. } else {
  211. frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
  212. for (size_t i = (start >> 3) + 1; i < (end >> 3); i++) {
  213. frag->reassembly[i] = 0xff;
  214. }
  215. if ((end & 7) != 0) {
  216. frag->reassembly[end >> 3] |= bit_range(0, end & 7);
  217. }
  218. }
  219. /* Check if the fragment is complete. */
  220. for (size_t i = 0; i < (msg_len >> 3); i++) {
  221. if (frag->reassembly[i] != 0xff) {
  222. return;
  223. }
  224. }
  225. if ((msg_len & 7) != 0 &&
  226. frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
  227. return;
  228. }
  229. OPENSSL_free(frag->reassembly);
  230. frag->reassembly = NULL;
  231. }
  232. /* dtls1_is_current_message_complete returns one if the current handshake
  233. * message is complete and zero otherwise. */
  234. static int dtls1_is_current_message_complete(const SSL *ssl) {
  235. hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
  236. SSL_MAX_HANDSHAKE_FLIGHT];
  237. return frag != NULL && frag->reassembly == NULL;
  238. }
  239. /* dtls1_get_incoming_message returns the incoming message corresponding to
  240. * |msg_hdr|. If none exists, it creates a new one and inserts it in the
  241. * queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
  242. * returns NULL on failure. The caller does not take ownership of the result. */
  243. static hm_fragment *dtls1_get_incoming_message(
  244. SSL *ssl, const struct hm_header_st *msg_hdr) {
  245. if (msg_hdr->seq < ssl->d1->handshake_read_seq ||
  246. msg_hdr->seq - ssl->d1->handshake_read_seq >= SSL_MAX_HANDSHAKE_FLIGHT) {
  247. return NULL;
  248. }
  249. size_t idx = msg_hdr->seq % SSL_MAX_HANDSHAKE_FLIGHT;
  250. hm_fragment *frag = ssl->d1->incoming_messages[idx];
  251. if (frag != NULL) {
  252. assert(frag->seq == msg_hdr->seq);
  253. /* The new fragment must be compatible with the previous fragments from this
  254. * message. */
  255. if (frag->type != msg_hdr->type ||
  256. frag->msg_len != msg_hdr->msg_len) {
  257. OPENSSL_PUT_ERROR(SSL, SSL_R_FRAGMENT_MISMATCH);
  258. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  259. return NULL;
  260. }
  261. return frag;
  262. }
  263. /* This is the first fragment from this message. */
  264. frag = dtls1_hm_fragment_new(msg_hdr);
  265. if (frag == NULL) {
  266. return NULL;
  267. }
  268. ssl->d1->incoming_messages[idx] = frag;
  269. return frag;
  270. }
  271. /* dtls1_process_handshake_record reads a handshake record and processes it. It
  272. * returns one if the record was successfully processed and 0 or -1 on error. */
  273. static int dtls1_process_handshake_record(SSL *ssl) {
  274. SSL3_RECORD *rr = &ssl->s3->rrec;
  275. start:
  276. if (rr->length == 0) {
  277. int ret = dtls1_get_record(ssl);
  278. if (ret <= 0) {
  279. return ret;
  280. }
  281. }
  282. /* Cross-epoch records are discarded, but we may receive out-of-order
  283. * application data between ChangeCipherSpec and Finished or a ChangeCipherSpec
  284. * before the appropriate point in the handshake. Those must be silently
  285. * discarded.
  286. *
  287. * However, only allow the out-of-order records in the correct epoch.
  288. * Application data must come in the encrypted epoch, and ChangeCipherSpec in
  289. * the unencrypted epoch (we never renegotiate). Other cases fall through and
  290. * fail with a fatal error. */
  291. if ((rr->type == SSL3_RT_APPLICATION_DATA &&
  292. ssl->s3->aead_read_ctx != NULL) ||
  293. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC &&
  294. ssl->s3->aead_read_ctx == NULL)) {
  295. rr->length = 0;
  296. goto start;
  297. }
  298. if (rr->type != SSL3_RT_HANDSHAKE) {
  299. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  300. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  301. return -1;
  302. }
  303. CBS cbs;
  304. CBS_init(&cbs, rr->data, rr->length);
  305. while (CBS_len(&cbs) > 0) {
  306. /* Read a handshake fragment. */
  307. struct hm_header_st msg_hdr;
  308. CBS body;
  309. if (!dtls1_parse_fragment(&cbs, &msg_hdr, &body)) {
  310. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
  311. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  312. return -1;
  313. }
  314. const size_t frag_off = msg_hdr.frag_off;
  315. const size_t frag_len = msg_hdr.frag_len;
  316. const size_t msg_len = msg_hdr.msg_len;
  317. if (frag_off > msg_len || frag_off + frag_len < frag_off ||
  318. frag_off + frag_len > msg_len ||
  319. msg_len > ssl_max_handshake_message_len(ssl)) {
  320. OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  321. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  322. return -1;
  323. }
  324. /* The encrypted epoch in DTLS has only one handshake message. */
  325. if (ssl->d1->r_epoch == 1 && msg_hdr.seq != ssl->d1->handshake_read_seq) {
  326. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  327. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  328. return -1;
  329. }
  330. if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
  331. msg_hdr.seq >
  332. (unsigned)ssl->d1->handshake_read_seq + SSL_MAX_HANDSHAKE_FLIGHT) {
  333. /* Ignore fragments from the past, or ones too far in the future. */
  334. continue;
  335. }
  336. hm_fragment *frag = dtls1_get_incoming_message(ssl, &msg_hdr);
  337. if (frag == NULL) {
  338. return -1;
  339. }
  340. assert(frag->msg_len == msg_len);
  341. if (frag->reassembly == NULL) {
  342. /* The message is already assembled. */
  343. continue;
  344. }
  345. assert(msg_len > 0);
  346. /* Copy the body into the fragment. */
  347. memcpy(frag->data + DTLS1_HM_HEADER_LENGTH + frag_off, CBS_data(&body),
  348. CBS_len(&body));
  349. dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
  350. }
  351. rr->length = 0;
  352. ssl_read_buffer_discard(ssl);
  353. return 1;
  354. }
  355. int dtls1_get_message(SSL *ssl, int msg_type,
  356. enum ssl_hash_message_t hash_message) {
  357. if (ssl->s3->tmp.reuse_message) {
  358. /* A ssl_dont_hash_message call cannot be combined with reuse_message; the
  359. * ssl_dont_hash_message would have to have been applied to the previous
  360. * call. */
  361. assert(hash_message == ssl_hash_message);
  362. assert(ssl->init_msg != NULL);
  363. ssl->s3->tmp.reuse_message = 0;
  364. hash_message = ssl_dont_hash_message;
  365. } else {
  366. dtls1_release_current_message(ssl, 0 /* don't free buffer */);
  367. }
  368. /* Process handshake records until the current message is ready. */
  369. while (!dtls1_is_current_message_complete(ssl)) {
  370. int ret = dtls1_process_handshake_record(ssl);
  371. if (ret <= 0) {
  372. return ret;
  373. }
  374. }
  375. hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
  376. SSL_MAX_HANDSHAKE_FLIGHT];
  377. assert(frag != NULL);
  378. assert(frag->reassembly == NULL);
  379. assert(ssl->d1->handshake_read_seq == frag->seq);
  380. /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
  381. * |ssl_get_message| API. */
  382. ssl->s3->tmp.message_type = frag->type;
  383. ssl->init_msg = frag->data + DTLS1_HM_HEADER_LENGTH;
  384. ssl->init_num = frag->msg_len;
  385. if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
  386. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  387. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  388. return -1;
  389. }
  390. if (hash_message == ssl_hash_message && !ssl_hash_current_message(ssl)) {
  391. return -1;
  392. }
  393. ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_HANDSHAKE, frag->data,
  394. ssl->init_num + DTLS1_HM_HEADER_LENGTH);
  395. return 1;
  396. }
  397. void dtls1_get_current_message(const SSL *ssl, CBS *out) {
  398. assert(dtls1_is_current_message_complete(ssl));
  399. hm_fragment *frag = ssl->d1->incoming_messages[ssl->d1->handshake_read_seq %
  400. SSL_MAX_HANDSHAKE_FLIGHT];
  401. CBS_init(out, frag->data, DTLS1_HM_HEADER_LENGTH + frag->msg_len);
  402. }
  403. void dtls1_release_current_message(SSL *ssl, int free_buffer) {
  404. if (ssl->init_msg == NULL) {
  405. return;
  406. }
  407. assert(dtls1_is_current_message_complete(ssl));
  408. size_t index = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  409. dtls1_hm_fragment_free(ssl->d1->incoming_messages[index]);
  410. ssl->d1->incoming_messages[index] = NULL;
  411. ssl->d1->handshake_read_seq++;
  412. ssl->init_msg = NULL;
  413. ssl->init_num = 0;
  414. }
  415. void dtls_clear_incoming_messages(SSL *ssl) {
  416. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  417. dtls1_hm_fragment_free(ssl->d1->incoming_messages[i]);
  418. ssl->d1->incoming_messages[i] = NULL;
  419. }
  420. }
  421. int dtls_has_incoming_messages(const SSL *ssl) {
  422. size_t current = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  423. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  424. /* Skip the current message. */
  425. if (ssl->init_msg != NULL && i == current) {
  426. assert(dtls1_is_current_message_complete(ssl));
  427. continue;
  428. }
  429. if (ssl->d1->incoming_messages[i] != NULL) {
  430. return 1;
  431. }
  432. }
  433. return 0;
  434. }
  435. int dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
  436. CBS *out_body) {
  437. memset(out_hdr, 0x00, sizeof(struct hm_header_st));
  438. if (!CBS_get_u8(cbs, &out_hdr->type) ||
  439. !CBS_get_u24(cbs, &out_hdr->msg_len) ||
  440. !CBS_get_u16(cbs, &out_hdr->seq) ||
  441. !CBS_get_u24(cbs, &out_hdr->frag_off) ||
  442. !CBS_get_u24(cbs, &out_hdr->frag_len) ||
  443. !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
  444. return 0;
  445. }
  446. return 1;
  447. }
  448. /* Sending handshake messages. */
  449. static void dtls1_update_mtu(SSL *ssl) {
  450. /* TODO(davidben): What is this code doing and do we need it? */
  451. if (ssl->d1->mtu < dtls1_min_mtu() &&
  452. !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
  453. long mtu = BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  454. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  455. ssl->d1->mtu = (unsigned)mtu;
  456. } else {
  457. ssl->d1->mtu = kDefaultMTU;
  458. BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
  459. }
  460. }
  461. /* The MTU should be above the minimum now. */
  462. assert(ssl->d1->mtu >= dtls1_min_mtu());
  463. }
  464. /* dtls1_max_record_size returns the maximum record body length that may be
  465. * written without exceeding the MTU. It accounts for any buffering installed on
  466. * the write BIO. If no record may be written, it returns zero. */
  467. static size_t dtls1_max_record_size(const SSL *ssl) {
  468. size_t ret = ssl->d1->mtu;
  469. size_t overhead = SSL_max_seal_overhead(ssl);
  470. if (ret <= overhead) {
  471. return 0;
  472. }
  473. ret -= overhead;
  474. size_t pending = BIO_wpending(ssl->wbio);
  475. if (ret <= pending) {
  476. return 0;
  477. }
  478. ret -= pending;
  479. return ret;
  480. }
  481. static int dtls1_write_change_cipher_spec(SSL *ssl,
  482. enum dtls1_use_epoch_t use_epoch) {
  483. dtls1_update_mtu(ssl);
  484. /* During the handshake, wbio is buffered to pack messages together. Flush the
  485. * buffer if the ChangeCipherSpec would not fit in a packet. */
  486. if (dtls1_max_record_size(ssl) == 0) {
  487. int ret = BIO_flush(ssl->wbio);
  488. if (ret <= 0) {
  489. ssl->rwstate = SSL_WRITING;
  490. return ret;
  491. }
  492. }
  493. static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
  494. int ret =
  495. dtls1_write_record(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  496. sizeof(kChangeCipherSpec), use_epoch);
  497. if (ret <= 0) {
  498. return ret;
  499. }
  500. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_CHANGE_CIPHER_SPEC,
  501. kChangeCipherSpec, sizeof(kChangeCipherSpec));
  502. return 1;
  503. }
  504. /* dtls1_do_handshake_write writes handshake message |in| using the given epoch,
  505. * starting |offset| bytes into the message body. It returns one on success. On
  506. * error, it returns <= 0 and sets |*out_offset| to the number of bytes of body
  507. * that were successfully written. This may be used to retry the write
  508. * later. |in| must be a reassembled handshake message with the full DTLS
  509. * handshake header. */
  510. static int dtls1_do_handshake_write(SSL *ssl, size_t *out_offset,
  511. const uint8_t *in, size_t offset,
  512. size_t len,
  513. enum dtls1_use_epoch_t use_epoch) {
  514. dtls1_update_mtu(ssl);
  515. int ret = -1;
  516. CBB cbb;
  517. CBB_zero(&cbb);
  518. /* Allocate a temporary buffer to hold the message fragments to avoid
  519. * clobbering the message. */
  520. uint8_t *buf = OPENSSL_malloc(ssl->d1->mtu);
  521. if (buf == NULL) {
  522. goto err;
  523. }
  524. /* Although it may be sent as multiple fragments, a DTLS message must be sent
  525. * serialized as a single fragment for purposes of |ssl_do_msg_callback| and
  526. * the handshake hash. */
  527. CBS cbs, body;
  528. struct hm_header_st hdr;
  529. CBS_init(&cbs, in, len);
  530. if (!dtls1_parse_fragment(&cbs, &hdr, &body) ||
  531. hdr.frag_off != 0 ||
  532. hdr.frag_len != CBS_len(&body) ||
  533. hdr.msg_len != CBS_len(&body) ||
  534. !CBS_skip(&body, offset) ||
  535. CBS_len(&cbs) != 0) {
  536. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  537. goto err;
  538. }
  539. do {
  540. /* During the handshake, wbio is buffered to pack messages together. Flush
  541. * the buffer if there isn't enough room to make progress. */
  542. if (dtls1_max_record_size(ssl) < DTLS1_HM_HEADER_LENGTH + 1) {
  543. int flush_ret = BIO_flush(ssl->wbio);
  544. if (flush_ret <= 0) {
  545. ssl->rwstate = SSL_WRITING;
  546. ret = flush_ret;
  547. goto err;
  548. }
  549. assert(BIO_wpending(ssl->wbio) == 0);
  550. }
  551. size_t todo = dtls1_max_record_size(ssl);
  552. if (todo < DTLS1_HM_HEADER_LENGTH + 1) {
  553. /* To make forward progress, the MTU must, at minimum, fit the handshake
  554. * header and one byte of handshake body. */
  555. OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
  556. goto err;
  557. }
  558. todo -= DTLS1_HM_HEADER_LENGTH;
  559. if (todo > CBS_len(&body)) {
  560. todo = CBS_len(&body);
  561. }
  562. if (todo >= (1u << 24)) {
  563. todo = (1u << 24) - 1;
  564. }
  565. size_t buf_len;
  566. if (!CBB_init_fixed(&cbb, buf, ssl->d1->mtu) ||
  567. !CBB_add_u8(&cbb, hdr.type) ||
  568. !CBB_add_u24(&cbb, hdr.msg_len) ||
  569. !CBB_add_u16(&cbb, hdr.seq) ||
  570. !CBB_add_u24(&cbb, offset) ||
  571. !CBB_add_u24(&cbb, todo) ||
  572. !CBB_add_bytes(&cbb, CBS_data(&body), todo) ||
  573. !CBB_finish(&cbb, NULL, &buf_len)) {
  574. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  575. goto err;
  576. }
  577. int write_ret =
  578. dtls1_write_record(ssl, SSL3_RT_HANDSHAKE, buf, buf_len, use_epoch);
  579. if (write_ret <= 0) {
  580. ret = write_ret;
  581. goto err;
  582. }
  583. if (!CBS_skip(&body, todo)) {
  584. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  585. goto err;
  586. }
  587. offset += todo;
  588. } while (CBS_len(&body) != 0);
  589. ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_HANDSHAKE, in, len);
  590. ret = 1;
  591. err:
  592. *out_offset = offset;
  593. CBB_cleanup(&cbb);
  594. OPENSSL_free(buf);
  595. return ret;
  596. }
  597. void dtls_clear_outgoing_messages(SSL *ssl) {
  598. for (size_t i = 0; i < ssl->d1->outgoing_messages_len; i++) {
  599. OPENSSL_free(ssl->d1->outgoing_messages[i].data);
  600. ssl->d1->outgoing_messages[i].data = NULL;
  601. }
  602. ssl->d1->outgoing_messages_len = 0;
  603. }
  604. /* dtls1_add_change_cipher_spec adds a ChangeCipherSpec to the current
  605. * handshake flight. */
  606. static int dtls1_add_change_cipher_spec(SSL *ssl) {
  607. if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
  608. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  609. return 0;
  610. }
  611. DTLS_OUTGOING_MESSAGE *msg =
  612. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
  613. msg->data = NULL;
  614. msg->len = 0;
  615. msg->epoch = ssl->d1->w_epoch;
  616. msg->is_ccs = 1;
  617. ssl->d1->outgoing_messages_len++;
  618. return 1;
  619. }
  620. static int dtls1_add_message(SSL *ssl, uint8_t *data, size_t len) {
  621. if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
  622. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  623. OPENSSL_free(data);
  624. return 0;
  625. }
  626. DTLS_OUTGOING_MESSAGE *msg =
  627. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
  628. msg->data = data;
  629. msg->len = len;
  630. msg->epoch = ssl->d1->w_epoch;
  631. msg->is_ccs = 0;
  632. ssl->d1->outgoing_messages_len++;
  633. return 1;
  634. }
  635. int dtls1_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
  636. /* Pick a modest size hint to save most of the |realloc| calls. */
  637. if (!CBB_init(cbb, 64) ||
  638. !CBB_add_u8(cbb, type) ||
  639. !CBB_add_u24(cbb, 0 /* length (filled in later) */) ||
  640. !CBB_add_u16(cbb, ssl->d1->handshake_write_seq) ||
  641. !CBB_add_u24(cbb, 0 /* offset */) ||
  642. !CBB_add_u24_length_prefixed(cbb, body)) {
  643. return 0;
  644. }
  645. return 1;
  646. }
  647. int dtls1_finish_message(SSL *ssl, CBB *cbb, uint8_t **out_msg,
  648. size_t *out_len) {
  649. *out_msg = NULL;
  650. if (!CBB_finish(cbb, out_msg, out_len) ||
  651. *out_len < DTLS1_HM_HEADER_LENGTH) {
  652. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  653. OPENSSL_free(*out_msg);
  654. return 0;
  655. }
  656. /* Fix up the header. Copy the fragment length into the total message
  657. * length. */
  658. memcpy(*out_msg + 1, *out_msg + DTLS1_HM_HEADER_LENGTH - 3, 3);
  659. return 1;
  660. }
  661. int dtls1_queue_message(SSL *ssl, uint8_t *msg, size_t len) {
  662. ssl3_update_handshake_hash(ssl, msg, len);
  663. ssl->d1->handshake_write_seq++;
  664. ssl->init_off = 0;
  665. return dtls1_add_message(ssl, msg, len);
  666. }
  667. int dtls1_write_message(SSL *ssl) {
  668. if (ssl->d1->outgoing_messages_len == 0) {
  669. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  670. return -1;
  671. }
  672. const DTLS_OUTGOING_MESSAGE *msg =
  673. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len - 1];
  674. if (msg->is_ccs) {
  675. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  676. return -1;
  677. }
  678. size_t offset = ssl->init_off;
  679. int ret = dtls1_do_handshake_write(ssl, &offset, msg->data, offset, msg->len,
  680. dtls1_use_current_epoch);
  681. ssl->init_off = offset;
  682. return ret;
  683. }
  684. static int dtls1_retransmit_message(SSL *ssl,
  685. const DTLS_OUTGOING_MESSAGE *msg) {
  686. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  687. * (negotiated cipher) exist. */
  688. assert(ssl->d1->w_epoch == 0 || ssl->d1->w_epoch == 1);
  689. assert(msg->epoch <= ssl->d1->w_epoch);
  690. enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
  691. if (ssl->d1->w_epoch == 1 && msg->epoch == 0) {
  692. use_epoch = dtls1_use_previous_epoch;
  693. }
  694. /* TODO(davidben): This cannot handle non-blocking writes. */
  695. int ret;
  696. if (msg->is_ccs) {
  697. ret = dtls1_write_change_cipher_spec(ssl, use_epoch);
  698. } else {
  699. size_t offset = 0;
  700. ret = dtls1_do_handshake_write(ssl, &offset, msg->data, offset, msg->len,
  701. use_epoch);
  702. }
  703. return ret;
  704. }
  705. int dtls1_retransmit_outgoing_messages(SSL *ssl) {
  706. /* Ensure we are packing handshake messages. */
  707. const int was_buffered = ssl_is_wbio_buffered(ssl);
  708. assert(was_buffered == SSL_in_init(ssl));
  709. if (!was_buffered && !ssl_init_wbio_buffer(ssl)) {
  710. return -1;
  711. }
  712. assert(ssl_is_wbio_buffered(ssl));
  713. int ret = -1;
  714. for (size_t i = 0; i < ssl->d1->outgoing_messages_len; i++) {
  715. if (dtls1_retransmit_message(ssl, &ssl->d1->outgoing_messages[i]) <= 0) {
  716. goto err;
  717. }
  718. }
  719. ret = BIO_flush(ssl->wbio);
  720. if (ret <= 0) {
  721. ssl->rwstate = SSL_WRITING;
  722. goto err;
  723. }
  724. err:
  725. if (!was_buffered) {
  726. ssl_free_wbio_buffer(ssl);
  727. }
  728. return ret;
  729. }
  730. int dtls1_send_change_cipher_spec(SSL *ssl) {
  731. int ret = dtls1_write_change_cipher_spec(ssl, dtls1_use_current_epoch);
  732. if (ret <= 0) {
  733. return ret;
  734. }
  735. dtls1_add_change_cipher_spec(ssl);
  736. return 1;
  737. }
  738. unsigned int dtls1_min_mtu(void) {
  739. return kMinMTU;
  740. }