Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

878 wiersze
30 KiB

  1. /*
  2. * DTLS implementation written by Nagendra Modadugu
  3. * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
  4. */
  5. /* ====================================================================
  6. * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * 1. Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * 2. Redistributions in binary form must reproduce the above copyright
  16. * notice, this list of conditions and the following disclaimer in
  17. * the documentation and/or other materials provided with the
  18. * distribution.
  19. *
  20. * 3. All advertising materials mentioning features or use of this
  21. * software must display the following acknowledgment:
  22. * "This product includes software developed by the OpenSSL Project
  23. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  24. *
  25. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  26. * endorse or promote products derived from this software without
  27. * prior written permission. For written permission, please contact
  28. * openssl-core@openssl.org.
  29. *
  30. * 5. Products derived from this software may not be called "OpenSSL"
  31. * nor may "OpenSSL" appear in their names without prior written
  32. * permission of the OpenSSL Project.
  33. *
  34. * 6. Redistributions of any form whatsoever must retain the following
  35. * acknowledgment:
  36. * "This product includes software developed by the OpenSSL Project
  37. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  38. *
  39. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  40. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  41. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  42. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  43. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  44. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  45. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  46. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  48. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  49. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  50. * OF THE POSSIBILITY OF SUCH DAMAGE.
  51. * ====================================================================
  52. *
  53. * This product includes cryptographic software written by Eric Young
  54. * (eay@cryptsoft.com). This product includes software written by Tim
  55. * Hudson (tjh@cryptsoft.com).
  56. *
  57. */
  58. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  59. * All rights reserved.
  60. *
  61. * This package is an SSL implementation written
  62. * by Eric Young (eay@cryptsoft.com).
  63. * The implementation was written so as to conform with Netscapes SSL.
  64. *
  65. * This library is free for commercial and non-commercial use as long as
  66. * the following conditions are aheared to. The following conditions
  67. * apply to all code found in this distribution, be it the RC4, RSA,
  68. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  69. * included with this distribution is covered by the same copyright terms
  70. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  71. *
  72. * Copyright remains Eric Young's, and as such any Copyright notices in
  73. * the code are not to be removed.
  74. * If this package is used in a product, Eric Young should be given attribution
  75. * as the author of the parts of the library used.
  76. * This can be in the form of a textual message at program startup or
  77. * in documentation (online or textual) provided with the package.
  78. *
  79. * Redistribution and use in source and binary forms, with or without
  80. * modification, are permitted provided that the following conditions
  81. * are met:
  82. * 1. Redistributions of source code must retain the copyright
  83. * notice, this list of conditions and the following disclaimer.
  84. * 2. Redistributions in binary form must reproduce the above copyright
  85. * notice, this list of conditions and the following disclaimer in the
  86. * documentation and/or other materials provided with the distribution.
  87. * 3. All advertising materials mentioning features or use of this software
  88. * must display the following acknowledgement:
  89. * "This product includes cryptographic software written by
  90. * Eric Young (eay@cryptsoft.com)"
  91. * The word 'cryptographic' can be left out if the rouines from the library
  92. * being used are not cryptographic related :-).
  93. * 4. If you include any Windows specific code (or a derivative thereof) from
  94. * the apps directory (application code) you must include an acknowledgement:
  95. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  96. *
  97. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  98. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  99. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  100. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  101. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  102. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  103. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  104. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  105. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  106. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  107. * SUCH DAMAGE.
  108. *
  109. * The licence and distribution terms for any publically available version or
  110. * derivative of this code cannot be changed. i.e. this code cannot simply be
  111. * copied and put under another distribution licence
  112. * [including the GNU Public Licence.] */
  113. #include <openssl/ssl.h>
  114. #include <assert.h>
  115. #include <limits.h>
  116. #include <string.h>
  117. #include <openssl/buf.h>
  118. #include <openssl/err.h>
  119. #include <openssl/evp.h>
  120. #include <openssl/mem.h>
  121. #include <openssl/rand.h>
  122. #include <openssl/x509.h>
  123. #include "internal.h"
  124. /* TODO(davidben): 28 comes from the size of IP + UDP header. Is this reasonable
  125. * for these values? Notably, why is kMinMTU a function of the transport
  126. * protocol's overhead rather than, say, what's needed to hold a minimally-sized
  127. * handshake fragment plus protocol overhead. */
  128. /* kMinMTU is the minimum acceptable MTU value. */
  129. static const unsigned int kMinMTU = 256 - 28;
  130. /* kDefaultMTU is the default MTU value to use if neither the user nor
  131. * the underlying BIO supplies one. */
  132. static const unsigned int kDefaultMTU = 1500 - 28;
  133. /* kMaxHandshakeBuffer is the maximum number of handshake messages ahead of the
  134. * current one to buffer. */
  135. static const unsigned int kHandshakeBufferSize = 10;
  136. static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly) {
  137. hm_fragment *frag = OPENSSL_malloc(sizeof(hm_fragment));
  138. if (frag == NULL) {
  139. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  140. return NULL;
  141. }
  142. memset(frag, 0, sizeof(hm_fragment));
  143. /* If the handshake message is empty, |frag->fragment| and |frag->reassembly|
  144. * are NULL. */
  145. if (frag_len > 0) {
  146. frag->fragment = OPENSSL_malloc(frag_len);
  147. if (frag->fragment == NULL) {
  148. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  149. goto err;
  150. }
  151. if (reassembly) {
  152. /* Initialize reassembly bitmask. */
  153. if (frag_len + 7 < frag_len) {
  154. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  155. goto err;
  156. }
  157. size_t bitmask_len = (frag_len + 7) / 8;
  158. frag->reassembly = OPENSSL_malloc(bitmask_len);
  159. if (frag->reassembly == NULL) {
  160. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  161. goto err;
  162. }
  163. memset(frag->reassembly, 0, bitmask_len);
  164. }
  165. }
  166. return frag;
  167. err:
  168. dtls1_hm_fragment_free(frag);
  169. return NULL;
  170. }
  171. void dtls1_hm_fragment_free(hm_fragment *frag) {
  172. if (frag == NULL) {
  173. return;
  174. }
  175. OPENSSL_free(frag->fragment);
  176. OPENSSL_free(frag->reassembly);
  177. OPENSSL_free(frag);
  178. }
  179. #if !defined(inline)
  180. #define inline __inline
  181. #endif
  182. /* bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
  183. * exclusive, set. */
  184. static inline uint8_t bit_range(size_t start, size_t end) {
  185. return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
  186. }
  187. /* dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
  188. * as received in |frag|. If |frag| becomes complete, it clears
  189. * |frag->reassembly|. The range must be within the bounds of |frag|'s message
  190. * and |frag->reassembly| must not be NULL. */
  191. static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
  192. size_t end) {
  193. size_t i;
  194. size_t msg_len = frag->msg_header.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 >> 3) == (end >> 3)) {
  202. frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
  203. } else {
  204. frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
  205. for (i = (start >> 3) + 1; i < (end >> 3); i++) {
  206. frag->reassembly[i] = 0xff;
  207. }
  208. if ((end & 7) != 0) {
  209. frag->reassembly[end >> 3] |= bit_range(0, end & 7);
  210. }
  211. }
  212. /* Check if the fragment is complete. */
  213. for (i = 0; i < (msg_len >> 3); i++) {
  214. if (frag->reassembly[i] != 0xff) {
  215. return;
  216. }
  217. }
  218. if ((msg_len & 7) != 0 &&
  219. frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
  220. return;
  221. }
  222. OPENSSL_free(frag->reassembly);
  223. frag->reassembly = NULL;
  224. }
  225. static void dtls1_update_mtu(SSL *ssl) {
  226. /* TODO(davidben): What is this code doing and do we need it? */
  227. if (ssl->d1->mtu < dtls1_min_mtu() &&
  228. !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
  229. long mtu = BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  230. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  231. ssl->d1->mtu = (unsigned)mtu;
  232. } else {
  233. ssl->d1->mtu = kDefaultMTU;
  234. BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SET_MTU, ssl->d1->mtu, NULL);
  235. }
  236. }
  237. /* The MTU should be above the minimum now. */
  238. assert(ssl->d1->mtu >= dtls1_min_mtu());
  239. }
  240. /* dtls1_max_record_size returns the maximum record body length that may be
  241. * written without exceeding the MTU. It accounts for any buffering installed on
  242. * the write BIO. If no record may be written, it returns zero. */
  243. static size_t dtls1_max_record_size(SSL *ssl) {
  244. size_t ret = ssl->d1->mtu;
  245. size_t overhead = ssl_max_seal_overhead(ssl);
  246. if (ret <= overhead) {
  247. return 0;
  248. }
  249. ret -= overhead;
  250. size_t pending = BIO_wpending(SSL_get_wbio(ssl));
  251. if (ret <= pending) {
  252. return 0;
  253. }
  254. ret -= pending;
  255. return ret;
  256. }
  257. static int dtls1_write_change_cipher_spec(SSL *ssl,
  258. enum dtls1_use_epoch_t use_epoch) {
  259. dtls1_update_mtu(ssl);
  260. /* During the handshake, wbio is buffered to pack messages together. Flush the
  261. * buffer if the ChangeCipherSpec would not fit in a packet. */
  262. if (dtls1_max_record_size(ssl) == 0) {
  263. int ret = BIO_flush(SSL_get_wbio(ssl));
  264. if (ret <= 0) {
  265. ssl->rwstate = SSL_WRITING;
  266. return ret;
  267. }
  268. }
  269. static const uint8_t kChangeCipherSpec[1] = {SSL3_MT_CCS};
  270. int ret =
  271. dtls1_write_bytes(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, kChangeCipherSpec,
  272. sizeof(kChangeCipherSpec), use_epoch);
  273. if (ret <= 0) {
  274. return ret;
  275. }
  276. if (ssl->msg_callback != NULL) {
  277. ssl->msg_callback(1 /* write */, ssl->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  278. kChangeCipherSpec, sizeof(kChangeCipherSpec), ssl,
  279. ssl->msg_callback_arg);
  280. }
  281. return 1;
  282. }
  283. int dtls1_do_handshake_write(SSL *ssl, enum dtls1_use_epoch_t use_epoch) {
  284. dtls1_update_mtu(ssl);
  285. int ret = -1;
  286. CBB cbb;
  287. CBB_zero(&cbb);
  288. /* Allocate a temporary buffer to hold the message fragments to avoid
  289. * clobbering the message. */
  290. uint8_t *buf = OPENSSL_malloc(ssl->d1->mtu);
  291. if (buf == NULL) {
  292. goto err;
  293. }
  294. /* Consume the message header. Fragments will have different headers
  295. * prepended. */
  296. if (ssl->init_off == 0) {
  297. ssl->init_off += DTLS1_HM_HEADER_LENGTH;
  298. ssl->init_num -= DTLS1_HM_HEADER_LENGTH;
  299. }
  300. assert(ssl->init_off >= DTLS1_HM_HEADER_LENGTH);
  301. do {
  302. /* During the handshake, wbio is buffered to pack messages together. Flush
  303. * the buffer if there isn't enough room to make progress. */
  304. if (dtls1_max_record_size(ssl) < DTLS1_HM_HEADER_LENGTH + 1) {
  305. int flush_ret = BIO_flush(SSL_get_wbio(ssl));
  306. if (flush_ret <= 0) {
  307. ssl->rwstate = SSL_WRITING;
  308. ret = flush_ret;
  309. goto err;
  310. }
  311. assert(BIO_wpending(SSL_get_wbio(ssl)) == 0);
  312. }
  313. size_t todo = dtls1_max_record_size(ssl);
  314. if (todo < DTLS1_HM_HEADER_LENGTH + 1) {
  315. /* To make forward progress, the MTU must, at minimum, fit the handshake
  316. * header and one byte of handshake body. */
  317. OPENSSL_PUT_ERROR(SSL, SSL_R_MTU_TOO_SMALL);
  318. goto err;
  319. }
  320. todo -= DTLS1_HM_HEADER_LENGTH;
  321. if (todo > (size_t)ssl->init_num) {
  322. todo = ssl->init_num;
  323. }
  324. if (todo >= (1u << 24)) {
  325. todo = (1u << 24) - 1;
  326. }
  327. size_t len;
  328. if (!CBB_init_fixed(&cbb, buf, ssl->d1->mtu) ||
  329. !CBB_add_u8(&cbb, ssl->d1->w_msg_hdr.type) ||
  330. !CBB_add_u24(&cbb, ssl->d1->w_msg_hdr.msg_len) ||
  331. !CBB_add_u16(&cbb, ssl->d1->w_msg_hdr.seq) ||
  332. !CBB_add_u24(&cbb, ssl->init_off - DTLS1_HM_HEADER_LENGTH) ||
  333. !CBB_add_u24(&cbb, todo) ||
  334. !CBB_add_bytes(
  335. &cbb, (const uint8_t *)ssl->init_buf->data + ssl->init_off, todo) ||
  336. !CBB_finish(&cbb, NULL, &len)) {
  337. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  338. goto err;
  339. }
  340. int write_ret = dtls1_write_bytes(ssl, SSL3_RT_HANDSHAKE, buf, len,
  341. use_epoch);
  342. if (write_ret <= 0) {
  343. ret = write_ret;
  344. goto err;
  345. }
  346. ssl->init_off += todo;
  347. ssl->init_num -= todo;
  348. } while (ssl->init_num > 0);
  349. if (ssl->msg_callback != NULL) {
  350. ssl->msg_callback(
  351. 1 /* write */, ssl->version, SSL3_RT_HANDSHAKE, ssl->init_buf->data,
  352. (size_t)(ssl->init_off + ssl->init_num), ssl, ssl->msg_callback_arg);
  353. }
  354. ssl->init_off = 0;
  355. ssl->init_num = 0;
  356. ret = 1;
  357. err:
  358. CBB_cleanup(&cbb);
  359. OPENSSL_free(buf);
  360. return ret;
  361. }
  362. /* dtls1_is_next_message_complete returns one if the next handshake message is
  363. * complete and zero otherwise. */
  364. static int dtls1_is_next_message_complete(SSL *ssl) {
  365. pitem *item = pqueue_peek(ssl->d1->buffered_messages);
  366. if (item == NULL) {
  367. return 0;
  368. }
  369. hm_fragment *frag = (hm_fragment *)item->data;
  370. assert(ssl->d1->handshake_read_seq <= frag->msg_header.seq);
  371. return ssl->d1->handshake_read_seq == frag->msg_header.seq &&
  372. frag->reassembly == NULL;
  373. }
  374. /* dtls1_discard_fragment_body discards a handshake fragment body of length
  375. * |frag_len|. It returns one on success and zero on error.
  376. *
  377. * TODO(davidben): This function will go away when ssl_read_bytes is gone from
  378. * the DTLS side. */
  379. static int dtls1_discard_fragment_body(SSL *ssl, size_t frag_len) {
  380. uint8_t discard[256];
  381. while (frag_len > 0) {
  382. size_t chunk = frag_len < sizeof(discard) ? frag_len : sizeof(discard);
  383. int ret = dtls1_read_bytes(ssl, SSL3_RT_HANDSHAKE, discard, chunk, 0);
  384. if (ret != (int) chunk) {
  385. return 0;
  386. }
  387. frag_len -= chunk;
  388. }
  389. return 1;
  390. }
  391. /* dtls1_get_buffered_message returns the buffered message corresponding to
  392. * |msg_hdr|. If none exists, it creates a new one and inserts it in the
  393. * queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
  394. * returns NULL on failure. The caller does not take ownership of the result. */
  395. static hm_fragment *dtls1_get_buffered_message(
  396. SSL *ssl, const struct hm_header_st *msg_hdr) {
  397. uint8_t seq64be[8];
  398. memset(seq64be, 0, sizeof(seq64be));
  399. seq64be[6] = (uint8_t)(msg_hdr->seq >> 8);
  400. seq64be[7] = (uint8_t)msg_hdr->seq;
  401. pitem *item = pqueue_find(ssl->d1->buffered_messages, seq64be);
  402. hm_fragment *frag;
  403. if (item == NULL) {
  404. /* This is the first fragment from this message. */
  405. frag = dtls1_hm_fragment_new(msg_hdr->msg_len,
  406. 1 /* reassembly buffer needed */);
  407. if (frag == NULL) {
  408. return NULL;
  409. }
  410. memcpy(&frag->msg_header, msg_hdr, sizeof(*msg_hdr));
  411. item = pitem_new(seq64be, frag);
  412. if (item == NULL) {
  413. dtls1_hm_fragment_free(frag);
  414. return NULL;
  415. }
  416. item = pqueue_insert(ssl->d1->buffered_messages, item);
  417. /* |pqueue_insert| fails iff a duplicate item is inserted, but |item| cannot
  418. * be a duplicate. */
  419. assert(item != NULL);
  420. } else {
  421. frag = item->data;
  422. assert(frag->msg_header.seq == msg_hdr->seq);
  423. if (frag->msg_header.type != msg_hdr->type ||
  424. frag->msg_header.msg_len != msg_hdr->msg_len) {
  425. /* The new fragment must be compatible with the previous fragments from
  426. * this message. */
  427. OPENSSL_PUT_ERROR(SSL, SSL_R_FRAGMENT_MISMATCH);
  428. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  429. return NULL;
  430. }
  431. }
  432. return frag;
  433. }
  434. /* dtls1_max_handshake_message_len returns the maximum number of bytes
  435. * permitted in a DTLS handshake message for |ssl|. The minimum is 16KB, but may
  436. * be greater if the maximum certificate list size requires it. */
  437. static size_t dtls1_max_handshake_message_len(const SSL *ssl) {
  438. size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
  439. if (max_len < ssl->max_cert_list) {
  440. return ssl->max_cert_list;
  441. }
  442. return max_len;
  443. }
  444. /* dtls1_process_fragment reads a handshake fragment and processes it. It
  445. * returns one if a fragment was successfully processed and 0 or -1 on error. */
  446. static int dtls1_process_fragment(SSL *ssl) {
  447. /* Read handshake message header. */
  448. uint8_t header[DTLS1_HM_HEADER_LENGTH];
  449. int ret = dtls1_read_bytes(ssl, SSL3_RT_HANDSHAKE, header,
  450. DTLS1_HM_HEADER_LENGTH, 0);
  451. if (ret <= 0) {
  452. return ret;
  453. }
  454. if (ret != DTLS1_HM_HEADER_LENGTH) {
  455. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  456. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  457. return -1;
  458. }
  459. /* Parse the message fragment header. */
  460. struct hm_header_st msg_hdr;
  461. dtls1_get_message_header(header, &msg_hdr);
  462. /* TODO(davidben): dtls1_read_bytes is the wrong abstraction for DTLS. There
  463. * should be no need to reach into |ssl->s3->rrec.length|. */
  464. const size_t frag_off = msg_hdr.frag_off;
  465. const size_t frag_len = msg_hdr.frag_len;
  466. const size_t msg_len = msg_hdr.msg_len;
  467. if (frag_off > msg_len || frag_off + frag_len < frag_off ||
  468. frag_off + frag_len > msg_len ||
  469. msg_len > dtls1_max_handshake_message_len(ssl) ||
  470. frag_len > ssl->s3->rrec.length) {
  471. OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  472. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  473. return -1;
  474. }
  475. if (msg_hdr.seq < ssl->d1->handshake_read_seq ||
  476. msg_hdr.seq > (unsigned)ssl->d1->handshake_read_seq +
  477. kHandshakeBufferSize) {
  478. /* Ignore fragments from the past, or ones too far in the future. */
  479. if (!dtls1_discard_fragment_body(ssl, frag_len)) {
  480. return -1;
  481. }
  482. return 1;
  483. }
  484. hm_fragment *frag = dtls1_get_buffered_message(ssl, &msg_hdr);
  485. if (frag == NULL) {
  486. return -1;
  487. }
  488. assert(frag->msg_header.msg_len == msg_len);
  489. if (frag->reassembly == NULL) {
  490. /* The message is already assembled. */
  491. if (!dtls1_discard_fragment_body(ssl, frag_len)) {
  492. return -1;
  493. }
  494. return 1;
  495. }
  496. assert(msg_len > 0);
  497. /* Read the body of the fragment. */
  498. ret = dtls1_read_bytes(ssl, SSL3_RT_HANDSHAKE, frag->fragment + frag_off,
  499. frag_len, 0);
  500. if (ret != (int) frag_len) {
  501. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  502. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  503. return -1;
  504. }
  505. dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
  506. return 1;
  507. }
  508. /* dtls1_get_message reads a handshake message of message type |msg_type| (any
  509. * if |msg_type| == -1), maximum acceptable body length |max|. Read an entire
  510. * handshake message. Handshake messages arrive in fragments. */
  511. long dtls1_get_message(SSL *ssl, int st1, int stn, int msg_type, long max,
  512. enum ssl_hash_message_t hash_message, int *ok) {
  513. pitem *item = NULL;
  514. hm_fragment *frag = NULL;
  515. int al;
  516. /* s3->tmp is used to store messages that are unexpected, caused
  517. * by the absence of an optional handshake message */
  518. if (ssl->s3->tmp.reuse_message) {
  519. /* A ssl_dont_hash_message call cannot be combined with reuse_message; the
  520. * ssl_dont_hash_message would have to have been applied to the previous
  521. * call. */
  522. assert(hash_message == ssl_hash_message);
  523. ssl->s3->tmp.reuse_message = 0;
  524. if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
  525. al = SSL_AD_UNEXPECTED_MESSAGE;
  526. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  527. goto f_err;
  528. }
  529. *ok = 1;
  530. ssl->init_msg = (uint8_t *)ssl->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  531. ssl->init_num = (int)ssl->s3->tmp.message_size;
  532. return ssl->init_num;
  533. }
  534. /* Process fragments until one is found. */
  535. while (!dtls1_is_next_message_complete(ssl)) {
  536. int ret = dtls1_process_fragment(ssl);
  537. if (ret <= 0) {
  538. *ok = 0;
  539. return ret;
  540. }
  541. }
  542. /* Read out the next complete handshake message. */
  543. item = pqueue_pop(ssl->d1->buffered_messages);
  544. assert(item != NULL);
  545. frag = (hm_fragment *)item->data;
  546. assert(ssl->d1->handshake_read_seq == frag->msg_header.seq);
  547. assert(frag->reassembly == NULL);
  548. if (frag->msg_header.msg_len > (size_t)max) {
  549. OPENSSL_PUT_ERROR(SSL, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  550. goto err;
  551. }
  552. /* Reconstruct the assembled message. */
  553. size_t len;
  554. CBB cbb;
  555. CBB_zero(&cbb);
  556. if (!BUF_MEM_grow(ssl->init_buf, (size_t)frag->msg_header.msg_len +
  557. DTLS1_HM_HEADER_LENGTH) ||
  558. !CBB_init_fixed(&cbb, (uint8_t *)ssl->init_buf->data,
  559. ssl->init_buf->max) ||
  560. !CBB_add_u8(&cbb, frag->msg_header.type) ||
  561. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  562. !CBB_add_u16(&cbb, frag->msg_header.seq) ||
  563. !CBB_add_u24(&cbb, 0 /* frag_off */) ||
  564. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  565. !CBB_add_bytes(&cbb, frag->fragment, frag->msg_header.msg_len) ||
  566. !CBB_finish(&cbb, NULL, &len)) {
  567. CBB_cleanup(&cbb);
  568. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  569. goto err;
  570. }
  571. assert(len == (size_t)frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
  572. ssl->d1->handshake_read_seq++;
  573. /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
  574. * |ssl_get_message| API. */
  575. ssl->s3->tmp.message_type = frag->msg_header.type;
  576. ssl->s3->tmp.message_size = frag->msg_header.msg_len;
  577. ssl->init_msg = (uint8_t *)ssl->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  578. ssl->init_num = frag->msg_header.msg_len;
  579. if (msg_type >= 0 && ssl->s3->tmp.message_type != msg_type) {
  580. al = SSL_AD_UNEXPECTED_MESSAGE;
  581. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  582. goto f_err;
  583. }
  584. if (hash_message == ssl_hash_message && !ssl3_hash_current_message(ssl)) {
  585. goto err;
  586. }
  587. if (ssl->msg_callback) {
  588. ssl->msg_callback(0, ssl->version, SSL3_RT_HANDSHAKE, ssl->init_buf->data,
  589. ssl->init_num + DTLS1_HM_HEADER_LENGTH, ssl,
  590. ssl->msg_callback_arg);
  591. }
  592. pitem_free(item);
  593. dtls1_hm_fragment_free(frag);
  594. ssl->state = stn;
  595. *ok = 1;
  596. return ssl->init_num;
  597. f_err:
  598. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  599. err:
  600. pitem_free(item);
  601. dtls1_hm_fragment_free(frag);
  602. *ok = 0;
  603. return -1;
  604. }
  605. int dtls1_read_failed(SSL *ssl, int code) {
  606. if (code > 0) {
  607. assert(0);
  608. return 1;
  609. }
  610. if (!dtls1_is_timer_expired(ssl)) {
  611. /* not a timeout, none of our business, let higher layers handle this. In
  612. * fact, it's probably an error */
  613. return code;
  614. }
  615. if (!SSL_in_init(ssl)) {
  616. /* done, no need to send a retransmit */
  617. BIO_set_flags(SSL_get_rbio(ssl), BIO_FLAGS_READ);
  618. return code;
  619. }
  620. return DTLSv1_handle_timeout(ssl);
  621. }
  622. static uint16_t dtls1_get_queue_priority(uint16_t seq, int is_ccs) {
  623. assert(seq * 2 >= seq);
  624. /* The index of the retransmission queue actually is the message sequence
  625. * number, since the queue only contains messages of a single handshake.
  626. * However, the ChangeCipherSpec has no message sequence number and so using
  627. * only the sequence will result in the CCS and Finished having the same
  628. * index. To prevent this, the sequence number is multiplied by 2. In case of
  629. * a CCS 1 is subtracted. This does not only differ CSS and Finished, it also
  630. * maintains the order of the index (important for priority queues) and fits
  631. * in the unsigned short variable. */
  632. return seq * 2 - is_ccs;
  633. }
  634. static int dtls1_retransmit_message(SSL *ssl, hm_fragment *frag) {
  635. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  636. * (negotiated cipher) exist. */
  637. assert(ssl->d1->w_epoch == 0 || ssl->d1->w_epoch == 1);
  638. assert(frag->msg_header.epoch <= ssl->d1->w_epoch);
  639. enum dtls1_use_epoch_t use_epoch = dtls1_use_current_epoch;
  640. if (ssl->d1->w_epoch == 1 && frag->msg_header.epoch == 0) {
  641. use_epoch = dtls1_use_previous_epoch;
  642. }
  643. /* TODO(davidben): This cannot handle non-blocking writes. */
  644. int ret;
  645. if (frag->msg_header.is_ccs) {
  646. ret = dtls1_write_change_cipher_spec(ssl, use_epoch);
  647. } else {
  648. /* Restore the message body.
  649. * TODO(davidben): Make this less stateful. */
  650. memcpy(ssl->init_buf->data, frag->fragment,
  651. frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
  652. ssl->init_num = frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH;
  653. dtls1_set_message_header(ssl, frag->msg_header.type,
  654. frag->msg_header.msg_len, frag->msg_header.seq,
  655. 0, frag->msg_header.frag_len);
  656. ret = dtls1_do_handshake_write(ssl, use_epoch);
  657. }
  658. /* TODO(davidben): Check return value? */
  659. (void)BIO_flush(SSL_get_wbio(ssl));
  660. return ret;
  661. }
  662. int dtls1_retransmit_buffered_messages(SSL *ssl) {
  663. pqueue sent = ssl->d1->sent_messages;
  664. piterator iter = pqueue_iterator(sent);
  665. pitem *item;
  666. for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
  667. hm_fragment *frag = (hm_fragment *)item->data;
  668. if (dtls1_retransmit_message(ssl, frag) <= 0) {
  669. return -1;
  670. }
  671. }
  672. return 1;
  673. }
  674. /* dtls1_buffer_change_cipher_spec adds a ChangeCipherSpec to the current
  675. * handshake flight, ordered just before the handshake message numbered
  676. * |seq|. */
  677. static int dtls1_buffer_change_cipher_spec(SSL *ssl, uint16_t seq) {
  678. hm_fragment *frag = dtls1_hm_fragment_new(0 /* frag_len */,
  679. 0 /* no reassembly */);
  680. if (frag == NULL) {
  681. return 0;
  682. }
  683. frag->msg_header.is_ccs = 1;
  684. frag->msg_header.epoch = ssl->d1->w_epoch;
  685. uint16_t priority = dtls1_get_queue_priority(seq, 1 /* is_ccs */);
  686. uint8_t seq64be[8];
  687. memset(seq64be, 0, sizeof(seq64be));
  688. seq64be[6] = (uint8_t)(priority >> 8);
  689. seq64be[7] = (uint8_t)priority;
  690. pitem *item = pitem_new(seq64be, frag);
  691. if (item == NULL) {
  692. dtls1_hm_fragment_free(frag);
  693. return 0;
  694. }
  695. pqueue_insert(ssl->d1->sent_messages, item);
  696. return 1;
  697. }
  698. int dtls1_buffer_message(SSL *ssl) {
  699. /* this function is called immediately after a message has
  700. * been serialized */
  701. assert(ssl->init_off == 0);
  702. hm_fragment *frag = dtls1_hm_fragment_new(ssl->init_num, 0);
  703. if (!frag) {
  704. return 0;
  705. }
  706. memcpy(frag->fragment, ssl->init_buf->data, ssl->init_num);
  707. assert(ssl->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH ==
  708. (unsigned int)ssl->init_num);
  709. frag->msg_header.msg_len = ssl->d1->w_msg_hdr.msg_len;
  710. frag->msg_header.seq = ssl->d1->w_msg_hdr.seq;
  711. frag->msg_header.type = ssl->d1->w_msg_hdr.type;
  712. frag->msg_header.frag_off = 0;
  713. frag->msg_header.frag_len = ssl->d1->w_msg_hdr.msg_len;
  714. frag->msg_header.is_ccs = 0;
  715. frag->msg_header.epoch = ssl->d1->w_epoch;
  716. uint16_t priority = dtls1_get_queue_priority(frag->msg_header.seq,
  717. 0 /* handshake */);
  718. uint8_t seq64be[8];
  719. memset(seq64be, 0, sizeof(seq64be));
  720. seq64be[6] = (uint8_t)(priority >> 8);
  721. seq64be[7] = (uint8_t)priority;
  722. pitem *item = pitem_new(seq64be, frag);
  723. if (item == NULL) {
  724. dtls1_hm_fragment_free(frag);
  725. return 0;
  726. }
  727. pqueue_insert(ssl->d1->sent_messages, item);
  728. return 1;
  729. }
  730. int dtls1_send_change_cipher_spec(SSL *ssl, int a, int b) {
  731. if (ssl->state == a) {
  732. /* Buffer the message to handle retransmits. */
  733. ssl->d1->handshake_write_seq = ssl->d1->next_handshake_write_seq;
  734. dtls1_buffer_change_cipher_spec(ssl, ssl->d1->handshake_write_seq);
  735. ssl->state = b;
  736. }
  737. return dtls1_write_change_cipher_spec(ssl, dtls1_use_current_epoch);
  738. }
  739. /* call this function when the buffered messages are no longer needed */
  740. void dtls1_clear_record_buffer(SSL *ssl) {
  741. pitem *item;
  742. for (item = pqueue_pop(ssl->d1->sent_messages); item != NULL;
  743. item = pqueue_pop(ssl->d1->sent_messages)) {
  744. dtls1_hm_fragment_free((hm_fragment *)item->data);
  745. pitem_free(item);
  746. }
  747. }
  748. /* don't actually do the writing, wait till the MTU has been retrieved */
  749. void dtls1_set_message_header(SSL *ssl, uint8_t mt, unsigned long len,
  750. unsigned short seq_num, unsigned long frag_off,
  751. unsigned long frag_len) {
  752. struct hm_header_st *msg_hdr = &ssl->d1->w_msg_hdr;
  753. msg_hdr->type = mt;
  754. msg_hdr->msg_len = len;
  755. msg_hdr->seq = seq_num;
  756. msg_hdr->frag_off = frag_off;
  757. msg_hdr->frag_len = frag_len;
  758. }
  759. unsigned int dtls1_min_mtu(void) {
  760. return kMinMTU;
  761. }
  762. void dtls1_get_message_header(uint8_t *data,
  763. struct hm_header_st *msg_hdr) {
  764. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  765. msg_hdr->type = *(data++);
  766. n2l3(data, msg_hdr->msg_len);
  767. n2s(data, msg_hdr->seq);
  768. n2l3(data, msg_hdr->frag_off);
  769. n2l3(data, msg_hdr->frag_len);
  770. }