Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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