d1_both.c 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599
  1. /* ssl/d1_both.c */
  2. /*
  3. * DTLS implementation written by Nagendra Modadugu
  4. * ([email protected]) for the OpenSSL project 2005.
  5. */
  6. /* ====================================================================
  7. * Copyright (c) 1998-2018 The OpenSSL Project. All rights reserved.
  8. *
  9. * Redistribution and use in source and binary forms, with or without
  10. * modification, are permitted provided that the following conditions
  11. * are met:
  12. *
  13. * 1. Redistributions of source code must retain the above copyright
  14. * notice, this list of conditions and the following disclaimer.
  15. *
  16. * 2. Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in
  18. * the documentation and/or other materials provided with the
  19. * distribution.
  20. *
  21. * 3. All advertising materials mentioning features or use of this
  22. * software must display the following acknowledgment:
  23. * "This product includes software developed by the OpenSSL Project
  24. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  25. *
  26. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  27. * endorse or promote products derived from this software without
  28. * prior written permission. For written permission, please contact
  29. * [email protected].
  30. *
  31. * 5. Products derived from this software may not be called "OpenSSL"
  32. * nor may "OpenSSL" appear in their names without prior written
  33. * permission of the OpenSSL Project.
  34. *
  35. * 6. Redistributions of any form whatsoever must retain the following
  36. * acknowledgment:
  37. * "This product includes software developed by the OpenSSL Project
  38. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  41. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  43. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  44. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  45. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  46. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  47. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  49. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  50. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  51. * OF THE POSSIBILITY OF SUCH DAMAGE.
  52. * ====================================================================
  53. *
  54. * This product includes cryptographic software written by Eric Young
  55. * ([email protected]). This product includes software written by Tim
  56. * Hudson ([email protected]).
  57. *
  58. */
  59. /* Copyright (C) 1995-1998 Eric Young ([email protected])
  60. * All rights reserved.
  61. *
  62. * This package is an SSL implementation written
  63. * by Eric Young ([email protected]).
  64. * The implementation was written so as to conform with Netscapes SSL.
  65. *
  66. * This library is free for commercial and non-commercial use as long as
  67. * the following conditions are aheared to. The following conditions
  68. * apply to all code found in this distribution, be it the RC4, RSA,
  69. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  70. * included with this distribution is covered by the same copyright terms
  71. * except that the holder is Tim Hudson ([email protected]).
  72. *
  73. * Copyright remains Eric Young's, and as such any Copyright notices in
  74. * the code are not to be removed.
  75. * If this package is used in a product, Eric Young should be given attribution
  76. * as the author of the parts of the library used.
  77. * This can be in the form of a textual message at program startup or
  78. * in documentation (online or textual) provided with the package.
  79. *
  80. * Redistribution and use in source and binary forms, with or without
  81. * modification, are permitted provided that the following conditions
  82. * are met:
  83. * 1. Redistributions of source code must retain the copyright
  84. * notice, this list of conditions and the following disclaimer.
  85. * 2. Redistributions in binary form must reproduce the above copyright
  86. * notice, this list of conditions and the following disclaimer in the
  87. * documentation and/or other materials provided with the distribution.
  88. * 3. All advertising materials mentioning features or use of this software
  89. * must display the following acknowledgement:
  90. * "This product includes cryptographic software written by
  91. * Eric Young ([email protected])"
  92. * The word 'cryptographic' can be left out if the rouines from the library
  93. * being used are not cryptographic related :-).
  94. * 4. If you include any Windows specific code (or a derivative thereof) from
  95. * the apps directory (application code) you must include an acknowledgement:
  96. * "This product includes software written by Tim Hudson ([email protected])"
  97. *
  98. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  99. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  100. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  101. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  102. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  103. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  104. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  105. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  106. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  107. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  108. * SUCH DAMAGE.
  109. *
  110. * The licence and distribution terms for any publically available version or
  111. * derivative of this code cannot be changed. i.e. this code cannot simply be
  112. * copied and put under another distribution licence
  113. * [including the GNU Public Licence.]
  114. */
  115. #include <limits.h>
  116. #include <string.h>
  117. #include <stdio.h>
  118. #include "ssl_locl.h"
  119. #include <openssl/buffer.h>
  120. #include <openssl/rand.h>
  121. #include <openssl/objects.h>
  122. #include <openssl/evp.h>
  123. #include <openssl/x509.h>
  124. #define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
  125. #define RSMBLY_BITMASK_MARK(bitmask, start, end) { \
  126. if ((end) - (start) <= 8) { \
  127. long ii; \
  128. for (ii = (start); ii < (end); ii++) bitmask[((ii) >> 3)] |= (1 << ((ii) & 7)); \
  129. } else { \
  130. long ii; \
  131. bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)]; \
  132. for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) bitmask[ii] = 0xff; \
  133. bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)]; \
  134. } }
  135. #define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete) { \
  136. long ii; \
  137. OPENSSL_assert((msg_len) > 0); \
  138. is_complete = 1; \
  139. if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) is_complete = 0; \
  140. if (is_complete) for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0 ; ii--) \
  141. if (bitmask[ii] != 0xff) { is_complete = 0; break; } }
  142. #if 0
  143. # define RSMBLY_BITMASK_PRINT(bitmask, msg_len) { \
  144. long ii; \
  145. printf("bitmask: "); for (ii = 0; ii < (msg_len); ii++) \
  146. printf("%d ", (bitmask[ii >> 3] & (1 << (ii & 7))) >> (ii & 7)); \
  147. printf("\n"); }
  148. #endif
  149. static unsigned char bitmask_start_values[] =
  150. { 0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80 };
  151. static unsigned char bitmask_end_values[] =
  152. { 0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f };
  153. /* XDTLS: figure out the right values */
  154. static const unsigned int g_probable_mtu[] = { 1500, 512, 256 };
  155. static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  156. unsigned long frag_len);
  157. static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p);
  158. static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
  159. unsigned long len,
  160. unsigned short seq_num,
  161. unsigned long frag_off,
  162. unsigned long frag_len);
  163. static long dtls1_get_message_fragment(SSL *s, int st1, int stn, long max,
  164. int *ok);
  165. static hm_fragment *dtls1_hm_fragment_new(unsigned long frag_len,
  166. int reassembly)
  167. {
  168. hm_fragment *frag = NULL;
  169. unsigned char *buf = NULL;
  170. unsigned char *bitmask = NULL;
  171. frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment));
  172. if (frag == NULL)
  173. return NULL;
  174. if (frag_len) {
  175. buf = (unsigned char *)OPENSSL_malloc(frag_len);
  176. if (buf == NULL) {
  177. OPENSSL_free(frag);
  178. return NULL;
  179. }
  180. }
  181. /* zero length fragment gets zero frag->fragment */
  182. frag->fragment = buf;
  183. /* Initialize reassembly bitmask if necessary */
  184. if (reassembly) {
  185. bitmask =
  186. (unsigned char *)OPENSSL_malloc(RSMBLY_BITMASK_SIZE(frag_len));
  187. if (bitmask == NULL) {
  188. if (buf != NULL)
  189. OPENSSL_free(buf);
  190. OPENSSL_free(frag);
  191. return NULL;
  192. }
  193. memset(bitmask, 0, RSMBLY_BITMASK_SIZE(frag_len));
  194. }
  195. frag->reassembly = bitmask;
  196. return frag;
  197. }
  198. void dtls1_hm_fragment_free(hm_fragment *frag)
  199. {
  200. if (frag->msg_header.is_ccs) {
  201. EVP_CIPHER_CTX_free(frag->msg_header.
  202. saved_retransmit_state.enc_write_ctx);
  203. EVP_MD_CTX_destroy(frag->msg_header.
  204. saved_retransmit_state.write_hash);
  205. }
  206. if (frag->fragment)
  207. OPENSSL_free(frag->fragment);
  208. if (frag->reassembly)
  209. OPENSSL_free(frag->reassembly);
  210. OPENSSL_free(frag);
  211. }
  212. static int dtls1_query_mtu(SSL *s)
  213. {
  214. if (s->d1->link_mtu) {
  215. s->d1->mtu =
  216. s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
  217. s->d1->link_mtu = 0;
  218. }
  219. /* AHA! Figure out the MTU, and stick to the right size */
  220. if (s->d1->mtu < dtls1_min_mtu(s)) {
  221. if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
  222. s->d1->mtu =
  223. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  224. /*
  225. * I've seen the kernel return bogus numbers when it doesn't know
  226. * (initial write), so just make sure we have a reasonable number
  227. */
  228. if (s->d1->mtu < dtls1_min_mtu(s)) {
  229. /* Set to min mtu */
  230. s->d1->mtu = dtls1_min_mtu(s);
  231. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
  232. s->d1->mtu, NULL);
  233. }
  234. } else
  235. return 0;
  236. }
  237. return 1;
  238. }
  239. /*
  240. * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
  241. * SSL3_RT_CHANGE_CIPHER_SPEC)
  242. */
  243. int dtls1_do_write(SSL *s, int type)
  244. {
  245. int ret;
  246. unsigned int curr_mtu;
  247. int retry = 1;
  248. unsigned int len, frag_off, mac_size, blocksize, used_len;
  249. if (!dtls1_query_mtu(s))
  250. return -1;
  251. OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu(s)); /* should have something
  252. * reasonable now */
  253. if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
  254. OPENSSL_assert(s->init_num ==
  255. (int)s->d1->w_msg_hdr.msg_len +
  256. DTLS1_HM_HEADER_LENGTH);
  257. if (s->write_hash) {
  258. if (s->enc_write_ctx
  259. && EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_GCM_MODE)
  260. mac_size = 0;
  261. else
  262. mac_size = EVP_MD_CTX_size(s->write_hash);
  263. } else
  264. mac_size = 0;
  265. if (s->enc_write_ctx &&
  266. (EVP_CIPHER_CTX_mode(s->enc_write_ctx) == EVP_CIPH_CBC_MODE))
  267. blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
  268. else
  269. blocksize = 0;
  270. frag_off = 0;
  271. s->rwstate = SSL_NOTHING;
  272. /* s->init_num shouldn't ever be < 0...but just in case */
  273. while (s->init_num > 0) {
  274. if (type == SSL3_RT_HANDSHAKE && s->init_off != 0) {
  275. /* We must be writing a fragment other than the first one */
  276. if (frag_off > 0) {
  277. /* This is the first attempt at writing out this fragment */
  278. if (s->init_off <= DTLS1_HM_HEADER_LENGTH) {
  279. /*
  280. * Each fragment that was already sent must at least have
  281. * contained the message header plus one other byte.
  282. * Therefore |init_off| must have progressed by at least
  283. * |DTLS1_HM_HEADER_LENGTH + 1| bytes. If not something went
  284. * wrong.
  285. */
  286. return -1;
  287. }
  288. /*
  289. * Adjust |init_off| and |init_num| to allow room for a new
  290. * message header for this fragment.
  291. */
  292. s->init_off -= DTLS1_HM_HEADER_LENGTH;
  293. s->init_num += DTLS1_HM_HEADER_LENGTH;
  294. } else {
  295. /*
  296. * We must have been called again after a retry so use the
  297. * fragment offset from our last attempt. We do not need
  298. * to adjust |init_off| and |init_num| as above, because
  299. * that should already have been done before the retry.
  300. */
  301. frag_off = s->d1->w_msg_hdr.frag_off;
  302. }
  303. }
  304. used_len = BIO_wpending(SSL_get_wbio(s)) + DTLS1_RT_HEADER_LENGTH
  305. + mac_size + blocksize;
  306. if (s->d1->mtu > used_len)
  307. curr_mtu = s->d1->mtu - used_len;
  308. else
  309. curr_mtu = 0;
  310. if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
  311. /*
  312. * grr.. we could get an error if MTU picked was wrong
  313. */
  314. ret = BIO_flush(SSL_get_wbio(s));
  315. if (ret <= 0) {
  316. s->rwstate = SSL_WRITING;
  317. return ret;
  318. }
  319. used_len = DTLS1_RT_HEADER_LENGTH + mac_size + blocksize;
  320. if (s->d1->mtu > used_len + DTLS1_HM_HEADER_LENGTH) {
  321. curr_mtu = s->d1->mtu - used_len;
  322. } else {
  323. /* Shouldn't happen */
  324. return -1;
  325. }
  326. }
  327. /*
  328. * We just checked that s->init_num > 0 so this cast should be safe
  329. */
  330. if (((unsigned int)s->init_num) > curr_mtu)
  331. len = curr_mtu;
  332. else
  333. len = s->init_num;
  334. /* Shouldn't ever happen */
  335. if (len > INT_MAX)
  336. len = INT_MAX;
  337. /*
  338. * XDTLS: this function is too long. split out the CCS part
  339. */
  340. if (type == SSL3_RT_HANDSHAKE) {
  341. if (len < DTLS1_HM_HEADER_LENGTH) {
  342. /*
  343. * len is so small that we really can't do anything sensible
  344. * so fail
  345. */
  346. return -1;
  347. }
  348. dtls1_fix_message_header(s, frag_off,
  349. len - DTLS1_HM_HEADER_LENGTH);
  350. dtls1_write_message_header(s,
  351. (unsigned char *)&s->init_buf->
  352. data[s->init_off]);
  353. }
  354. ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off],
  355. len);
  356. if (ret < 0) {
  357. /*
  358. * might need to update MTU here, but we don't know which
  359. * previous packet caused the failure -- so can't really
  360. * retransmit anything. continue as if everything is fine and
  361. * wait for an alert to handle the retransmit
  362. */
  363. if (retry && BIO_ctrl(SSL_get_wbio(s),
  364. BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
  365. if (!(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU)) {
  366. if (!dtls1_query_mtu(s))
  367. return -1;
  368. /* Have one more go */
  369. retry = 0;
  370. } else
  371. return -1;
  372. } else {
  373. return (-1);
  374. }
  375. } else {
  376. /*
  377. * bad if this assert fails, only part of the handshake message
  378. * got sent. but why would this happen?
  379. */
  380. OPENSSL_assert(len == (unsigned int)ret);
  381. if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
  382. /*
  383. * should not be done for 'Hello Request's, but in that case
  384. * we'll ignore the result anyway
  385. */
  386. unsigned char *p =
  387. (unsigned char *)&s->init_buf->data[s->init_off];
  388. const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  389. int xlen;
  390. if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
  391. /*
  392. * reconstruct message header is if it is being sent in
  393. * single fragment
  394. */
  395. *p++ = msg_hdr->type;
  396. l2n3(msg_hdr->msg_len, p);
  397. s2n(msg_hdr->seq, p);
  398. l2n3(0, p);
  399. l2n3(msg_hdr->msg_len, p);
  400. p -= DTLS1_HM_HEADER_LENGTH;
  401. xlen = ret;
  402. } else {
  403. p += DTLS1_HM_HEADER_LENGTH;
  404. xlen = ret - DTLS1_HM_HEADER_LENGTH;
  405. }
  406. ssl3_finish_mac(s, p, xlen);
  407. }
  408. if (ret == s->init_num) {
  409. if (s->msg_callback)
  410. s->msg_callback(1, s->version, type, s->init_buf->data,
  411. (size_t)(s->init_off + s->init_num), s,
  412. s->msg_callback_arg);
  413. s->init_off = 0; /* done writing this message */
  414. s->init_num = 0;
  415. return (1);
  416. }
  417. s->init_off += ret;
  418. s->init_num -= ret;
  419. ret -= DTLS1_HM_HEADER_LENGTH;
  420. frag_off += ret;
  421. /*
  422. * We save the fragment offset for the next fragment so we have it
  423. * available in case of an IO retry. We don't know the length of the
  424. * next fragment yet so just set that to 0 for now. It will be
  425. * updated again later.
  426. */
  427. dtls1_fix_message_header(s, frag_off, 0);
  428. }
  429. }
  430. return (0);
  431. }
  432. /*
  433. * Obtain handshake message of message type 'mt' (any if mt == -1), maximum
  434. * acceptable body length 'max'. Read an entire handshake message. Handshake
  435. * messages arrive in fragments.
  436. */
  437. long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
  438. {
  439. int i, al;
  440. struct hm_header_st *msg_hdr;
  441. unsigned char *p;
  442. unsigned long msg_len;
  443. /*
  444. * s3->tmp is used to store messages that are unexpected, caused by the
  445. * absence of an optional handshake message
  446. */
  447. if (s->s3->tmp.reuse_message) {
  448. s->s3->tmp.reuse_message = 0;
  449. if ((mt >= 0) && (s->s3->tmp.message_type != mt)) {
  450. al = SSL_AD_UNEXPECTED_MESSAGE;
  451. SSLerr(SSL_F_DTLS1_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
  452. goto f_err;
  453. }
  454. *ok = 1;
  455. s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  456. s->init_num = (int)s->s3->tmp.message_size;
  457. return s->init_num;
  458. }
  459. msg_hdr = &s->d1->r_msg_hdr;
  460. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  461. again:
  462. i = dtls1_get_message_fragment(s, st1, stn, max, ok);
  463. if (i == DTLS1_HM_BAD_FRAGMENT || i == DTLS1_HM_FRAGMENT_RETRY) {
  464. /* bad fragment received */
  465. goto again;
  466. } else if (i <= 0 && !*ok) {
  467. return i;
  468. }
  469. /*
  470. * Don't change the *message* read sequence number while listening. For
  471. * the *record* write sequence we reflect the ClientHello sequence number
  472. * when listening.
  473. */
  474. if (s->d1->listen)
  475. memcpy(s->s3->write_sequence, s->s3->read_sequence,
  476. sizeof(s->s3->write_sequence));
  477. else
  478. s->d1->handshake_read_seq++;
  479. if (mt >= 0 && s->s3->tmp.message_type != mt) {
  480. al = SSL_AD_UNEXPECTED_MESSAGE;
  481. SSLerr(SSL_F_DTLS1_GET_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
  482. goto f_err;
  483. }
  484. p = (unsigned char *)s->init_buf->data;
  485. msg_len = msg_hdr->msg_len;
  486. /* reconstruct message header */
  487. *(p++) = msg_hdr->type;
  488. l2n3(msg_len, p);
  489. s2n(msg_hdr->seq, p);
  490. l2n3(0, p);
  491. l2n3(msg_len, p);
  492. if (s->version != DTLS1_BAD_VER) {
  493. p -= DTLS1_HM_HEADER_LENGTH;
  494. msg_len += DTLS1_HM_HEADER_LENGTH;
  495. }
  496. ssl3_finish_mac(s, p, msg_len);
  497. if (s->msg_callback)
  498. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  499. p, msg_len, s, s->msg_callback_arg);
  500. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  501. s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  502. return s->init_num;
  503. f_err:
  504. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  505. *ok = 0;
  506. return -1;
  507. }
  508. static int dtls1_preprocess_fragment(SSL *s, struct hm_header_st *msg_hdr,
  509. int max)
  510. {
  511. size_t frag_off, frag_len, msg_len;
  512. msg_len = msg_hdr->msg_len;
  513. frag_off = msg_hdr->frag_off;
  514. frag_len = msg_hdr->frag_len;
  515. /* sanity checking */
  516. if ((frag_off + frag_len) > msg_len) {
  517. SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  518. return SSL_AD_ILLEGAL_PARAMETER;
  519. }
  520. if ((frag_off + frag_len) > (unsigned long)max) {
  521. SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  522. return SSL_AD_ILLEGAL_PARAMETER;
  523. }
  524. if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
  525. /*
  526. * msg_len is limited to 2^24, but is effectively checked against max
  527. * above
  528. *
  529. * Make buffer slightly larger than message length as a precaution
  530. * against small OOB reads e.g. CVE-2016-6306
  531. */
  532. if (!BUF_MEM_grow_clean
  533. (s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH + 16)) {
  534. SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, ERR_R_BUF_LIB);
  535. return SSL_AD_INTERNAL_ERROR;
  536. }
  537. s->s3->tmp.message_size = msg_len;
  538. s->d1->r_msg_hdr.msg_len = msg_len;
  539. s->s3->tmp.message_type = msg_hdr->type;
  540. s->d1->r_msg_hdr.type = msg_hdr->type;
  541. s->d1->r_msg_hdr.seq = msg_hdr->seq;
  542. } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
  543. /*
  544. * They must be playing with us! BTW, failure to enforce upper limit
  545. * would open possibility for buffer overrun.
  546. */
  547. SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT, SSL_R_EXCESSIVE_MESSAGE_SIZE);
  548. return SSL_AD_ILLEGAL_PARAMETER;
  549. }
  550. return 0; /* no error */
  551. }
  552. static int dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
  553. {
  554. /*-
  555. * (0) check whether the desired fragment is available
  556. * if so:
  557. * (1) copy over the fragment to s->init_buf->data[]
  558. * (2) update s->init_num
  559. */
  560. pitem *item;
  561. hm_fragment *frag;
  562. int al;
  563. *ok = 0;
  564. do {
  565. item = pqueue_peek(s->d1->buffered_messages);
  566. if (item == NULL)
  567. return 0;
  568. frag = (hm_fragment *)item->data;
  569. if (frag->msg_header.seq < s->d1->handshake_read_seq) {
  570. /* This is a stale message that has been buffered so clear it */
  571. pqueue_pop(s->d1->buffered_messages);
  572. dtls1_hm_fragment_free(frag);
  573. pitem_free(item);
  574. item = NULL;
  575. frag = NULL;
  576. }
  577. } while (item == NULL);
  578. /* Don't return if reassembly still in progress */
  579. if (frag->reassembly != NULL)
  580. return 0;
  581. if (s->d1->handshake_read_seq == frag->msg_header.seq) {
  582. unsigned long frag_len = frag->msg_header.frag_len;
  583. pqueue_pop(s->d1->buffered_messages);
  584. al = dtls1_preprocess_fragment(s, &frag->msg_header, max);
  585. /* al will be 0 if no alert */
  586. if (al == 0 && frag->msg_header.frag_len > 0) {
  587. unsigned char *p =
  588. (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  589. memcpy(&p[frag->msg_header.frag_off], frag->fragment,
  590. frag->msg_header.frag_len);
  591. }
  592. dtls1_hm_fragment_free(frag);
  593. pitem_free(item);
  594. if (al == 0) {
  595. *ok = 1;
  596. return frag_len;
  597. }
  598. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  599. s->init_num = 0;
  600. *ok = 0;
  601. return -1;
  602. } else
  603. return 0;
  604. }
  605. /*
  606. * dtls1_max_handshake_message_len returns the maximum number of bytes
  607. * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
  608. * may be greater if the maximum certificate list size requires it.
  609. */
  610. static unsigned long dtls1_max_handshake_message_len(const SSL *s)
  611. {
  612. unsigned long max_len =
  613. DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
  614. if (max_len < (unsigned long)s->max_cert_list)
  615. return s->max_cert_list;
  616. return max_len;
  617. }
  618. static int
  619. dtls1_reassemble_fragment(SSL *s, const struct hm_header_st *msg_hdr, int *ok)
  620. {
  621. hm_fragment *frag = NULL;
  622. pitem *item = NULL;
  623. int i = -1, is_complete;
  624. unsigned char seq64be[8];
  625. unsigned long frag_len = msg_hdr->frag_len;
  626. if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len ||
  627. msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
  628. goto err;
  629. if (frag_len == 0)
  630. return DTLS1_HM_FRAGMENT_RETRY;
  631. /* Try to find item in queue */
  632. memset(seq64be, 0, sizeof(seq64be));
  633. seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
  634. seq64be[7] = (unsigned char)msg_hdr->seq;
  635. item = pqueue_find(s->d1->buffered_messages, seq64be);
  636. if (item == NULL) {
  637. frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
  638. if (frag == NULL)
  639. goto err;
  640. memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
  641. frag->msg_header.frag_len = frag->msg_header.msg_len;
  642. frag->msg_header.frag_off = 0;
  643. } else {
  644. frag = (hm_fragment *)item->data;
  645. if (frag->msg_header.msg_len != msg_hdr->msg_len) {
  646. item = NULL;
  647. frag = NULL;
  648. goto err;
  649. }
  650. }
  651. /*
  652. * If message is already reassembled, this must be a retransmit and can
  653. * be dropped. In this case item != NULL and so frag does not need to be
  654. * freed.
  655. */
  656. if (frag->reassembly == NULL) {
  657. unsigned char devnull[256];
  658. while (frag_len) {
  659. i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
  660. devnull,
  661. frag_len >
  662. sizeof(devnull) ? sizeof(devnull) :
  663. frag_len, 0);
  664. if (i <= 0)
  665. goto err;
  666. frag_len -= i;
  667. }
  668. return DTLS1_HM_FRAGMENT_RETRY;
  669. }
  670. /* read the body of the fragment (header has already been read */
  671. i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
  672. frag->fragment + msg_hdr->frag_off,
  673. frag_len, 0);
  674. if ((unsigned long)i != frag_len)
  675. i = -1;
  676. if (i <= 0)
  677. goto err;
  678. RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
  679. (long)(msg_hdr->frag_off + frag_len));
  680. RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
  681. is_complete);
  682. if (is_complete) {
  683. OPENSSL_free(frag->reassembly);
  684. frag->reassembly = NULL;
  685. }
  686. if (item == NULL) {
  687. item = pitem_new(seq64be, frag);
  688. if (item == NULL) {
  689. i = -1;
  690. goto err;
  691. }
  692. item = pqueue_insert(s->d1->buffered_messages, item);
  693. /*
  694. * pqueue_insert fails iff a duplicate item is inserted. However,
  695. * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
  696. * would have returned it and control would never have reached this
  697. * branch.
  698. */
  699. OPENSSL_assert(item != NULL);
  700. }
  701. return DTLS1_HM_FRAGMENT_RETRY;
  702. err:
  703. if (frag != NULL && item == NULL)
  704. dtls1_hm_fragment_free(frag);
  705. *ok = 0;
  706. return i;
  707. }
  708. static int
  709. dtls1_process_out_of_seq_message(SSL *s, const struct hm_header_st *msg_hdr,
  710. int *ok)
  711. {
  712. int i = -1;
  713. hm_fragment *frag = NULL;
  714. pitem *item = NULL;
  715. unsigned char seq64be[8];
  716. unsigned long frag_len = msg_hdr->frag_len;
  717. if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
  718. goto err;
  719. /* Try to find item in queue, to prevent duplicate entries */
  720. memset(seq64be, 0, sizeof(seq64be));
  721. seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
  722. seq64be[7] = (unsigned char)msg_hdr->seq;
  723. item = pqueue_find(s->d1->buffered_messages, seq64be);
  724. /*
  725. * If we already have an entry and this one is a fragment, don't discard
  726. * it and rather try to reassemble it.
  727. */
  728. if (item != NULL && frag_len != msg_hdr->msg_len)
  729. item = NULL;
  730. /*
  731. * Discard the message if sequence number was already there, is too far
  732. * in the future, already in the queue or if we received a FINISHED
  733. * before the SERVER_HELLO, which then must be a stale retransmit.
  734. */
  735. if (msg_hdr->seq <= s->d1->handshake_read_seq ||
  736. msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
  737. (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
  738. {
  739. unsigned char devnull[256];
  740. while (frag_len) {
  741. i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
  742. devnull,
  743. frag_len >
  744. sizeof(devnull) ? sizeof(devnull) :
  745. frag_len, 0);
  746. if (i <= 0)
  747. goto err;
  748. frag_len -= i;
  749. }
  750. } else {
  751. if (frag_len != msg_hdr->msg_len)
  752. return dtls1_reassemble_fragment(s, msg_hdr, ok);
  753. if (frag_len > dtls1_max_handshake_message_len(s))
  754. goto err;
  755. frag = dtls1_hm_fragment_new(frag_len, 0);
  756. if (frag == NULL)
  757. goto err;
  758. memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
  759. if (frag_len) {
  760. /*
  761. * read the body of the fragment (header has already been read
  762. */
  763. i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
  764. frag->fragment, frag_len, 0);
  765. if ((unsigned long)i != frag_len)
  766. i = -1;
  767. if (i <= 0)
  768. goto err;
  769. }
  770. item = pitem_new(seq64be, frag);
  771. if (item == NULL)
  772. goto err;
  773. item = pqueue_insert(s->d1->buffered_messages, item);
  774. /*
  775. * pqueue_insert fails iff a duplicate item is inserted. However,
  776. * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
  777. * would have returned it. Then, either |frag_len| !=
  778. * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
  779. * have been processed with |dtls1_reassemble_fragment|, above, or
  780. * the record will have been discarded.
  781. */
  782. OPENSSL_assert(item != NULL);
  783. }
  784. return DTLS1_HM_FRAGMENT_RETRY;
  785. err:
  786. if (frag != NULL && item == NULL)
  787. dtls1_hm_fragment_free(frag);
  788. *ok = 0;
  789. return i;
  790. }
  791. static long
  792. dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
  793. {
  794. unsigned char wire[DTLS1_HM_HEADER_LENGTH];
  795. unsigned long len, frag_off, frag_len;
  796. int i, al;
  797. struct hm_header_st msg_hdr;
  798. redo:
  799. /* see if we have the required fragment already */
  800. if ((frag_len = dtls1_retrieve_buffered_fragment(s, max, ok)) || *ok) {
  801. if (*ok)
  802. s->init_num = frag_len;
  803. return frag_len;
  804. }
  805. /* read handshake message header */
  806. i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE, wire,
  807. DTLS1_HM_HEADER_LENGTH, 0);
  808. if (i <= 0) { /* nbio, or an error */
  809. s->rwstate = SSL_READING;
  810. *ok = 0;
  811. return i;
  812. }
  813. /* Handshake fails if message header is incomplete */
  814. if (i != DTLS1_HM_HEADER_LENGTH) {
  815. al = SSL_AD_UNEXPECTED_MESSAGE;
  816. SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_UNEXPECTED_MESSAGE);
  817. goto f_err;
  818. }
  819. /* parse the message fragment header */
  820. dtls1_get_message_header(wire, &msg_hdr);
  821. len = msg_hdr.msg_len;
  822. frag_off = msg_hdr.frag_off;
  823. frag_len = msg_hdr.frag_len;
  824. /*
  825. * We must have at least frag_len bytes left in the record to be read.
  826. * Fragments must not span records.
  827. */
  828. if (frag_len > s->s3->rrec.length) {
  829. al = SSL3_AD_ILLEGAL_PARAMETER;
  830. SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL_R_BAD_LENGTH);
  831. goto f_err;
  832. }
  833. /*
  834. * if this is a future (or stale) message it gets buffered
  835. * (or dropped)--no further processing at this time
  836. * While listening, we accept seq 1 (ClientHello with cookie)
  837. * although we're still expecting seq 0 (ClientHello)
  838. */
  839. if (msg_hdr.seq != s->d1->handshake_read_seq
  840. && !(s->d1->listen && msg_hdr.seq == 1))
  841. return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
  842. if (frag_len && frag_len < len)
  843. return dtls1_reassemble_fragment(s, &msg_hdr, ok);
  844. if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
  845. wire[0] == SSL3_MT_HELLO_REQUEST) {
  846. /*
  847. * The server may always send 'Hello Request' messages -- we are
  848. * doing a handshake anyway now, so ignore them if their format is
  849. * correct. Does not count for 'Finished' MAC.
  850. */
  851. if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0) {
  852. if (s->msg_callback)
  853. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  854. wire, DTLS1_HM_HEADER_LENGTH, s,
  855. s->msg_callback_arg);
  856. s->init_num = 0;
  857. goto redo;
  858. } else { /* Incorrectly formated Hello request */
  859. al = SSL_AD_UNEXPECTED_MESSAGE;
  860. SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,
  861. SSL_R_UNEXPECTED_MESSAGE);
  862. goto f_err;
  863. }
  864. }
  865. if ((al = dtls1_preprocess_fragment(s, &msg_hdr, max)))
  866. goto f_err;
  867. if (frag_len > 0) {
  868. unsigned char *p =
  869. (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  870. i = s->method->ssl_read_bytes(s, SSL3_RT_HANDSHAKE,
  871. &p[frag_off], frag_len, 0);
  872. /*
  873. * This shouldn't ever fail due to NBIO because we already checked
  874. * that we have enough data in the record
  875. */
  876. if (i <= 0) {
  877. s->rwstate = SSL_READING;
  878. *ok = 0;
  879. return i;
  880. }
  881. } else
  882. i = 0;
  883. /*
  884. * XDTLS: an incorrectly formatted fragment should cause the handshake
  885. * to fail
  886. */
  887. if (i != (int)frag_len) {
  888. al = SSL3_AD_ILLEGAL_PARAMETER;
  889. SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT, SSL3_AD_ILLEGAL_PARAMETER);
  890. goto f_err;
  891. }
  892. *ok = 1;
  893. s->state = stn;
  894. /*
  895. * Note that s->init_num is *not* used as current offset in
  896. * s->init_buf->data, but as a counter summing up fragments' lengths: as
  897. * soon as they sum up to handshake packet length, we assume we have got
  898. * all the fragments.
  899. */
  900. s->init_num = frag_len;
  901. return frag_len;
  902. f_err:
  903. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  904. s->init_num = 0;
  905. *ok = 0;
  906. return (-1);
  907. }
  908. /*-
  909. * for these 2 messages, we need to
  910. * ssl->enc_read_ctx re-init
  911. * ssl->s3->read_sequence zero
  912. * ssl->s3->read_mac_secret re-init
  913. * ssl->session->read_sym_enc assign
  914. * ssl->session->read_compression assign
  915. * ssl->session->read_hash assign
  916. */
  917. int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
  918. {
  919. unsigned char *p;
  920. if (s->state == a) {
  921. p = (unsigned char *)s->init_buf->data;
  922. *p++ = SSL3_MT_CCS;
  923. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  924. s->init_num = DTLS1_CCS_HEADER_LENGTH;
  925. if (s->version == DTLS1_BAD_VER) {
  926. s->d1->next_handshake_write_seq++;
  927. s2n(s->d1->handshake_write_seq, p);
  928. s->init_num += 2;
  929. }
  930. s->init_off = 0;
  931. dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
  932. s->d1->handshake_write_seq, 0, 0);
  933. /* buffer the message to handle re-xmits */
  934. dtls1_buffer_message(s, 1);
  935. s->state = b;
  936. }
  937. /* SSL3_ST_CW_CHANGE_B */
  938. return (dtls1_do_write(s, SSL3_RT_CHANGE_CIPHER_SPEC));
  939. }
  940. int dtls1_read_failed(SSL *s, int code)
  941. {
  942. if (code > 0) {
  943. #ifdef TLS_DEBUG
  944. fprintf(stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
  945. #endif
  946. return 1;
  947. }
  948. if (!dtls1_is_timer_expired(s)) {
  949. /*
  950. * not a timeout, none of our business, let higher layers handle
  951. * this. in fact it's probably an error
  952. */
  953. return code;
  954. }
  955. #ifndef OPENSSL_NO_HEARTBEATS
  956. /* done, no need to send a retransmit */
  957. if (!SSL_in_init(s) && !s->tlsext_hb_pending)
  958. #else
  959. /* done, no need to send a retransmit */
  960. if (!SSL_in_init(s))
  961. #endif
  962. {
  963. BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
  964. return code;
  965. }
  966. #if 0 /* for now, each alert contains only one
  967. * record number */
  968. item = pqueue_peek(state->rcvd_records);
  969. if (item) {
  970. /* send an alert immediately for all the missing records */
  971. } else
  972. #endif
  973. #if 0 /* no more alert sending, just retransmit the
  974. * last set of messages */
  975. if (state->timeout.read_timeouts >= DTLS1_TMO_READ_COUNT)
  976. ssl3_send_alert(s, SSL3_AL_WARNING,
  977. DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  978. #endif
  979. return dtls1_handle_timeout(s);
  980. }
  981. int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
  982. {
  983. /*
  984. * The index of the retransmission queue actually is the message sequence
  985. * number, since the queue only contains messages of a single handshake.
  986. * However, the ChangeCipherSpec has no message sequence number and so
  987. * using only the sequence will result in the CCS and Finished having the
  988. * same index. To prevent this, the sequence number is multiplied by 2.
  989. * In case of a CCS 1 is subtracted. This does not only differ CSS and
  990. * Finished, it also maintains the order of the index (important for
  991. * priority queues) and fits in the unsigned short variable.
  992. */
  993. return seq * 2 - is_ccs;
  994. }
  995. int dtls1_retransmit_buffered_messages(SSL *s)
  996. {
  997. pqueue sent = s->d1->sent_messages;
  998. piterator iter;
  999. pitem *item;
  1000. hm_fragment *frag;
  1001. int found = 0;
  1002. iter = pqueue_iterator(sent);
  1003. for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
  1004. frag = (hm_fragment *)item->data;
  1005. if (dtls1_retransmit_message(s, (unsigned short)
  1006. dtls1_get_queue_priority
  1007. (frag->msg_header.seq,
  1008. frag->msg_header.is_ccs), 0,
  1009. &found) <= 0 && found) {
  1010. #ifdef TLS_DEBUG
  1011. fprintf(stderr, "dtls1_retransmit_message() failed\n");
  1012. #endif
  1013. return -1;
  1014. }
  1015. }
  1016. return 1;
  1017. }
  1018. int dtls1_buffer_message(SSL *s, int is_ccs)
  1019. {
  1020. pitem *item;
  1021. hm_fragment *frag;
  1022. unsigned char seq64be[8];
  1023. /*
  1024. * this function is called immediately after a message has been
  1025. * serialized
  1026. */
  1027. OPENSSL_assert(s->init_off == 0);
  1028. frag = dtls1_hm_fragment_new(s->init_num, 0);
  1029. if (!frag)
  1030. return 0;
  1031. memcpy(frag->fragment, s->init_buf->data, s->init_num);
  1032. if (is_ccs) {
  1033. /* For DTLS1_BAD_VER the header length is non-standard */
  1034. OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
  1035. ((s->version==DTLS1_BAD_VER)?3:DTLS1_CCS_HEADER_LENGTH)
  1036. == (unsigned int)s->init_num);
  1037. } else {
  1038. OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
  1039. DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
  1040. }
  1041. frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
  1042. frag->msg_header.seq = s->d1->w_msg_hdr.seq;
  1043. frag->msg_header.type = s->d1->w_msg_hdr.type;
  1044. frag->msg_header.frag_off = 0;
  1045. frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
  1046. frag->msg_header.is_ccs = is_ccs;
  1047. /* save current state */
  1048. frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
  1049. frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
  1050. frag->msg_header.saved_retransmit_state.compress = s->compress;
  1051. frag->msg_header.saved_retransmit_state.session = s->session;
  1052. frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
  1053. memset(seq64be, 0, sizeof(seq64be));
  1054. seq64be[6] =
  1055. (unsigned
  1056. char)(dtls1_get_queue_priority(frag->msg_header.seq,
  1057. frag->msg_header.is_ccs) >> 8);
  1058. seq64be[7] =
  1059. (unsigned
  1060. char)(dtls1_get_queue_priority(frag->msg_header.seq,
  1061. frag->msg_header.is_ccs));
  1062. item = pitem_new(seq64be, frag);
  1063. if (item == NULL) {
  1064. dtls1_hm_fragment_free(frag);
  1065. return 0;
  1066. }
  1067. #if 0
  1068. fprintf(stderr, "buffered messge: \ttype = %xx\n", msg_buf->type);
  1069. fprintf(stderr, "\t\t\t\t\tlen = %d\n", msg_buf->len);
  1070. fprintf(stderr, "\t\t\t\t\tseq_num = %d\n", msg_buf->seq_num);
  1071. #endif
  1072. pqueue_insert(s->d1->sent_messages, item);
  1073. return 1;
  1074. }
  1075. int
  1076. dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
  1077. int *found)
  1078. {
  1079. int ret;
  1080. /* XDTLS: for now assuming that read/writes are blocking */
  1081. pitem *item;
  1082. hm_fragment *frag;
  1083. unsigned long header_length;
  1084. unsigned char seq64be[8];
  1085. struct dtls1_retransmit_state saved_state;
  1086. unsigned char save_write_sequence[8] = {0, 0, 0, 0, 0, 0, 0, 0};
  1087. /*-
  1088. OPENSSL_assert(s->init_num == 0);
  1089. OPENSSL_assert(s->init_off == 0);
  1090. */
  1091. /* XDTLS: the requested message ought to be found, otherwise error */
  1092. memset(seq64be, 0, sizeof(seq64be));
  1093. seq64be[6] = (unsigned char)(seq >> 8);
  1094. seq64be[7] = (unsigned char)seq;
  1095. item = pqueue_find(s->d1->sent_messages, seq64be);
  1096. if (item == NULL) {
  1097. #ifdef TLS_DEBUG
  1098. fprintf(stderr, "retransmit: message %d non-existant\n", seq);
  1099. #endif
  1100. *found = 0;
  1101. return 0;
  1102. }
  1103. *found = 1;
  1104. frag = (hm_fragment *)item->data;
  1105. if (frag->msg_header.is_ccs)
  1106. header_length = DTLS1_CCS_HEADER_LENGTH;
  1107. else
  1108. header_length = DTLS1_HM_HEADER_LENGTH;
  1109. memcpy(s->init_buf->data, frag->fragment,
  1110. frag->msg_header.msg_len + header_length);
  1111. s->init_num = frag->msg_header.msg_len + header_length;
  1112. dtls1_set_message_header_int(s, frag->msg_header.type,
  1113. frag->msg_header.msg_len,
  1114. frag->msg_header.seq, 0,
  1115. frag->msg_header.frag_len);
  1116. /* save current state */
  1117. saved_state.enc_write_ctx = s->enc_write_ctx;
  1118. saved_state.write_hash = s->write_hash;
  1119. saved_state.compress = s->compress;
  1120. saved_state.session = s->session;
  1121. saved_state.epoch = s->d1->w_epoch;
  1122. saved_state.epoch = s->d1->w_epoch;
  1123. s->d1->retransmitting = 1;
  1124. /* restore state in which the message was originally sent */
  1125. s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
  1126. s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
  1127. s->compress = frag->msg_header.saved_retransmit_state.compress;
  1128. s->session = frag->msg_header.saved_retransmit_state.session;
  1129. s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
  1130. if (frag->msg_header.saved_retransmit_state.epoch ==
  1131. saved_state.epoch - 1) {
  1132. memcpy(save_write_sequence, s->s3->write_sequence,
  1133. sizeof(s->s3->write_sequence));
  1134. memcpy(s->s3->write_sequence, s->d1->last_write_sequence,
  1135. sizeof(s->s3->write_sequence));
  1136. }
  1137. ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
  1138. SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
  1139. /* restore current state */
  1140. s->enc_write_ctx = saved_state.enc_write_ctx;
  1141. s->write_hash = saved_state.write_hash;
  1142. s->compress = saved_state.compress;
  1143. s->session = saved_state.session;
  1144. s->d1->w_epoch = saved_state.epoch;
  1145. if (frag->msg_header.saved_retransmit_state.epoch ==
  1146. saved_state.epoch - 1) {
  1147. memcpy(s->d1->last_write_sequence, s->s3->write_sequence,
  1148. sizeof(s->s3->write_sequence));
  1149. memcpy(s->s3->write_sequence, save_write_sequence,
  1150. sizeof(s->s3->write_sequence));
  1151. }
  1152. s->d1->retransmitting = 0;
  1153. (void)BIO_flush(SSL_get_wbio(s));
  1154. return ret;
  1155. }
  1156. unsigned char *dtls1_set_message_header(SSL *s, unsigned char *p,
  1157. unsigned char mt, unsigned long len,
  1158. unsigned long frag_off,
  1159. unsigned long frag_len)
  1160. {
  1161. /* Don't change sequence numbers while listening */
  1162. if (frag_off == 0 && !s->d1->listen) {
  1163. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  1164. s->d1->next_handshake_write_seq++;
  1165. }
  1166. dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
  1167. frag_off, frag_len);
  1168. return p += DTLS1_HM_HEADER_LENGTH;
  1169. }
  1170. /* don't actually do the writing, wait till the MTU has been retrieved */
  1171. static void
  1172. dtls1_set_message_header_int(SSL *s, unsigned char mt,
  1173. unsigned long len, unsigned short seq_num,
  1174. unsigned long frag_off, unsigned long frag_len)
  1175. {
  1176. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1177. msg_hdr->type = mt;
  1178. msg_hdr->msg_len = len;
  1179. msg_hdr->seq = seq_num;
  1180. msg_hdr->frag_off = frag_off;
  1181. msg_hdr->frag_len = frag_len;
  1182. }
  1183. static void
  1184. dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  1185. unsigned long frag_len)
  1186. {
  1187. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1188. msg_hdr->frag_off = frag_off;
  1189. msg_hdr->frag_len = frag_len;
  1190. }
  1191. static unsigned char *dtls1_write_message_header(SSL *s, unsigned char *p)
  1192. {
  1193. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1194. *p++ = msg_hdr->type;
  1195. l2n3(msg_hdr->msg_len, p);
  1196. s2n(msg_hdr->seq, p);
  1197. l2n3(msg_hdr->frag_off, p);
  1198. l2n3(msg_hdr->frag_len, p);
  1199. return p;
  1200. }
  1201. unsigned int dtls1_link_min_mtu(void)
  1202. {
  1203. return (g_probable_mtu[(sizeof(g_probable_mtu) /
  1204. sizeof(g_probable_mtu[0])) - 1]);
  1205. }
  1206. unsigned int dtls1_min_mtu(SSL *s)
  1207. {
  1208. return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(s));
  1209. }
  1210. void
  1211. dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
  1212. {
  1213. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  1214. msg_hdr->type = *(data++);
  1215. n2l3(data, msg_hdr->msg_len);
  1216. n2s(data, msg_hdr->seq);
  1217. n2l3(data, msg_hdr->frag_off);
  1218. n2l3(data, msg_hdr->frag_len);
  1219. }
  1220. void dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
  1221. {
  1222. memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
  1223. ccs_hdr->type = *(data++);
  1224. }
  1225. int dtls1_shutdown(SSL *s)
  1226. {
  1227. int ret;
  1228. #ifndef OPENSSL_NO_SCTP
  1229. BIO *wbio;
  1230. wbio = SSL_get_wbio(s);
  1231. if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
  1232. !(s->shutdown & SSL_SENT_SHUTDOWN)) {
  1233. ret = BIO_dgram_sctp_wait_for_dry(wbio);
  1234. if (ret < 0)
  1235. return -1;
  1236. if (ret == 0)
  1237. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
  1238. NULL);
  1239. }
  1240. #endif
  1241. ret = ssl3_shutdown(s);
  1242. #ifndef OPENSSL_NO_SCTP
  1243. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
  1244. #endif
  1245. return ret;
  1246. }
  1247. #ifndef OPENSSL_NO_HEARTBEATS
  1248. int dtls1_process_heartbeat(SSL *s)
  1249. {
  1250. unsigned char *p = &s->s3->rrec.data[0], *pl;
  1251. unsigned short hbtype;
  1252. unsigned int payload;
  1253. unsigned int padding = 16; /* Use minimum padding */
  1254. if (s->msg_callback)
  1255. s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
  1256. &s->s3->rrec.data[0], s->s3->rrec.length,
  1257. s, s->msg_callback_arg);
  1258. /* Read type and payload length first */
  1259. if (1 + 2 + 16 > s->s3->rrec.length)
  1260. return 0; /* silently discard */
  1261. if (s->s3->rrec.length > SSL3_RT_MAX_PLAIN_LENGTH)
  1262. return 0; /* silently discard per RFC 6520 sec. 4 */
  1263. hbtype = *p++;
  1264. n2s(p, payload);
  1265. if (1 + 2 + payload + 16 > s->s3->rrec.length)
  1266. return 0; /* silently discard per RFC 6520 sec. 4 */
  1267. pl = p;
  1268. if (hbtype == TLS1_HB_REQUEST) {
  1269. unsigned char *buffer, *bp;
  1270. unsigned int write_length = 1 /* heartbeat type */ +
  1271. 2 /* heartbeat length */ +
  1272. payload + padding;
  1273. int r;
  1274. if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
  1275. return 0;
  1276. /*
  1277. * Allocate memory for the response, size is 1 byte message type,
  1278. * plus 2 bytes payload length, plus payload, plus padding
  1279. */
  1280. buffer = OPENSSL_malloc(write_length);
  1281. if (buffer == NULL)
  1282. return -1;
  1283. bp = buffer;
  1284. /* Enter response type, length and copy payload */
  1285. *bp++ = TLS1_HB_RESPONSE;
  1286. s2n(payload, bp);
  1287. memcpy(bp, pl, payload);
  1288. bp += payload;
  1289. /* Random padding */
  1290. if (RAND_bytes(bp, padding) <= 0) {
  1291. OPENSSL_free(buffer);
  1292. return -1;
  1293. }
  1294. r = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, write_length);
  1295. if (r >= 0 && s->msg_callback)
  1296. s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
  1297. buffer, write_length, s, s->msg_callback_arg);
  1298. OPENSSL_free(buffer);
  1299. if (r < 0)
  1300. return r;
  1301. } else if (hbtype == TLS1_HB_RESPONSE) {
  1302. unsigned int seq;
  1303. /*
  1304. * We only send sequence numbers (2 bytes unsigned int), and 16
  1305. * random bytes, so we just try to read the sequence number
  1306. */
  1307. n2s(pl, seq);
  1308. if (payload == 18 && seq == s->tlsext_hb_seq) {
  1309. dtls1_stop_timer(s);
  1310. s->tlsext_hb_seq++;
  1311. s->tlsext_hb_pending = 0;
  1312. }
  1313. }
  1314. return 0;
  1315. }
  1316. int dtls1_heartbeat(SSL *s)
  1317. {
  1318. unsigned char *buf, *p;
  1319. int ret = -1;
  1320. unsigned int payload = 18; /* Sequence number + random bytes */
  1321. unsigned int padding = 16; /* Use minimum padding */
  1322. /* Only send if peer supports and accepts HB requests... */
  1323. if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
  1324. s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS) {
  1325. SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
  1326. return -1;
  1327. }
  1328. /* ...and there is none in flight yet... */
  1329. if (s->tlsext_hb_pending) {
  1330. SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_TLS_HEARTBEAT_PENDING);
  1331. return -1;
  1332. }
  1333. /* ...and no handshake in progress. */
  1334. if (SSL_in_init(s) || s->in_handshake) {
  1335. SSLerr(SSL_F_DTLS1_HEARTBEAT, SSL_R_UNEXPECTED_MESSAGE);
  1336. return -1;
  1337. }
  1338. /*
  1339. * Check if padding is too long, payload and padding must not exceed 2^14
  1340. * - 3 = 16381 bytes in total.
  1341. */
  1342. OPENSSL_assert(payload + padding <= 16381);
  1343. /*-
  1344. * Create HeartBeat message, we just use a sequence number
  1345. * as payload to distuingish different messages and add
  1346. * some random stuff.
  1347. * - Message Type, 1 byte
  1348. * - Payload Length, 2 bytes (unsigned int)
  1349. * - Payload, the sequence number (2 bytes uint)
  1350. * - Payload, random bytes (16 bytes uint)
  1351. * - Padding
  1352. */
  1353. buf = OPENSSL_malloc(1 + 2 + payload + padding);
  1354. if (buf == NULL)
  1355. goto err;
  1356. p = buf;
  1357. /* Message Type */
  1358. *p++ = TLS1_HB_REQUEST;
  1359. /* Payload length (18 bytes here) */
  1360. s2n(payload, p);
  1361. /* Sequence number */
  1362. s2n(s->tlsext_hb_seq, p);
  1363. /* 16 random bytes */
  1364. if (RAND_bytes(p, 16) <= 0)
  1365. goto err;
  1366. p += 16;
  1367. /* Random padding */
  1368. if (RAND_bytes(p, padding) <= 0)
  1369. goto err;
  1370. ret = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
  1371. if (ret >= 0) {
  1372. if (s->msg_callback)
  1373. s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
  1374. buf, 3 + payload + padding,
  1375. s, s->msg_callback_arg);
  1376. dtls1_start_timer(s);
  1377. s->tlsext_hb_pending = 1;
  1378. }
  1379. err:
  1380. OPENSSL_free(buf);
  1381. return ret;
  1382. }
  1383. #endif