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.
 
 
 
 
 
 

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