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.
 
 
 
 
 
 

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