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.
 
 
 
 
 
 

931 rivejä
32 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 <assert.h>
  114. #include <limits.h>
  115. #include <stdio.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/obj.h>
  122. #include <openssl/rand.h>
  123. #include <openssl/x509.h>
  124. #include "internal.h"
  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. /* kMaxHandshakeBuffer is the maximum number of handshake messages ahead of the
  135. * current one to buffer. */
  136. static const unsigned int kHandshakeBufferSize = 10;
  137. static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  138. unsigned long frag_len);
  139. static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
  140. static hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len,
  141. int reassembly) {
  142. hm_fragment *frag = NULL;
  143. uint8_t *buf = NULL;
  144. uint8_t *bitmask = NULL;
  145. frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment));
  146. if (frag == NULL) {
  147. OPENSSL_PUT_ERROR(SSL, dtls1_hm_fragment_new, ERR_R_MALLOC_FAILURE);
  148. return NULL;
  149. }
  150. if (frag_len) {
  151. buf = (uint8_t *)OPENSSL_malloc(frag_len);
  152. if (buf == NULL) {
  153. OPENSSL_PUT_ERROR(SSL, dtls1_hm_fragment_new, ERR_R_MALLOC_FAILURE);
  154. OPENSSL_free(frag);
  155. return NULL;
  156. }
  157. }
  158. /* zero length fragment gets zero frag->fragment */
  159. frag->fragment = buf;
  160. /* Initialize reassembly bitmask if necessary */
  161. if (reassembly && frag_len > 0) {
  162. if (frag_len + 7 < frag_len) {
  163. OPENSSL_PUT_ERROR(SSL, dtls1_hm_fragment_new, ERR_R_OVERFLOW);
  164. return NULL;
  165. }
  166. size_t bitmask_len = (frag_len + 7) / 8;
  167. bitmask = (uint8_t *)OPENSSL_malloc(bitmask_len);
  168. if (bitmask == NULL) {
  169. OPENSSL_PUT_ERROR(SSL, dtls1_hm_fragment_new, ERR_R_MALLOC_FAILURE);
  170. if (buf != NULL) {
  171. OPENSSL_free(buf);
  172. }
  173. OPENSSL_free(frag);
  174. return NULL;
  175. }
  176. memset(bitmask, 0, bitmask_len);
  177. }
  178. frag->reassembly = bitmask;
  179. return frag;
  180. }
  181. void dtls1_hm_fragment_free(hm_fragment *frag) {
  182. if (frag->fragment) {
  183. OPENSSL_free(frag->fragment);
  184. }
  185. if (frag->reassembly) {
  186. OPENSSL_free(frag->reassembly);
  187. }
  188. OPENSSL_free(frag);
  189. }
  190. #if !defined(inline)
  191. #define inline __inline
  192. #endif
  193. /* bit_range returns a |uint8_t| with bits |start|, inclusive, to |end|,
  194. * exclusive, set. */
  195. static inline uint8_t bit_range(size_t start, size_t end) {
  196. return (uint8_t)(~((1u << start) - 1) & ((1u << end) - 1));
  197. }
  198. /* dtls1_hm_fragment_mark marks bytes |start|, inclusive, to |end|, exclusive,
  199. * as received in |frag|. If |frag| becomes complete, it clears
  200. * |frag->reassembly|. The range must be within the bounds of |frag|'s message
  201. * and |frag->reassembly| must not be NULL. */
  202. static void dtls1_hm_fragment_mark(hm_fragment *frag, size_t start,
  203. size_t end) {
  204. size_t i;
  205. size_t msg_len = frag->msg_header.msg_len;
  206. if (frag->reassembly == NULL || start > end || end > msg_len) {
  207. assert(0);
  208. return;
  209. }
  210. /* A zero-length message will never have a pending reassembly. */
  211. assert(msg_len > 0);
  212. if ((start >> 3) == (end >> 3)) {
  213. frag->reassembly[start >> 3] |= bit_range(start & 7, end & 7);
  214. } else {
  215. frag->reassembly[start >> 3] |= bit_range(start & 7, 8);
  216. for (i = (start >> 3) + 1; i < (end >> 3); i++) {
  217. frag->reassembly[i] = 0xff;
  218. }
  219. if ((end & 7) != 0) {
  220. frag->reassembly[end >> 3] |= bit_range(0, end & 7);
  221. }
  222. }
  223. /* Check if the fragment is complete. */
  224. for (i = 0; i < (msg_len >> 3); i++) {
  225. if (frag->reassembly[i] != 0xff) {
  226. return;
  227. }
  228. }
  229. if ((msg_len & 7) != 0 &&
  230. frag->reassembly[msg_len >> 3] != bit_range(0, msg_len & 7)) {
  231. return;
  232. }
  233. OPENSSL_free(frag->reassembly);
  234. frag->reassembly = NULL;
  235. }
  236. /* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
  237. * SSL3_RT_CHANGE_CIPHER_SPEC) */
  238. int dtls1_do_write(SSL *s, int type) {
  239. int ret;
  240. int curr_mtu;
  241. unsigned int len, frag_off;
  242. size_t max_overhead = 0;
  243. /* AHA! Figure out the MTU, and stick to the right size */
  244. if (s->d1->mtu < dtls1_min_mtu() &&
  245. !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
  246. long mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  247. if (mtu >= 0 && mtu <= (1 << 30) && (unsigned)mtu >= dtls1_min_mtu()) {
  248. s->d1->mtu = (unsigned)mtu;
  249. } else {
  250. s->d1->mtu = kDefaultMTU;
  251. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU, s->d1->mtu, NULL);
  252. }
  253. }
  254. /* should have something reasonable now */
  255. assert(s->d1->mtu >= dtls1_min_mtu());
  256. if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {
  257. assert(s->init_num ==
  258. (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
  259. }
  260. /* Determine the maximum overhead of the current cipher. */
  261. if (s->aead_write_ctx != NULL) {
  262. max_overhead = EVP_AEAD_max_overhead(s->aead_write_ctx->ctx.aead);
  263. if (s->aead_write_ctx->variable_nonce_included_in_record) {
  264. max_overhead += s->aead_write_ctx->variable_nonce_len;
  265. }
  266. }
  267. frag_off = 0;
  268. while (s->init_num) {
  269. /* Account for data in the buffering BIO; multiple records may be packed
  270. * into a single packet during the handshake.
  271. *
  272. * TODO(davidben): This is buggy; if the MTU is larger than the buffer size,
  273. * the large record will be split across two packets. Moreover, in that
  274. * case, the |dtls1_write_bytes| call may not return synchronously. This
  275. * will break on retry as the |s->init_off| and |s->init_num| adjustment
  276. * will run a second time. */
  277. curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
  278. DTLS1_RT_HEADER_LENGTH - max_overhead;
  279. if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
  280. /* Flush the buffer and continue with a fresh packet.
  281. *
  282. * TODO(davidben): If |BIO_flush| is not synchronous and requires multiple
  283. * calls to |dtls1_do_write|, |frag_off| will be wrong. */
  284. ret = BIO_flush(SSL_get_wbio(s));
  285. if (ret <= 0) {
  286. return ret;
  287. }
  288. assert(BIO_wpending(SSL_get_wbio(s)) == 0);
  289. curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH - max_overhead;
  290. }
  291. /* XDTLS: this function is too long. split out the CCS part */
  292. if (type == SSL3_RT_HANDSHAKE) {
  293. /* If this isn't the first fragment, reserve space to prepend a new
  294. * fragment header. This will override the body of a previous fragment. */
  295. if (s->init_off != 0) {
  296. assert(s->init_off > DTLS1_HM_HEADER_LENGTH);
  297. s->init_off -= DTLS1_HM_HEADER_LENGTH;
  298. s->init_num += DTLS1_HM_HEADER_LENGTH;
  299. }
  300. if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
  301. /* To make forward progress, the MTU must, at minimum, fit the handshake
  302. * header and one byte of handshake body. */
  303. OPENSSL_PUT_ERROR(SSL, dtls1_do_write, SSL_R_MTU_TOO_SMALL);
  304. return -1;
  305. }
  306. if (s->init_num > curr_mtu) {
  307. len = curr_mtu;
  308. } else {
  309. len = s->init_num;
  310. }
  311. assert(len >= DTLS1_HM_HEADER_LENGTH);
  312. dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH);
  313. dtls1_write_message_header(
  314. s, (uint8_t *)&s->init_buf->data[s->init_off]);
  315. } else {
  316. assert(type == SSL3_RT_CHANGE_CIPHER_SPEC);
  317. /* ChangeCipherSpec cannot be fragmented. */
  318. if (s->init_num > curr_mtu) {
  319. OPENSSL_PUT_ERROR(SSL, dtls1_do_write, SSL_R_MTU_TOO_SMALL);
  320. return -1;
  321. }
  322. len = s->init_num;
  323. }
  324. ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len);
  325. if (ret < 0) {
  326. return -1;
  327. }
  328. /* bad if this assert fails, only part of the handshake message got sent.
  329. * But why would this happen? */
  330. assert(len == (unsigned int)ret);
  331. if (ret == s->init_num) {
  332. if (s->msg_callback) {
  333. s->msg_callback(1, s->version, type, s->init_buf->data,
  334. (size_t)(s->init_off + s->init_num), s,
  335. s->msg_callback_arg);
  336. }
  337. s->init_off = 0; /* done writing this message */
  338. s->init_num = 0;
  339. return 1;
  340. }
  341. s->init_off += ret;
  342. s->init_num -= ret;
  343. frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
  344. }
  345. return 0;
  346. }
  347. /* dtls1_is_next_message_complete returns one if the next handshake message is
  348. * complete and zero otherwise. */
  349. static int dtls1_is_next_message_complete(SSL *s) {
  350. pitem *item = pqueue_peek(s->d1->buffered_messages);
  351. if (item == NULL) {
  352. return 0;
  353. }
  354. hm_fragment *frag = (hm_fragment *)item->data;
  355. assert(s->d1->handshake_read_seq <= frag->msg_header.seq);
  356. return s->d1->handshake_read_seq == frag->msg_header.seq &&
  357. frag->reassembly == NULL;
  358. }
  359. /* dtls1_discard_fragment_body discards a handshake fragment body of length
  360. * |frag_len|. It returns one on success and zero on error.
  361. *
  362. * TODO(davidben): This function will go away when ssl_read_bytes is gone from
  363. * the DTLS side. */
  364. static int dtls1_discard_fragment_body(SSL *s, size_t frag_len) {
  365. uint8_t discard[256];
  366. while (frag_len > 0) {
  367. size_t chunk = frag_len < sizeof(discard) ? frag_len : sizeof(discard);
  368. int ret = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, discard, chunk,
  369. 0);
  370. if (ret != chunk) {
  371. return 0;
  372. }
  373. frag_len -= chunk;
  374. }
  375. return 1;
  376. }
  377. /* dtls1_get_buffered_message returns the buffered message corresponding to
  378. * |msg_hdr|. If none exists, it creates a new one and inserts it in the
  379. * queue. Otherwise, it checks |msg_hdr| is consistent with the existing one. It
  380. * returns NULL on failure. The caller does not take ownership of the result. */
  381. static hm_fragment *dtls1_get_buffered_message(
  382. SSL *s, const struct hm_header_st *msg_hdr) {
  383. uint8_t seq64be[8];
  384. memset(seq64be, 0, sizeof(seq64be));
  385. seq64be[6] = (uint8_t)(msg_hdr->seq >> 8);
  386. seq64be[7] = (uint8_t)msg_hdr->seq;
  387. pitem *item = pqueue_find(s->d1->buffered_messages, seq64be);
  388. hm_fragment *frag;
  389. if (item == NULL) {
  390. /* This is the first fragment from this message. */
  391. frag = dtls1_hm_fragment_new(msg_hdr->msg_len,
  392. 1 /* reassembly buffer needed */);
  393. if (frag == NULL) {
  394. return NULL;
  395. }
  396. memcpy(&frag->msg_header, msg_hdr, sizeof(*msg_hdr));
  397. item = pitem_new(seq64be, frag);
  398. if (item == NULL) {
  399. dtls1_hm_fragment_free(frag);
  400. return NULL;
  401. }
  402. item = pqueue_insert(s->d1->buffered_messages, item);
  403. /* |pqueue_insert| fails iff a duplicate item is inserted, but |item| cannot
  404. * be a duplicate. */
  405. assert(item != NULL);
  406. } else {
  407. frag = item->data;
  408. assert(frag->msg_header.seq == msg_hdr->seq);
  409. if (frag->msg_header.type != msg_hdr->type ||
  410. frag->msg_header.msg_len != msg_hdr->msg_len) {
  411. /* The new fragment must be compatible with the previous fragments from
  412. * this message. */
  413. OPENSSL_PUT_ERROR(SSL, dtls1_get_buffered_message,
  414. SSL_R_FRAGMENT_MISMATCH);
  415. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  416. return NULL;
  417. }
  418. }
  419. return frag;
  420. }
  421. /* dtls1_max_handshake_message_len returns the maximum number of bytes
  422. * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but may
  423. * be greater if the maximum certificate list size requires it. */
  424. static size_t dtls1_max_handshake_message_len(const SSL *s) {
  425. size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
  426. if (max_len < (size_t)s->max_cert_list) {
  427. return (size_t)s->max_cert_list;
  428. }
  429. return max_len;
  430. }
  431. /* dtls1_process_fragment reads a handshake fragment and processes it. It
  432. * returns one if a fragment was successfully processed and 0 or -1 on error. */
  433. static int dtls1_process_fragment(SSL *s) {
  434. /* Read handshake message header.
  435. *
  436. * TODO(davidben): ssl_read_bytes allows splitting the fragment header and
  437. * body across two records. Change this interface to consume the fragment in
  438. * one pass. */
  439. uint8_t header[DTLS1_HM_HEADER_LENGTH];
  440. int ret = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, header,
  441. DTLS1_HM_HEADER_LENGTH, 0);
  442. if (ret <= 0) {
  443. return ret;
  444. }
  445. if (ret != DTLS1_HM_HEADER_LENGTH) {
  446. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment, SSL_R_UNEXPECTED_MESSAGE);
  447. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  448. return -1;
  449. }
  450. /* Parse the message fragment header. */
  451. struct hm_header_st msg_hdr;
  452. dtls1_get_message_header(header, &msg_hdr);
  453. const size_t frag_off = msg_hdr.frag_off;
  454. const size_t frag_len = msg_hdr.frag_len;
  455. const size_t msg_len = msg_hdr.msg_len;
  456. if (frag_off > msg_len || frag_off + frag_len < frag_off ||
  457. frag_off + frag_len > msg_len ||
  458. msg_len > dtls1_max_handshake_message_len(s)) {
  459. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment,
  460. SSL_R_EXCESSIVE_MESSAGE_SIZE);
  461. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  462. return -1;
  463. }
  464. if (msg_hdr.seq < s->d1->handshake_read_seq ||
  465. msg_hdr.seq > (unsigned)s->d1->handshake_read_seq +
  466. kHandshakeBufferSize) {
  467. /* Ignore fragments from the past, or ones too far in the future. */
  468. if (!dtls1_discard_fragment_body(s, frag_len)) {
  469. return -1;
  470. }
  471. return 1;
  472. }
  473. hm_fragment *frag = dtls1_get_buffered_message(s, &msg_hdr);
  474. if (frag == NULL) {
  475. return -1;
  476. }
  477. assert(frag->msg_header.msg_len == msg_len);
  478. if (frag->reassembly == NULL) {
  479. /* The message is already assembled. */
  480. if (!dtls1_discard_fragment_body(s, frag_len)) {
  481. return -1;
  482. }
  483. return 1;
  484. }
  485. assert(msg_len > 0);
  486. /* Read the body of the fragment. */
  487. ret = s->method->ssl_read_bytes(
  488. s, SSL3_RT_HANDSHAKE, frag->fragment + frag_off, frag_len, 0);
  489. if (ret != frag_len) {
  490. OPENSSL_PUT_ERROR(SSL, dtls1_process_fragment, SSL_R_UNEXPECTED_MESSAGE);
  491. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  492. return -1;
  493. }
  494. dtls1_hm_fragment_mark(frag, frag_off, frag_off + frag_len);
  495. return 1;
  496. }
  497. /* dtls1_get_message reads a handshake message of message type |msg_type| (any
  498. * if |msg_type| == -1), maximum acceptable body length |max|. Read an entire
  499. * handshake message. Handshake messages arrive in fragments. */
  500. long dtls1_get_message(SSL *s, int st1, int stn, int msg_type, long max,
  501. enum ssl_hash_message_t hash_message, int *ok) {
  502. pitem *item = NULL;
  503. hm_fragment *frag = NULL;
  504. int al;
  505. /* s3->tmp is used to store messages that are unexpected, caused
  506. * by the absence of an optional handshake message */
  507. if (s->s3->tmp.reuse_message) {
  508. /* A ssl_dont_hash_message call cannot be combined with reuse_message; the
  509. * ssl_dont_hash_message would have to have been applied to the previous
  510. * call. */
  511. assert(hash_message == ssl_hash_message);
  512. s->s3->tmp.reuse_message = 0;
  513. if (msg_type >= 0 && s->s3->tmp.message_type != msg_type) {
  514. al = SSL_AD_UNEXPECTED_MESSAGE;
  515. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_UNEXPECTED_MESSAGE);
  516. goto f_err;
  517. }
  518. *ok = 1;
  519. s->init_msg = (uint8_t *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  520. s->init_num = (int)s->s3->tmp.message_size;
  521. return s->init_num;
  522. }
  523. /* Process fragments until one is found. */
  524. while (!dtls1_is_next_message_complete(s)) {
  525. int ret = dtls1_process_fragment(s);
  526. if (ret <= 0) {
  527. *ok = 0;
  528. return ret;
  529. }
  530. }
  531. /* Read out the next complete handshake message. */
  532. item = pqueue_pop(s->d1->buffered_messages);
  533. assert(item != NULL);
  534. frag = (hm_fragment *)item->data;
  535. assert(s->d1->handshake_read_seq == frag->msg_header.seq);
  536. assert(frag->reassembly == NULL);
  537. if (frag->msg_header.msg_len > (size_t)max) {
  538. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  539. goto err;
  540. }
  541. CBB cbb;
  542. if (!BUF_MEM_grow(s->init_buf,
  543. (size_t)frag->msg_header.msg_len +
  544. DTLS1_HM_HEADER_LENGTH) ||
  545. !CBB_init_fixed(&cbb, (uint8_t *)s->init_buf->data, s->init_buf->max)) {
  546. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, ERR_R_MALLOC_FAILURE);
  547. goto err;
  548. }
  549. /* Reconstruct the assembled message. */
  550. size_t len;
  551. if (!CBB_add_u8(&cbb, frag->msg_header.type) ||
  552. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  553. !CBB_add_u16(&cbb, frag->msg_header.seq) ||
  554. !CBB_add_u24(&cbb, 0 /* frag_off */) ||
  555. !CBB_add_u24(&cbb, frag->msg_header.msg_len) ||
  556. !CBB_add_bytes(&cbb, frag->fragment, frag->msg_header.msg_len) ||
  557. !CBB_finish(&cbb, NULL, &len)) {
  558. CBB_cleanup(&cbb);
  559. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, ERR_R_INTERNAL_ERROR);
  560. goto err;
  561. }
  562. assert(len == (size_t)frag->msg_header.msg_len + DTLS1_HM_HEADER_LENGTH);
  563. s->d1->handshake_read_seq++;
  564. /* TODO(davidben): This function has a lot of implicit outputs. Simplify the
  565. * |ssl_get_message| API. */
  566. s->s3->tmp.message_type = frag->msg_header.type;
  567. s->s3->tmp.message_size = frag->msg_header.msg_len;
  568. s->init_msg = (uint8_t *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  569. s->init_num = frag->msg_header.msg_len;
  570. if (msg_type >= 0 && s->s3->tmp.message_type != msg_type) {
  571. al = SSL_AD_UNEXPECTED_MESSAGE;
  572. OPENSSL_PUT_ERROR(SSL, dtls1_get_message, SSL_R_UNEXPECTED_MESSAGE);
  573. goto f_err;
  574. }
  575. if (hash_message == ssl_hash_message && !ssl3_hash_current_message(s)) {
  576. goto err;
  577. }
  578. if (s->msg_callback) {
  579. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
  580. s->init_num + DTLS1_HM_HEADER_LENGTH, s,
  581. s->msg_callback_arg);
  582. }
  583. pitem_free(item);
  584. dtls1_hm_fragment_free(frag);
  585. s->state = stn;
  586. *ok = 1;
  587. return s->init_num;
  588. f_err:
  589. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  590. err:
  591. if (item != NULL) {
  592. pitem_free(item);
  593. }
  594. if (frag != NULL) {
  595. dtls1_hm_fragment_free(frag);
  596. }
  597. *ok = 0;
  598. return -1;
  599. }
  600. /* for these 2 messages, we need to
  601. * ssl->enc_read_ctx re-init
  602. * ssl->s3->read_sequence zero
  603. * ssl->s3->read_mac_secret re-init
  604. * ssl->session->read_sym_enc assign
  605. * ssl->session->read_compression assign
  606. * ssl->session->read_hash assign */
  607. int dtls1_send_change_cipher_spec(SSL *s, int a, int b) {
  608. uint8_t *p;
  609. if (s->state == a) {
  610. p = (uint8_t *)s->init_buf->data;
  611. *p++ = SSL3_MT_CCS;
  612. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  613. s->init_num = DTLS1_CCS_HEADER_LENGTH;
  614. s->init_off = 0;
  615. dtls1_set_message_header(s, SSL3_MT_CCS, 0, s->d1->handshake_write_seq, 0,
  616. 0);
  617. /* buffer the message to handle re-xmits */
  618. dtls1_buffer_message(s, 1);
  619. s->state = b;
  620. }
  621. /* SSL3_ST_CW_CHANGE_B */
  622. return dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC);
  623. }
  624. int dtls1_read_failed(SSL *s, int code) {
  625. if (code > 0) {
  626. assert(0);
  627. return 1;
  628. }
  629. if (!dtls1_is_timer_expired(s)) {
  630. /* not a timeout, none of our business, let higher layers handle this. In
  631. * fact, it's probably an error */
  632. return code;
  633. }
  634. if (!SSL_in_init(s)) {
  635. /* done, no need to send a retransmit */
  636. BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
  637. return code;
  638. }
  639. return dtls1_handle_timeout(s);
  640. }
  641. int dtls1_get_queue_priority(unsigned short seq, int is_ccs) {
  642. /* The index of the retransmission queue actually is the message sequence
  643. * number, since the queue only contains messages of a single handshake.
  644. * However, the ChangeCipherSpec has no message sequence number and so using
  645. * only the sequence will result in the CCS and Finished having the same
  646. * index. To prevent this, the sequence number is multiplied by 2. In case of
  647. * a CCS 1 is subtracted. This does not only differ CSS and Finished, it also
  648. * maintains the order of the index (important for priority queues) and fits
  649. * in the unsigned short variable. */
  650. return seq * 2 - is_ccs;
  651. }
  652. static int dtls1_retransmit_message(SSL *s, hm_fragment *frag) {
  653. int ret;
  654. /* XDTLS: for now assuming that read/writes are blocking */
  655. unsigned long header_length;
  656. uint8_t save_write_sequence[8];
  657. /* assert(s->init_num == 0);
  658. assert(s->init_off == 0); */
  659. if (frag->msg_header.is_ccs) {
  660. header_length = DTLS1_CCS_HEADER_LENGTH;
  661. } else {
  662. header_length = DTLS1_HM_HEADER_LENGTH;
  663. }
  664. memcpy(s->init_buf->data, frag->fragment,
  665. frag->msg_header.msg_len + header_length);
  666. s->init_num = frag->msg_header.msg_len + header_length;
  667. dtls1_set_message_header(s, frag->msg_header.type,
  668. frag->msg_header.msg_len, frag->msg_header.seq,
  669. 0, frag->msg_header.frag_len);
  670. /* Save current state. */
  671. SSL_AEAD_CTX *aead_write_ctx = s->aead_write_ctx;
  672. uint16_t epoch = s->d1->w_epoch;
  673. /* DTLS renegotiation is unsupported, so only epochs 0 (NULL cipher) and 1
  674. * (negotiated cipher) exist. */
  675. assert(epoch == 0 || epoch == 1);
  676. assert(frag->msg_header.epoch <= epoch);
  677. const int fragment_from_previous_epoch = (epoch == 1 &&
  678. frag->msg_header.epoch == 0);
  679. if (fragment_from_previous_epoch) {
  680. /* Rewind to the previous epoch.
  681. *
  682. * TODO(davidben): Instead of swapping out connection-global state, this
  683. * logic should pass a "use previous epoch" parameter down to lower-level
  684. * functions. */
  685. s->d1->w_epoch = frag->msg_header.epoch;
  686. s->aead_write_ctx = NULL;
  687. memcpy(save_write_sequence, s->s3->write_sequence,
  688. sizeof(s->s3->write_sequence));
  689. memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
  690. sizeof(s->s3->write_sequence));
  691. } else {
  692. /* Otherwise the messages must be from the same epoch. */
  693. assert(frag->msg_header.epoch == epoch);
  694. }
  695. ret = dtls1_do_write(s, frag->msg_header.is_ccs ? SSL3_RT_CHANGE_CIPHER_SPEC
  696. : SSL3_RT_HANDSHAKE);
  697. if (fragment_from_previous_epoch) {
  698. /* Restore the current epoch. */
  699. s->aead_write_ctx = aead_write_ctx;
  700. s->d1->w_epoch = epoch;
  701. memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
  702. sizeof(s->s3->write_sequence));
  703. memcpy(s->s3->write_sequence, save_write_sequence,
  704. sizeof(s->s3->write_sequence));
  705. }
  706. (void)BIO_flush(SSL_get_wbio(s));
  707. return ret;
  708. }
  709. int dtls1_retransmit_buffered_messages(SSL *s) {
  710. pqueue sent = s->d1->sent_messages;
  711. piterator iter = pqueue_iterator(sent);
  712. pitem *item;
  713. for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
  714. hm_fragment *frag = (hm_fragment *)item->data;
  715. if (dtls1_retransmit_message(s, frag) <= 0) {
  716. return -1;
  717. }
  718. }
  719. return 1;
  720. }
  721. int dtls1_buffer_message(SSL *s, int is_ccs) {
  722. pitem *item;
  723. hm_fragment *frag;
  724. uint8_t seq64be[8];
  725. /* this function is called immediately after a message has
  726. * been serialized */
  727. assert(s->init_off == 0);
  728. frag = dtls1_hm_fragment_new(s->init_num, 0);
  729. if (!frag) {
  730. return 0;
  731. }
  732. memcpy(frag->fragment, s->init_buf->data, s->init_num);
  733. if (is_ccs) {
  734. assert(s->d1->w_msg_hdr.msg_len + DTLS1_CCS_HEADER_LENGTH ==
  735. (unsigned int)s->init_num);
  736. } else {
  737. assert(s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH ==
  738. (unsigned int)s->init_num);
  739. }
  740. frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
  741. frag->msg_header.seq = s->d1->w_msg_hdr.seq;
  742. frag->msg_header.type = s->d1->w_msg_hdr.type;
  743. frag->msg_header.frag_off = 0;
  744. frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
  745. frag->msg_header.is_ccs = is_ccs;
  746. frag->msg_header.epoch = s->d1->w_epoch;
  747. memset(seq64be, 0, sizeof(seq64be));
  748. seq64be[6] = (uint8_t)(
  749. dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs) >>
  750. 8);
  751. seq64be[7] = (uint8_t)(
  752. dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs));
  753. item = pitem_new(seq64be, frag);
  754. if (item == NULL) {
  755. dtls1_hm_fragment_free(frag);
  756. return 0;
  757. }
  758. pqueue_insert(s->d1->sent_messages, item);
  759. return 1;
  760. }
  761. /* call this function when the buffered messages are no longer needed */
  762. void dtls1_clear_record_buffer(SSL *s) {
  763. pitem *item;
  764. for (item = pqueue_pop(s->d1->sent_messages); item != NULL;
  765. item = pqueue_pop(s->d1->sent_messages)) {
  766. dtls1_hm_fragment_free((hm_fragment *)item->data);
  767. pitem_free(item);
  768. }
  769. }
  770. /* don't actually do the writing, wait till the MTU has been retrieved */
  771. void dtls1_set_message_header(SSL *s, uint8_t mt, unsigned long len,
  772. unsigned short seq_num, unsigned long frag_off,
  773. unsigned long frag_len) {
  774. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  775. msg_hdr->type = mt;
  776. msg_hdr->msg_len = len;
  777. msg_hdr->seq = seq_num;
  778. msg_hdr->frag_off = frag_off;
  779. msg_hdr->frag_len = frag_len;
  780. }
  781. static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  782. unsigned long frag_len) {
  783. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  784. msg_hdr->frag_off = frag_off;
  785. msg_hdr->frag_len = frag_len;
  786. }
  787. static uint8_t *dtls1_write_message_header(SSL *s, uint8_t *p) {
  788. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  789. *p++ = msg_hdr->type;
  790. l2n3(msg_hdr->msg_len, p);
  791. s2n(msg_hdr->seq, p);
  792. l2n3(msg_hdr->frag_off, p);
  793. l2n3(msg_hdr->frag_len, p);
  794. return p;
  795. }
  796. unsigned int dtls1_min_mtu(void) {
  797. return kMinMTU;
  798. }
  799. void dtls1_get_message_header(uint8_t *data,
  800. struct hm_header_st *msg_hdr) {
  801. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  802. msg_hdr->type = *(data++);
  803. n2l3(data, msg_hdr->msg_len);
  804. n2s(data, msg_hdr->seq);
  805. n2l3(data, msg_hdr->frag_off);
  806. n2l3(data, msg_hdr->frag_len);
  807. }
  808. int dtls1_shutdown(SSL *s) {
  809. int ret;
  810. ret = ssl3_shutdown(s);
  811. return ret;
  812. }