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.

d1_both.c 28 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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 && !dtls1_hash_current_message(ssl)) {
  391. return -1;
  392. }
  393. ssl_do_msg_callback(ssl, 0 /* read */, ssl->version, SSL3_RT_HANDSHAKE,
  394. frag->data, ssl->init_num + DTLS1_HM_HEADER_LENGTH);
  395. return 1;
  396. }
  397. int dtls1_hash_current_message(SSL *ssl) {
  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. return ssl3_update_handshake_hash(ssl, frag->data,
  402. DTLS1_HM_HEADER_LENGTH + frag->msg_len);
  403. }
  404. void dtls1_release_current_message(SSL *ssl, int free_buffer) {
  405. if (ssl->init_msg == NULL) {
  406. return;
  407. }
  408. assert(dtls1_is_current_message_complete(ssl));
  409. size_t index = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  410. dtls1_hm_fragment_free(ssl->d1->incoming_messages[index]);
  411. ssl->d1->incoming_messages[index] = NULL;
  412. ssl->d1->handshake_read_seq++;
  413. ssl->init_msg = NULL;
  414. ssl->init_num = 0;
  415. }
  416. void dtls_clear_incoming_messages(SSL *ssl) {
  417. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  418. dtls1_hm_fragment_free(ssl->d1->incoming_messages[i]);
  419. ssl->d1->incoming_messages[i] = NULL;
  420. }
  421. }
  422. int dtls_has_incoming_messages(const SSL *ssl) {
  423. size_t current = ssl->d1->handshake_read_seq % SSL_MAX_HANDSHAKE_FLIGHT;
  424. for (size_t i = 0; i < SSL_MAX_HANDSHAKE_FLIGHT; i++) {
  425. /* Skip the current message. */
  426. if (ssl->init_msg != NULL && i == current) {
  427. assert(dtls1_is_current_message_complete(ssl));
  428. continue;
  429. }
  430. if (ssl->d1->incoming_messages[i] != NULL) {
  431. return 1;
  432. }
  433. }
  434. return 0;
  435. }
  436. int dtls1_parse_fragment(CBS *cbs, struct hm_header_st *out_hdr,
  437. CBS *out_body) {
  438. memset(out_hdr, 0x00, sizeof(struct hm_header_st));
  439. if (!CBS_get_u8(cbs, &out_hdr->type) ||
  440. !CBS_get_u24(cbs, &out_hdr->msg_len) ||
  441. !CBS_get_u16(cbs, &out_hdr->seq) ||
  442. !CBS_get_u24(cbs, &out_hdr->frag_off) ||
  443. !CBS_get_u24(cbs, &out_hdr->frag_len) ||
  444. !CBS_get_bytes(cbs, out_body, out_hdr->frag_len)) {
  445. return 0;
  446. }
  447. return 1;
  448. }
  449. /* Sending handshake messages. */
  450. static void dtls1_update_mtu(SSL *ssl) {
  451. /* TODO(davidben): What is this code doing and do we need it? */
  452. if (ssl->d1->mtu < dtls1_min_mtu() &&
  453. !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
  454. long mtu = BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  455. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  456. ssl->d1->mtu = (unsigned)mtu;
  457. } else {
  458. ssl->d1->mtu = kDefaultMTU;
  459. BIO_ctrl(ssl->wbio, BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
  460. }
  461. }
  462. /* The MTU should be above the minimum now. */
  463. assert(ssl->d1->mtu >= dtls1_min_mtu());
  464. }
  465. /* dtls1_max_record_size returns the maximum record body length that may be
  466. * written without exceeding the MTU. It accounts for any buffering installed on
  467. * the write BIO. If no record may be written, it returns zero. */
  468. static size_t dtls1_max_record_size(SSL *ssl) {
  469. size_t ret = ssl->d1->mtu;
  470. size_t overhead = ssl_max_seal_overhead(ssl);
  471. if (ret <= overhead) {
  472. return 0;
  473. }
  474. ret -= overhead;
  475. size_t pending = BIO_wpending(ssl->wbio);
  476. if (ret <= pending) {
  477. return 0;
  478. }
  479. ret -= pending;
  480. return ret;
  481. }
  482. static int dtls1_write_change_cipher_spec(SSL *ssl,
  483. enum dtls1_use_epoch_t use_epoch) {
  484. dtls1_update_mtu(ssl);
  485. /* During the handshake, wbio is buffered to pack messages together. Flush the
  486. * buffer if the ChangeCipherSpec would not fit in a packet. */
  487. if (dtls1_max_record_size(ssl) == 0) {
  488. int ret = BIO_flush(ssl->wbio);
  489. if (ret <= 0) {
  490. ssl->rwstate = SSL_WRITING;
  491. return ret;
  492. }
  493. }
  494. static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
  495. int ret =
  496. dtls1_write_record(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  497. sizeof(kChangeCipherSpec), use_epoch);
  498. if (ret <= 0) {
  499. return ret;
  500. }
  501. ssl_do_msg_callback(ssl, 1 /* write */, ssl->version,
  502. SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  503. sizeof(kChangeCipherSpec));
  504. return 1;
  505. }
  506. /* dtls1_do_handshake_write writes handshake message |in| using the given epoch,
  507. * starting |offset| bytes into the message body. It returns one on success. On
  508. * error, it returns <= 0 and sets |*out_offset| to the number of bytes of body
  509. * that were successfully written. This may be used to retry the write
  510. * later. |in| must be a reassembled handshake message with the full DTLS
  511. * handshake header. */
  512. static int dtls1_do_handshake_write(SSL *ssl, size_t *out_offset,
  513. const uint8_t *in, size_t offset,
  514. size_t len,
  515. enum dtls1_use_epoch_t use_epoch) {
  516. dtls1_update_mtu(ssl);
  517. int ret = -1;
  518. CBB cbb;
  519. CBB_zero(&cbb);
  520. /* Allocate a temporary buffer to hold the message fragments to avoid
  521. * clobbering the message. */
  522. uint8_t *buf = OPENSSL_malloc(ssl->d1->mtu);
  523. if (buf == NULL) {
  524. goto err;
  525. }
  526. /* Although it may be sent as multiple fragments, a DTLS message must be sent
  527. * serialized as a single fragment for purposes of |ssl_do_msg_callback| and
  528. * the handshake hash. */
  529. CBS cbs, body;
  530. struct hm_header_st hdr;
  531. CBS_init(&cbs, in, len);
  532. if (!dtls1_parse_fragment(&cbs, &hdr, &body) ||
  533. hdr.frag_off != 0 ||
  534. hdr.frag_len != CBS_len(&body) ||
  535. hdr.msg_len != CBS_len(&body) ||
  536. !CBS_skip(&body, offset) ||
  537. CBS_len(&cbs) != 0) {
  538. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  539. goto err;
  540. }
  541. do {
  542. /* During the handshake, wbio is buffered to pack messages together. Flush
  543. * the buffer if there isn't enough room to make progress. */
  544. if (dtls1_max_record_size(ssl) < DTLS1_HM_HEADER_LENGTH + 1) {
  545. int flush_ret = BIO_flush(ssl->wbio);
  546. if (flush_ret <= 0) {
  547. ssl->rwstate = SSL_WRITING;
  548. ret = flush_ret;
  549. goto err;
  550. }
  551. assert(BIO_wpending(ssl->wbio) == 0);
  552. }
  553. size_t todo = dtls1_max_record_size(ssl);
  554. if (todo < DTLS1_HM_HEADER_LENGTH + 1) {
  555. /* To make forward progress, the MTU must, at minimum, fit the handshake
  556. * header and one byte of handshake body. */
  557. OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
  558. goto err;
  559. }
  560. todo -= DTLS1_HM_HEADER_LENGTH;
  561. if (todo > CBS_len(&body)) {
  562. todo = CBS_len(&body);
  563. }
  564. if (todo >= (1u << 24)) {
  565. todo = (1u << 24) - 1;
  566. }
  567. size_t buf_len;
  568. if (!CBB_init_fixed(&cbb, buf, ssl->d1->mtu) ||
  569. !CBB_add_u8(&cbb, hdr.type) ||
  570. !CBB_add_u24(&cbb, hdr.msg_len) ||
  571. !CBB_add_u16(&cbb, hdr.seq) ||
  572. !CBB_add_u24(&cbb, offset) ||
  573. !CBB_add_u24(&cbb, todo) ||
  574. !CBB_add_bytes(&cbb, CBS_data(&body), todo) ||
  575. !CBB_finish(&cbb, NULL, &buf_len)) {
  576. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  577. goto err;
  578. }
  579. int write_ret =
  580. dtls1_write_record(ssl, SSL3_RT_HANDSHAKE, buf, buf_len, use_epoch);
  581. if (write_ret <= 0) {
  582. ret = write_ret;
  583. goto err;
  584. }
  585. if (!CBS_skip(&body, todo)) {
  586. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  587. goto err;
  588. }
  589. offset += todo;
  590. } while (CBS_len(&body) != 0);
  591. ssl_do_msg_callback(ssl, 1 /* write */, ssl->version, SSL3_RT_HANDSHAKE, in,
  592. len);
  593. ret = 1;
  594. err:
  595. *out_offset = offset;
  596. CBB_cleanup(&cbb);
  597. OPENSSL_free(buf);
  598. return ret;
  599. }
  600. void dtls_clear_outgoing_messages(SSL *ssl) {
  601. for (size_t i = 0; i < ssl->d1->outgoing_messages_len; i++) {
  602. OPENSSL_free(ssl->d1->outgoing_messages[i].data);
  603. ssl->d1->outgoing_messages[i].data = NULL;
  604. }
  605. ssl->d1->outgoing_messages_len = 0;
  606. }
  607. /* dtls1_add_change_cipher_spec adds a ChangeCipherSpec to the current
  608. * handshake flight. */
  609. static int dtls1_add_change_cipher_spec(SSL *ssl) {
  610. if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
  611. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  612. return 0;
  613. }
  614. DTLS_OUTGOING_MESSAGE *msg =
  615. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
  616. msg->data = NULL;
  617. msg->len = 0;
  618. msg->epoch = ssl->d1->w_epoch;
  619. msg->is_ccs = 1;
  620. ssl->d1->outgoing_messages_len++;
  621. return 1;
  622. }
  623. static int dtls1_add_message(SSL *ssl, uint8_t *data, size_t len) {
  624. if (ssl->d1->outgoing_messages_len >= SSL_MAX_HANDSHAKE_FLIGHT) {
  625. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  626. OPENSSL_free(data);
  627. return 0;
  628. }
  629. DTLS_OUTGOING_MESSAGE *msg =
  630. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len];
  631. msg->data = data;
  632. msg->len = len;
  633. msg->epoch = ssl->d1->w_epoch;
  634. msg->is_ccs = 0;
  635. ssl->d1->outgoing_messages_len++;
  636. return 1;
  637. }
  638. int dtls1_init_message(SSL *ssl, CBB *cbb, CBB *body, uint8_t type) {
  639. /* Pick a modest size hint to save most of the |realloc| calls. */
  640. if (!CBB_init(cbb, 64) ||
  641. !CBB_add_u8(cbb, type) ||
  642. !CBB_add_u24(cbb, 0 /* length (filled in later) */) ||
  643. !CBB_add_u16(cbb, ssl->d1->handshake_write_seq) ||
  644. !CBB_add_u24(cbb, 0 /* offset */) ||
  645. !CBB_add_u24_length_prefixed(cbb, body)) {
  646. return 0;
  647. }
  648. return 1;
  649. }
  650. int dtls1_finish_message(SSL *ssl, CBB *cbb) {
  651. uint8_t *msg = NULL;
  652. size_t len;
  653. if (!CBB_finish(cbb, &msg, &len) ||
  654. len > 0xffffffffu ||
  655. len < DTLS1_HM_HEADER_LENGTH) {
  656. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  657. OPENSSL_free(msg);
  658. return 0;
  659. }
  660. /* Fix up the header. Copy the fragment length into the total message
  661. * length. */
  662. memcpy(msg + 1, msg + DTLS1_HM_HEADER_LENGTH - 3, 3);
  663. ssl3_update_handshake_hash(ssl, msg, len);
  664. ssl->d1->handshake_write_seq++;
  665. ssl->init_off = 0;
  666. return dtls1_add_message(ssl, msg, len);
  667. }
  668. int dtls1_write_message(SSL *ssl) {
  669. if (ssl->d1->outgoing_messages_len == 0) {
  670. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  671. return -1;
  672. }
  673. const DTLS_OUTGOING_MESSAGE *msg =
  674. &ssl->d1->outgoing_messages[ssl->d1->outgoing_messages_len - 1];
  675. if (msg->is_ccs) {
  676. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  677. return -1;
  678. }
  679. size_t offset = ssl->init_off;
  680. int ret = dtls1_do_handshake_write(ssl, &offset, msg->data, offset, msg->len,
  681. dtls1_use_current_epoch);
  682. ssl->init_off = offset;
  683. return ret;
  684. }
  685. static int dtls1_retransmit_message(SSL *ssl,
  686. const DTLS_OUTGOING_MESSAGE *msg) {
  687. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  688. * (negotiated cipher) exist. */
  689. assert(ssl->d1->w_epoch == 0 || ssl->d1->w_epoch == 1);
  690. assert(msg->epoch <= ssl->d1->w_epoch);
  691. enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
  692. if (ssl->d1->w_epoch == 1 && msg->epoch == 0) {
  693. use_epoch = dtls1_use_previous_epoch;
  694. }
  695. /* TODO(davidben): This cannot handle non-blocking writes. */
  696. int ret;
  697. if (msg->is_ccs) {
  698. ret = dtls1_write_change_cipher_spec(ssl, use_epoch);
  699. } else {
  700. size_t offset = 0;
  701. ret = dtls1_do_handshake_write(ssl, &offset, msg->data, offset, msg->len,
  702. use_epoch);
  703. }
  704. return ret;
  705. }
  706. int dtls1_retransmit_outgoing_messages(SSL *ssl) {
  707. /* Ensure we are packing handshake messages. */
  708. const int was_buffered = ssl_is_wbio_buffered(ssl);
  709. assert(was_buffered == SSL_in_init(ssl));
  710. if (!was_buffered && !ssl_init_wbio_buffer(ssl)) {
  711. return -1;
  712. }
  713. assert(ssl_is_wbio_buffered(ssl));
  714. int ret = -1;
  715. for (size_t i = 0; i < ssl->d1->outgoing_messages_len; i++) {
  716. if (dtls1_retransmit_message(ssl, &ssl->d1->outgoing_messages[i]) <= 0) {
  717. goto err;
  718. }
  719. }
  720. ret = BIO_flush(ssl->wbio);
  721. if (ret <= 0) {
  722. ssl->rwstate = SSL_WRITING;
  723. goto err;
  724. }
  725. err:
  726. if (!was_buffered) {
  727. ssl_free_wbio_buffer(ssl);
  728. }
  729. return ret;
  730. }
  731. int dtls1_send_change_cipher_spec(SSL *ssl) {
  732. int ret = dtls1_write_change_cipher_spec(ssl, dtls1_use_current_epoch);
  733. if (ret <= 0) {
  734. return ret;
  735. }
  736. dtls1_add_change_cipher_spec(ssl);
  737. return 1;
  738. }
  739. unsigned int dtls1_min_mtu(void) {
  740. return kMinMTU;
  741. }