d1_both.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  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-2005 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[] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80};
  150. static unsigned char bitmask_end_values[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
  151. /* XDTLS: figure out the right values */
  152. static unsigned int g_probable_mtu[] = {1500 - 28, 512 - 28, 256 - 28};
  153. static unsigned int dtls1_guess_mtu(unsigned int curr_mtu);
  154. static void dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  155. unsigned long frag_len);
  156. static unsigned char *dtls1_write_message_header(SSL *s,
  157. unsigned char *p);
  158. static void dtls1_set_message_header_int(SSL *s, unsigned char mt,
  159. unsigned long len, unsigned short seq_num, unsigned long frag_off,
  160. unsigned long frag_len);
  161. static long dtls1_get_message_fragment(SSL *s, int st1, int stn,
  162. long max, int *ok);
  163. static hm_fragment *
  164. dtls1_hm_fragment_new(unsigned long frag_len, int reassembly)
  165. {
  166. hm_fragment *frag = NULL;
  167. unsigned char *buf = NULL;
  168. unsigned char *bitmask = NULL;
  169. frag = (hm_fragment *)OPENSSL_malloc(sizeof(hm_fragment));
  170. if ( frag == NULL)
  171. return NULL;
  172. if (frag_len)
  173. {
  174. buf = (unsigned char *)OPENSSL_malloc(frag_len);
  175. if ( buf == NULL)
  176. {
  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. {
  186. bitmask = (unsigned char *)OPENSSL_malloc(RSMBLY_BITMASK_SIZE(frag_len));
  187. if (bitmask == NULL)
  188. {
  189. if (buf != NULL) 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. static void
  199. dtls1_hm_fragment_free(hm_fragment *frag)
  200. {
  201. if (frag->msg_header.is_ccs)
  202. {
  203. EVP_CIPHER_CTX_free(frag->msg_header.saved_retransmit_state.enc_write_ctx);
  204. EVP_MD_CTX_destroy(frag->msg_header.saved_retransmit_state.write_hash);
  205. }
  206. if (frag->fragment) OPENSSL_free(frag->fragment);
  207. if (frag->reassembly) OPENSSL_free(frag->reassembly);
  208. OPENSSL_free(frag);
  209. }
  210. /* send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or SSL3_RT_CHANGE_CIPHER_SPEC) */
  211. int dtls1_do_write(SSL *s, int type)
  212. {
  213. int ret;
  214. int curr_mtu;
  215. unsigned int len, frag_off, mac_size, blocksize;
  216. /* AHA! Figure out the MTU, and stick to the right size */
  217. if (s->d1->mtu < dtls1_min_mtu() && !(SSL_get_options(s) & SSL_OP_NO_QUERY_MTU))
  218. {
  219. s->d1->mtu =
  220. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  221. /* I've seen the kernel return bogus numbers when it doesn't know
  222. * (initial write), so just make sure we have a reasonable number */
  223. if (s->d1->mtu < dtls1_min_mtu())
  224. {
  225. s->d1->mtu = 0;
  226. s->d1->mtu = dtls1_guess_mtu(s->d1->mtu);
  227. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SET_MTU,
  228. s->d1->mtu, NULL);
  229. }
  230. }
  231. #if 0
  232. mtu = s->d1->mtu;
  233. fprintf(stderr, "using MTU = %d\n", mtu);
  234. mtu -= (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
  235. curr_mtu = mtu - BIO_wpending(SSL_get_wbio(s));
  236. if ( curr_mtu > 0)
  237. mtu = curr_mtu;
  238. else if ( ( ret = BIO_flush(SSL_get_wbio(s))) <= 0)
  239. return ret;
  240. if ( BIO_wpending(SSL_get_wbio(s)) + s->init_num >= mtu)
  241. {
  242. ret = BIO_flush(SSL_get_wbio(s));
  243. if ( ret <= 0)
  244. return ret;
  245. mtu = s->d1->mtu - (DTLS1_HM_HEADER_LENGTH + DTLS1_RT_HEADER_LENGTH);
  246. }
  247. #endif
  248. OPENSSL_assert(s->d1->mtu >= dtls1_min_mtu()); /* should have something reasonable now */
  249. if ( s->init_off == 0 && type == SSL3_RT_HANDSHAKE)
  250. OPENSSL_assert(s->init_num ==
  251. (int)s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH);
  252. if (s->write_hash)
  253. mac_size = EVP_MD_CTX_size(s->write_hash);
  254. else
  255. mac_size = 0;
  256. if (s->enc_write_ctx &&
  257. (EVP_CIPHER_mode( s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
  258. blocksize = 2 * EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
  259. else
  260. blocksize = 0;
  261. frag_off = 0;
  262. while( s->init_num)
  263. {
  264. curr_mtu = s->d1->mtu - BIO_wpending(SSL_get_wbio(s)) -
  265. DTLS1_RT_HEADER_LENGTH - mac_size - blocksize;
  266. if ( curr_mtu <= DTLS1_HM_HEADER_LENGTH)
  267. {
  268. /* grr.. we could get an error if MTU picked was wrong */
  269. ret = BIO_flush(SSL_get_wbio(s));
  270. if ( ret <= 0)
  271. return ret;
  272. curr_mtu = s->d1->mtu - DTLS1_RT_HEADER_LENGTH -
  273. mac_size - blocksize;
  274. }
  275. if ( s->init_num > curr_mtu)
  276. len = curr_mtu;
  277. else
  278. len = s->init_num;
  279. /* XDTLS: this function is too long. split out the CCS part */
  280. if ( type == SSL3_RT_HANDSHAKE)
  281. {
  282. if ( s->init_off != 0)
  283. {
  284. OPENSSL_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. if ( s->init_num > curr_mtu)
  288. len = curr_mtu;
  289. else
  290. len = s->init_num;
  291. }
  292. dtls1_fix_message_header(s, frag_off,
  293. len - DTLS1_HM_HEADER_LENGTH);
  294. dtls1_write_message_header(s, (unsigned char *)&s->init_buf->data[s->init_off]);
  295. OPENSSL_assert(len >= DTLS1_HM_HEADER_LENGTH);
  296. }
  297. ret=dtls1_write_bytes(s,type,&s->init_buf->data[s->init_off],
  298. len);
  299. if (ret < 0)
  300. {
  301. /* might need to update MTU here, but we don't know
  302. * which previous packet caused the failure -- so can't
  303. * really retransmit anything. continue as if everything
  304. * is fine and wait for an alert to handle the
  305. * retransmit
  306. */
  307. if ( BIO_ctrl(SSL_get_wbio(s),
  308. BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0 )
  309. s->d1->mtu = BIO_ctrl(SSL_get_wbio(s),
  310. BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
  311. else
  312. return(-1);
  313. }
  314. else
  315. {
  316. /* bad if this assert fails, only part of the handshake
  317. * message got sent. but why would this happen? */
  318. OPENSSL_assert(len == (unsigned int)ret);
  319. if (type == SSL3_RT_HANDSHAKE && ! s->d1->retransmitting)
  320. {
  321. /* should not be done for 'Hello Request's, but in that case
  322. * we'll ignore the result anyway */
  323. unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];
  324. const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  325. int xlen;
  326. if (frag_off == 0 && s->version != DTLS1_BAD_VER)
  327. {
  328. /* reconstruct message header is if it
  329. * is being sent in single fragment */
  330. *p++ = msg_hdr->type;
  331. l2n3(msg_hdr->msg_len,p);
  332. s2n (msg_hdr->seq,p);
  333. l2n3(0,p);
  334. l2n3(msg_hdr->msg_len,p);
  335. p -= DTLS1_HM_HEADER_LENGTH;
  336. xlen = ret;
  337. }
  338. else
  339. {
  340. p += DTLS1_HM_HEADER_LENGTH;
  341. xlen = ret - DTLS1_HM_HEADER_LENGTH;
  342. }
  343. ssl3_finish_mac(s, p, xlen);
  344. }
  345. if (ret == s->init_num)
  346. {
  347. if (s->msg_callback)
  348. s->msg_callback(1, s->version, type, s->init_buf->data,
  349. (size_t)(s->init_off + s->init_num), s,
  350. s->msg_callback_arg);
  351. s->init_off = 0; /* done writing this message */
  352. s->init_num = 0;
  353. return(1);
  354. }
  355. s->init_off+=ret;
  356. s->init_num-=ret;
  357. frag_off += (ret -= DTLS1_HM_HEADER_LENGTH);
  358. }
  359. }
  360. return(0);
  361. }
  362. /* Obtain handshake message of message type 'mt' (any if mt == -1),
  363. * maximum acceptable body length 'max'.
  364. * Read an entire handshake message. Handshake messages arrive in
  365. * fragments.
  366. */
  367. long dtls1_get_message(SSL *s, int st1, int stn, int mt, long max, int *ok)
  368. {
  369. int i, al;
  370. struct hm_header_st *msg_hdr;
  371. unsigned char *p;
  372. unsigned long msg_len;
  373. /* s3->tmp is used to store messages that are unexpected, caused
  374. * by the absence of an optional handshake message */
  375. if (s->s3->tmp.reuse_message)
  376. {
  377. s->s3->tmp.reuse_message=0;
  378. if ((mt >= 0) && (s->s3->tmp.message_type != mt))
  379. {
  380. al=SSL_AD_UNEXPECTED_MESSAGE;
  381. SSLerr(SSL_F_DTLS1_GET_MESSAGE,SSL_R_UNEXPECTED_MESSAGE);
  382. goto f_err;
  383. }
  384. *ok=1;
  385. s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  386. s->init_num = (int)s->s3->tmp.message_size;
  387. return s->init_num;
  388. }
  389. msg_hdr = &s->d1->r_msg_hdr;
  390. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  391. again:
  392. i = dtls1_get_message_fragment(s, st1, stn, max, ok);
  393. if ( i == DTLS1_HM_BAD_FRAGMENT ||
  394. i == DTLS1_HM_FRAGMENT_RETRY) /* bad fragment received */
  395. goto again;
  396. else if ( i <= 0 && !*ok)
  397. return i;
  398. p = (unsigned char *)s->init_buf->data;
  399. msg_len = msg_hdr->msg_len;
  400. /* reconstruct message header */
  401. *(p++) = msg_hdr->type;
  402. l2n3(msg_len,p);
  403. s2n (msg_hdr->seq,p);
  404. l2n3(0,p);
  405. l2n3(msg_len,p);
  406. if (s->version != DTLS1_BAD_VER) {
  407. p -= DTLS1_HM_HEADER_LENGTH;
  408. msg_len += DTLS1_HM_HEADER_LENGTH;
  409. }
  410. ssl3_finish_mac(s, p, msg_len);
  411. if (s->msg_callback)
  412. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  413. p, msg_len,
  414. s, s->msg_callback_arg);
  415. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  416. /* Don't change sequence numbers while listening */
  417. if (!s->d1->listen)
  418. s->d1->handshake_read_seq++;
  419. s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
  420. return s->init_num;
  421. f_err:
  422. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  423. *ok = 0;
  424. return -1;
  425. }
  426. static int dtls1_preprocess_fragment(SSL *s,struct hm_header_st *msg_hdr,int max)
  427. {
  428. size_t frag_off,frag_len,msg_len;
  429. msg_len = msg_hdr->msg_len;
  430. frag_off = msg_hdr->frag_off;
  431. frag_len = msg_hdr->frag_len;
  432. /* sanity checking */
  433. if ( (frag_off+frag_len) > msg_len)
  434. {
  435. SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE);
  436. return SSL_AD_ILLEGAL_PARAMETER;
  437. }
  438. if ( (frag_off+frag_len) > (unsigned long)max)
  439. {
  440. SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE);
  441. return SSL_AD_ILLEGAL_PARAMETER;
  442. }
  443. if ( s->d1->r_msg_hdr.frag_off == 0) /* first fragment */
  444. {
  445. /* msg_len is limited to 2^24, but is effectively checked
  446. * against max above */
  447. if (!BUF_MEM_grow_clean(s->init_buf,msg_len+DTLS1_HM_HEADER_LENGTH))
  448. {
  449. SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,ERR_R_BUF_LIB);
  450. return SSL_AD_INTERNAL_ERROR;
  451. }
  452. s->s3->tmp.message_size = msg_len;
  453. s->d1->r_msg_hdr.msg_len = msg_len;
  454. s->s3->tmp.message_type = msg_hdr->type;
  455. s->d1->r_msg_hdr.type = msg_hdr->type;
  456. s->d1->r_msg_hdr.seq = msg_hdr->seq;
  457. }
  458. else if (msg_len != s->d1->r_msg_hdr.msg_len)
  459. {
  460. /* They must be playing with us! BTW, failure to enforce
  461. * upper limit would open possibility for buffer overrun. */
  462. SSLerr(SSL_F_DTLS1_PREPROCESS_FRAGMENT,SSL_R_EXCESSIVE_MESSAGE_SIZE);
  463. return SSL_AD_ILLEGAL_PARAMETER;
  464. }
  465. return 0; /* no error */
  466. }
  467. static int
  468. dtls1_retrieve_buffered_fragment(SSL *s, long max, int *ok)
  469. {
  470. /* (0) check whether the desired fragment is available
  471. * if so:
  472. * (1) copy over the fragment to s->init_buf->data[]
  473. * (2) update s->init_num
  474. */
  475. pitem *item;
  476. hm_fragment *frag;
  477. int al;
  478. *ok = 0;
  479. item = pqueue_peek(s->d1->buffered_messages);
  480. if ( item == NULL)
  481. return 0;
  482. frag = (hm_fragment *)item->data;
  483. /* Don't return if reassembly still in progress */
  484. if (frag->reassembly != NULL)
  485. return 0;
  486. if ( s->d1->handshake_read_seq == frag->msg_header.seq)
  487. {
  488. unsigned long frag_len = frag->msg_header.frag_len;
  489. pqueue_pop(s->d1->buffered_messages);
  490. al=dtls1_preprocess_fragment(s,&frag->msg_header,max);
  491. if (al==0) /* no alert */
  492. {
  493. unsigned char *p = (unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH;
  494. memcpy(&p[frag->msg_header.frag_off],
  495. frag->fragment,frag->msg_header.frag_len);
  496. }
  497. dtls1_hm_fragment_free(frag);
  498. pitem_free(item);
  499. if (al==0)
  500. {
  501. *ok = 1;
  502. return frag_len;
  503. }
  504. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  505. s->init_num = 0;
  506. *ok = 0;
  507. return -1;
  508. }
  509. else
  510. return 0;
  511. }
  512. static int
  513. dtls1_reassemble_fragment(SSL *s, struct hm_header_st* msg_hdr, int *ok)
  514. {
  515. hm_fragment *frag = NULL;
  516. pitem *item = NULL;
  517. int i = -1, is_complete;
  518. unsigned char seq64be[8];
  519. unsigned long frag_len = msg_hdr->frag_len, max_len;
  520. if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len)
  521. goto err;
  522. /* Determine maximum allowed message size. Depends on (user set)
  523. * maximum certificate length, but 16k is minimum.
  524. */
  525. if (DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH < s->max_cert_list)
  526. max_len = s->max_cert_list;
  527. else
  528. max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
  529. if ((msg_hdr->frag_off+frag_len) > max_len)
  530. goto err;
  531. /* Try to find item in queue */
  532. memset(seq64be,0,sizeof(seq64be));
  533. seq64be[6] = (unsigned char) (msg_hdr->seq>>8);
  534. seq64be[7] = (unsigned char) msg_hdr->seq;
  535. item = pqueue_find(s->d1->buffered_messages, seq64be);
  536. if (item == NULL)
  537. {
  538. frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
  539. if ( frag == NULL)
  540. goto err;
  541. memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
  542. frag->msg_header.frag_len = frag->msg_header.msg_len;
  543. frag->msg_header.frag_off = 0;
  544. }
  545. else
  546. {
  547. frag = (hm_fragment*) item->data;
  548. if (frag->msg_header.msg_len != msg_hdr->msg_len)
  549. {
  550. item = NULL;
  551. frag = NULL;
  552. goto err;
  553. }
  554. }
  555. /* If message is already reassembled, this must be a
  556. * retransmit and can be dropped.
  557. */
  558. if (frag->reassembly == NULL)
  559. {
  560. unsigned char devnull [256];
  561. while (frag_len)
  562. {
  563. i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  564. devnull,
  565. frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0);
  566. if (i<=0) goto err;
  567. frag_len -= i;
  568. }
  569. return DTLS1_HM_FRAGMENT_RETRY;
  570. }
  571. /* read the body of the fragment (header has already been read */
  572. i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  573. frag->fragment + msg_hdr->frag_off,frag_len,0);
  574. if (i<=0 || (unsigned long)i!=frag_len)
  575. goto err;
  576. RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
  577. (long)(msg_hdr->frag_off + frag_len));
  578. RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
  579. is_complete);
  580. if (is_complete)
  581. {
  582. OPENSSL_free(frag->reassembly);
  583. frag->reassembly = NULL;
  584. }
  585. if (item == NULL)
  586. {
  587. memset(seq64be,0,sizeof(seq64be));
  588. seq64be[6] = (unsigned char)(msg_hdr->seq>>8);
  589. seq64be[7] = (unsigned char)(msg_hdr->seq);
  590. item = pitem_new(seq64be, frag);
  591. if (item == NULL)
  592. {
  593. i = -1;
  594. goto err;
  595. }
  596. pqueue_insert(s->d1->buffered_messages, item);
  597. }
  598. return DTLS1_HM_FRAGMENT_RETRY;
  599. err:
  600. if (frag != NULL) dtls1_hm_fragment_free(frag);
  601. if (item != NULL) OPENSSL_free(item);
  602. *ok = 0;
  603. return i;
  604. }
  605. static int
  606. dtls1_process_out_of_seq_message(SSL *s, struct hm_header_st* msg_hdr, int *ok)
  607. {
  608. int i=-1;
  609. hm_fragment *frag = NULL;
  610. pitem *item = NULL;
  611. unsigned char seq64be[8];
  612. unsigned long frag_len = msg_hdr->frag_len;
  613. if ((msg_hdr->frag_off+frag_len) > msg_hdr->msg_len)
  614. goto err;
  615. /* Try to find item in queue, to prevent duplicate entries */
  616. memset(seq64be,0,sizeof(seq64be));
  617. seq64be[6] = (unsigned char) (msg_hdr->seq>>8);
  618. seq64be[7] = (unsigned char) msg_hdr->seq;
  619. item = pqueue_find(s->d1->buffered_messages, seq64be);
  620. /* If we already have an entry and this one is a fragment,
  621. * don't discard it and rather try to reassemble it.
  622. */
  623. if (item != NULL && frag_len < msg_hdr->msg_len)
  624. item = NULL;
  625. /* Discard the message if sequence number was already there, is
  626. * too far in the future, already in the queue or if we received
  627. * a FINISHED before the SERVER_HELLO, which then must be a stale
  628. * retransmit.
  629. */
  630. if (msg_hdr->seq <= s->d1->handshake_read_seq ||
  631. msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL ||
  632. (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED))
  633. {
  634. unsigned char devnull [256];
  635. while (frag_len)
  636. {
  637. i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  638. devnull,
  639. frag_len>sizeof(devnull)?sizeof(devnull):frag_len,0);
  640. if (i<=0) goto err;
  641. frag_len -= i;
  642. }
  643. }
  644. else
  645. {
  646. if (frag_len && frag_len < msg_hdr->msg_len)
  647. return dtls1_reassemble_fragment(s, msg_hdr, ok);
  648. frag = dtls1_hm_fragment_new(frag_len, 0);
  649. if ( frag == NULL)
  650. goto err;
  651. memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
  652. if (frag_len)
  653. {
  654. /* read the body of the fragment (header has already been read */
  655. i = s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  656. frag->fragment,frag_len,0);
  657. if (i<=0 || (unsigned long)i!=frag_len)
  658. goto err;
  659. }
  660. memset(seq64be,0,sizeof(seq64be));
  661. seq64be[6] = (unsigned char)(msg_hdr->seq>>8);
  662. seq64be[7] = (unsigned char)(msg_hdr->seq);
  663. item = pitem_new(seq64be, frag);
  664. if ( item == NULL)
  665. goto err;
  666. pqueue_insert(s->d1->buffered_messages, item);
  667. }
  668. return DTLS1_HM_FRAGMENT_RETRY;
  669. err:
  670. if ( frag != NULL) dtls1_hm_fragment_free(frag);
  671. if ( item != NULL) OPENSSL_free(item);
  672. *ok = 0;
  673. return i;
  674. }
  675. static long
  676. dtls1_get_message_fragment(SSL *s, int st1, int stn, long max, int *ok)
  677. {
  678. unsigned char wire[DTLS1_HM_HEADER_LENGTH];
  679. unsigned long len, frag_off, frag_len;
  680. int i,al;
  681. struct hm_header_st msg_hdr;
  682. redo:
  683. /* see if we have the required fragment already */
  684. if ((frag_len = dtls1_retrieve_buffered_fragment(s,max,ok)) || *ok)
  685. {
  686. if (*ok) s->init_num = frag_len;
  687. return frag_len;
  688. }
  689. /* read handshake message header */
  690. i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,wire,
  691. DTLS1_HM_HEADER_LENGTH, 0);
  692. if (i <= 0) /* nbio, or an error */
  693. {
  694. s->rwstate=SSL_READING;
  695. *ok = 0;
  696. return i;
  697. }
  698. /* Handshake fails if message header is incomplete */
  699. if (i != DTLS1_HM_HEADER_LENGTH)
  700. {
  701. al=SSL_AD_UNEXPECTED_MESSAGE;
  702. SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE);
  703. goto f_err;
  704. }
  705. /* parse the message fragment header */
  706. dtls1_get_message_header(wire, &msg_hdr);
  707. /*
  708. * if this is a future (or stale) message it gets buffered
  709. * (or dropped)--no further processing at this time
  710. * While listening, we accept seq 1 (ClientHello with cookie)
  711. * although we're still expecting seq 0 (ClientHello)
  712. */
  713. if (msg_hdr.seq != s->d1->handshake_read_seq && !(s->d1->listen && msg_hdr.seq == 1))
  714. return dtls1_process_out_of_seq_message(s, &msg_hdr, ok);
  715. len = msg_hdr.msg_len;
  716. frag_off = msg_hdr.frag_off;
  717. frag_len = msg_hdr.frag_len;
  718. if (frag_len && frag_len < len)
  719. return dtls1_reassemble_fragment(s, &msg_hdr, ok);
  720. if (!s->server && s->d1->r_msg_hdr.frag_off == 0 &&
  721. wire[0] == SSL3_MT_HELLO_REQUEST)
  722. {
  723. /* The server may always send 'Hello Request' messages --
  724. * we are doing a handshake anyway now, so ignore them
  725. * if their format is correct. Does not count for
  726. * 'Finished' MAC. */
  727. if (wire[1] == 0 && wire[2] == 0 && wire[3] == 0)
  728. {
  729. if (s->msg_callback)
  730. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  731. wire, DTLS1_HM_HEADER_LENGTH, s,
  732. s->msg_callback_arg);
  733. s->init_num = 0;
  734. goto redo;
  735. }
  736. else /* Incorrectly formated Hello request */
  737. {
  738. al=SSL_AD_UNEXPECTED_MESSAGE;
  739. SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL_R_UNEXPECTED_MESSAGE);
  740. goto f_err;
  741. }
  742. }
  743. if ((al=dtls1_preprocess_fragment(s,&msg_hdr,max)))
  744. goto f_err;
  745. /* XDTLS: ressurect this when restart is in place */
  746. s->state=stn;
  747. if ( frag_len > 0)
  748. {
  749. unsigned char *p=(unsigned char *)s->init_buf->data+DTLS1_HM_HEADER_LENGTH;
  750. i=s->method->ssl_read_bytes(s,SSL3_RT_HANDSHAKE,
  751. &p[frag_off],frag_len,0);
  752. /* XDTLS: fix this--message fragments cannot span multiple packets */
  753. if (i <= 0)
  754. {
  755. s->rwstate=SSL_READING;
  756. *ok = 0;
  757. return i;
  758. }
  759. }
  760. else
  761. i = 0;
  762. /* XDTLS: an incorrectly formatted fragment should cause the
  763. * handshake to fail */
  764. if (i != (int)frag_len)
  765. {
  766. al=SSL3_AD_ILLEGAL_PARAMETER;
  767. SSLerr(SSL_F_DTLS1_GET_MESSAGE_FRAGMENT,SSL3_AD_ILLEGAL_PARAMETER);
  768. goto f_err;
  769. }
  770. *ok = 1;
  771. /* Note that s->init_num is *not* used as current offset in
  772. * s->init_buf->data, but as a counter summing up fragments'
  773. * lengths: as soon as they sum up to handshake packet
  774. * length, we assume we have got all the fragments. */
  775. s->init_num = frag_len;
  776. return frag_len;
  777. f_err:
  778. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  779. s->init_num = 0;
  780. *ok=0;
  781. return(-1);
  782. }
  783. int dtls1_send_finished(SSL *s, int a, int b, const char *sender, int slen)
  784. {
  785. unsigned char *p,*d;
  786. int i;
  787. unsigned long l;
  788. if (s->state == a)
  789. {
  790. d=(unsigned char *)s->init_buf->data;
  791. p= &(d[DTLS1_HM_HEADER_LENGTH]);
  792. i=s->method->ssl3_enc->final_finish_mac(s,
  793. sender,slen,s->s3->tmp.finish_md);
  794. s->s3->tmp.finish_md_len = i;
  795. memcpy(p, s->s3->tmp.finish_md, i);
  796. p+=i;
  797. l=i;
  798. /* Copy the finished so we can use it for
  799. * renegotiation checks
  800. */
  801. if(s->type == SSL_ST_CONNECT)
  802. {
  803. OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
  804. memcpy(s->s3->previous_client_finished,
  805. s->s3->tmp.finish_md, i);
  806. s->s3->previous_client_finished_len=i;
  807. }
  808. else
  809. {
  810. OPENSSL_assert(i <= EVP_MAX_MD_SIZE);
  811. memcpy(s->s3->previous_server_finished,
  812. s->s3->tmp.finish_md, i);
  813. s->s3->previous_server_finished_len=i;
  814. }
  815. #ifdef OPENSSL_SYS_WIN16
  816. /* MSVC 1.5 does not clear the top bytes of the word unless
  817. * I do this.
  818. */
  819. l&=0xffff;
  820. #endif
  821. d = dtls1_set_message_header(s, d, SSL3_MT_FINISHED, l, 0, l);
  822. s->init_num=(int)l+DTLS1_HM_HEADER_LENGTH;
  823. s->init_off=0;
  824. /* buffer the message to handle re-xmits */
  825. dtls1_buffer_message(s, 0);
  826. s->state=b;
  827. }
  828. /* SSL3_ST_SEND_xxxxxx_HELLO_B */
  829. return(dtls1_do_write(s,SSL3_RT_HANDSHAKE));
  830. }
  831. /* for these 2 messages, we need to
  832. * ssl->enc_read_ctx re-init
  833. * ssl->s3->read_sequence zero
  834. * ssl->s3->read_mac_secret re-init
  835. * ssl->session->read_sym_enc assign
  836. * ssl->session->read_compression assign
  837. * ssl->session->read_hash assign
  838. */
  839. int dtls1_send_change_cipher_spec(SSL *s, int a, int b)
  840. {
  841. unsigned char *p;
  842. if (s->state == a)
  843. {
  844. p=(unsigned char *)s->init_buf->data;
  845. *p++=SSL3_MT_CCS;
  846. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  847. s->init_num=DTLS1_CCS_HEADER_LENGTH;
  848. if (s->version == DTLS1_BAD_VER) {
  849. s->d1->next_handshake_write_seq++;
  850. s2n(s->d1->handshake_write_seq,p);
  851. s->init_num+=2;
  852. }
  853. s->init_off=0;
  854. dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
  855. s->d1->handshake_write_seq, 0, 0);
  856. /* buffer the message to handle re-xmits */
  857. dtls1_buffer_message(s, 1);
  858. s->state=b;
  859. }
  860. /* SSL3_ST_CW_CHANGE_B */
  861. return(dtls1_do_write(s,SSL3_RT_CHANGE_CIPHER_SPEC));
  862. }
  863. static int dtls1_add_cert_to_buf(BUF_MEM *buf, unsigned long *l, X509 *x)
  864. {
  865. int n;
  866. unsigned char *p;
  867. n=i2d_X509(x,NULL);
  868. if (!BUF_MEM_grow_clean(buf,(int)(n+(*l)+3)))
  869. {
  870. SSLerr(SSL_F_DTLS1_ADD_CERT_TO_BUF,ERR_R_BUF_LIB);
  871. return 0;
  872. }
  873. p=(unsigned char *)&(buf->data[*l]);
  874. l2n3(n,p);
  875. i2d_X509(x,&p);
  876. *l+=n+3;
  877. return 1;
  878. }
  879. unsigned long dtls1_output_cert_chain(SSL *s, X509 *x)
  880. {
  881. unsigned char *p;
  882. int i;
  883. unsigned long l= 3 + DTLS1_HM_HEADER_LENGTH;
  884. BUF_MEM *buf;
  885. /* TLSv1 sends a chain with nothing in it, instead of an alert */
  886. buf=s->init_buf;
  887. if (!BUF_MEM_grow_clean(buf,10))
  888. {
  889. SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN,ERR_R_BUF_LIB);
  890. return(0);
  891. }
  892. if (x != NULL)
  893. {
  894. X509_STORE_CTX xs_ctx;
  895. if (!X509_STORE_CTX_init(&xs_ctx,s->ctx->cert_store,x,NULL))
  896. {
  897. SSLerr(SSL_F_DTLS1_OUTPUT_CERT_CHAIN,ERR_R_X509_LIB);
  898. return(0);
  899. }
  900. X509_verify_cert(&xs_ctx);
  901. /* Don't leave errors in the queue */
  902. ERR_clear_error();
  903. for (i=0; i < sk_X509_num(xs_ctx.chain); i++)
  904. {
  905. x = sk_X509_value(xs_ctx.chain, i);
  906. if (!dtls1_add_cert_to_buf(buf, &l, x))
  907. {
  908. X509_STORE_CTX_cleanup(&xs_ctx);
  909. return 0;
  910. }
  911. }
  912. X509_STORE_CTX_cleanup(&xs_ctx);
  913. }
  914. /* Thawte special :-) */
  915. for (i=0; i<sk_X509_num(s->ctx->extra_certs); i++)
  916. {
  917. x=sk_X509_value(s->ctx->extra_certs,i);
  918. if (!dtls1_add_cert_to_buf(buf, &l, x))
  919. return 0;
  920. }
  921. l-= (3 + DTLS1_HM_HEADER_LENGTH);
  922. p=(unsigned char *)&(buf->data[DTLS1_HM_HEADER_LENGTH]);
  923. l2n3(l,p);
  924. l+=3;
  925. p=(unsigned char *)&(buf->data[0]);
  926. p = dtls1_set_message_header(s, p, SSL3_MT_CERTIFICATE, l, 0, l);
  927. l+=DTLS1_HM_HEADER_LENGTH;
  928. return(l);
  929. }
  930. int dtls1_read_failed(SSL *s, int code)
  931. {
  932. if ( code > 0)
  933. {
  934. fprintf( stderr, "invalid state reached %s:%d", __FILE__, __LINE__);
  935. return 1;
  936. }
  937. if (!dtls1_is_timer_expired(s))
  938. {
  939. /* not a timeout, none of our business,
  940. let higher layers handle this. in fact it's probably an error */
  941. return code;
  942. }
  943. #ifndef OPENSSL_NO_HEARTBEATS
  944. if (!SSL_in_init(s) && !s->tlsext_hb_pending) /* done, no need to send a retransmit */
  945. #else
  946. if (!SSL_in_init(s)) /* done, no need to send a retransmit */
  947. #endif
  948. {
  949. BIO_set_flags(SSL_get_rbio(s), BIO_FLAGS_READ);
  950. return code;
  951. }
  952. #if 0 /* for now, each alert contains only one record number */
  953. item = pqueue_peek(state->rcvd_records);
  954. if ( item )
  955. {
  956. /* send an alert immediately for all the missing records */
  957. }
  958. else
  959. #endif
  960. #if 0 /* no more alert sending, just retransmit the last set of messages */
  961. if ( state->timeout.read_timeouts >= DTLS1_TMO_READ_COUNT)
  962. ssl3_send_alert(s,SSL3_AL_WARNING,
  963. DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  964. #endif
  965. return dtls1_handle_timeout(s);
  966. }
  967. int
  968. dtls1_get_queue_priority(unsigned short seq, int is_ccs)
  969. {
  970. /* The index of the retransmission queue actually is the message sequence number,
  971. * since the queue only contains messages of a single handshake. However, the
  972. * ChangeCipherSpec has no message sequence number and so using only the sequence
  973. * will result in the CCS and Finished having the same index. To prevent this,
  974. * the sequence number is multiplied by 2. In case of a CCS 1 is subtracted.
  975. * This does not only differ CSS and Finished, it also maintains the order of the
  976. * index (important for priority queues) and fits in the unsigned short variable.
  977. */
  978. return seq * 2 - is_ccs;
  979. }
  980. int
  981. dtls1_retransmit_buffered_messages(SSL *s)
  982. {
  983. pqueue sent = s->d1->sent_messages;
  984. piterator iter;
  985. pitem *item;
  986. hm_fragment *frag;
  987. int found = 0;
  988. iter = pqueue_iterator(sent);
  989. for ( item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter))
  990. {
  991. frag = (hm_fragment *)item->data;
  992. if ( dtls1_retransmit_message(s,
  993. (unsigned short)dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs),
  994. 0, &found) <= 0 && found)
  995. {
  996. fprintf(stderr, "dtls1_retransmit_message() failed\n");
  997. return -1;
  998. }
  999. }
  1000. return 1;
  1001. }
  1002. int
  1003. dtls1_buffer_message(SSL *s, int is_ccs)
  1004. {
  1005. pitem *item;
  1006. hm_fragment *frag;
  1007. unsigned char seq64be[8];
  1008. /* this function is called immediately after a message has
  1009. * been serialized */
  1010. OPENSSL_assert(s->init_off == 0);
  1011. frag = dtls1_hm_fragment_new(s->init_num, 0);
  1012. memcpy(frag->fragment, s->init_buf->data, s->init_num);
  1013. if ( is_ccs)
  1014. {
  1015. OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
  1016. ((s->version==DTLS1_VERSION)?DTLS1_CCS_HEADER_LENGTH:3) == (unsigned int)s->init_num);
  1017. }
  1018. else
  1019. {
  1020. OPENSSL_assert(s->d1->w_msg_hdr.msg_len +
  1021. DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num);
  1022. }
  1023. frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
  1024. frag->msg_header.seq = s->d1->w_msg_hdr.seq;
  1025. frag->msg_header.type = s->d1->w_msg_hdr.type;
  1026. frag->msg_header.frag_off = 0;
  1027. frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
  1028. frag->msg_header.is_ccs = is_ccs;
  1029. /* save current state*/
  1030. frag->msg_header.saved_retransmit_state.enc_write_ctx = s->enc_write_ctx;
  1031. frag->msg_header.saved_retransmit_state.write_hash = s->write_hash;
  1032. frag->msg_header.saved_retransmit_state.compress = s->compress;
  1033. frag->msg_header.saved_retransmit_state.session = s->session;
  1034. frag->msg_header.saved_retransmit_state.epoch = s->d1->w_epoch;
  1035. memset(seq64be,0,sizeof(seq64be));
  1036. seq64be[6] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,
  1037. frag->msg_header.is_ccs)>>8);
  1038. seq64be[7] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,
  1039. frag->msg_header.is_ccs));
  1040. item = pitem_new(seq64be, frag);
  1041. if ( item == NULL)
  1042. {
  1043. dtls1_hm_fragment_free(frag);
  1044. return 0;
  1045. }
  1046. #if 0
  1047. fprintf( stderr, "buffered messge: \ttype = %xx\n", msg_buf->type);
  1048. fprintf( stderr, "\t\t\t\t\tlen = %d\n", msg_buf->len);
  1049. fprintf( stderr, "\t\t\t\t\tseq_num = %d\n", msg_buf->seq_num);
  1050. #endif
  1051. pqueue_insert(s->d1->sent_messages, item);
  1052. return 1;
  1053. }
  1054. int
  1055. dtls1_retransmit_message(SSL *s, unsigned short seq, unsigned long frag_off,
  1056. int *found)
  1057. {
  1058. int ret;
  1059. /* XDTLS: for now assuming that read/writes are blocking */
  1060. pitem *item;
  1061. hm_fragment *frag ;
  1062. unsigned long header_length;
  1063. unsigned char seq64be[8];
  1064. struct dtls1_retransmit_state saved_state;
  1065. unsigned char save_write_sequence[8];
  1066. /*
  1067. OPENSSL_assert(s->init_num == 0);
  1068. OPENSSL_assert(s->init_off == 0);
  1069. */
  1070. /* XDTLS: the requested message ought to be found, otherwise error */
  1071. memset(seq64be,0,sizeof(seq64be));
  1072. seq64be[6] = (unsigned char)(seq>>8);
  1073. seq64be[7] = (unsigned char)seq;
  1074. item = pqueue_find(s->d1->sent_messages, seq64be);
  1075. if ( item == NULL)
  1076. {
  1077. fprintf(stderr, "retransmit: message %d non-existant\n", seq);
  1078. *found = 0;
  1079. return 0;
  1080. }
  1081. *found = 1;
  1082. frag = (hm_fragment *)item->data;
  1083. if ( frag->msg_header.is_ccs)
  1084. header_length = DTLS1_CCS_HEADER_LENGTH;
  1085. else
  1086. header_length = DTLS1_HM_HEADER_LENGTH;
  1087. memcpy(s->init_buf->data, frag->fragment,
  1088. frag->msg_header.msg_len + header_length);
  1089. s->init_num = frag->msg_header.msg_len + header_length;
  1090. dtls1_set_message_header_int(s, frag->msg_header.type,
  1091. frag->msg_header.msg_len, frag->msg_header.seq, 0,
  1092. frag->msg_header.frag_len);
  1093. /* save current state */
  1094. saved_state.enc_write_ctx = s->enc_write_ctx;
  1095. saved_state.write_hash = s->write_hash;
  1096. saved_state.compress = s->compress;
  1097. saved_state.session = s->session;
  1098. saved_state.epoch = s->d1->w_epoch;
  1099. saved_state.epoch = s->d1->w_epoch;
  1100. s->d1->retransmitting = 1;
  1101. /* restore state in which the message was originally sent */
  1102. s->enc_write_ctx = frag->msg_header.saved_retransmit_state.enc_write_ctx;
  1103. s->write_hash = frag->msg_header.saved_retransmit_state.write_hash;
  1104. s->compress = frag->msg_header.saved_retransmit_state.compress;
  1105. s->session = frag->msg_header.saved_retransmit_state.session;
  1106. s->d1->w_epoch = frag->msg_header.saved_retransmit_state.epoch;
  1107. if (frag->msg_header.saved_retransmit_state.epoch == saved_state.epoch - 1)
  1108. {
  1109. memcpy(save_write_sequence, s->s3->write_sequence, sizeof(s->s3->write_sequence));
  1110. memcpy(s->s3->write_sequence, s->d1->last_write_sequence, sizeof(s->s3->write_sequence));
  1111. }
  1112. ret = dtls1_do_write(s, frag->msg_header.is_ccs ?
  1113. SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
  1114. /* restore current state */
  1115. s->enc_write_ctx = saved_state.enc_write_ctx;
  1116. s->write_hash = saved_state.write_hash;
  1117. s->compress = saved_state.compress;
  1118. s->session = saved_state.session;
  1119. s->d1->w_epoch = saved_state.epoch;
  1120. if (frag->msg_header.saved_retransmit_state.epoch == saved_state.epoch - 1)
  1121. {
  1122. memcpy(s->d1->last_write_sequence, s->s3->write_sequence, sizeof(s->s3->write_sequence));
  1123. memcpy(s->s3->write_sequence, save_write_sequence, sizeof(s->s3->write_sequence));
  1124. }
  1125. s->d1->retransmitting = 0;
  1126. (void)BIO_flush(SSL_get_wbio(s));
  1127. return ret;
  1128. }
  1129. /* call this function when the buffered messages are no longer needed */
  1130. void
  1131. dtls1_clear_record_buffer(SSL *s)
  1132. {
  1133. pitem *item;
  1134. for(item = pqueue_pop(s->d1->sent_messages);
  1135. item != NULL; item = pqueue_pop(s->d1->sent_messages))
  1136. {
  1137. dtls1_hm_fragment_free((hm_fragment *)item->data);
  1138. pitem_free(item);
  1139. }
  1140. }
  1141. unsigned char *
  1142. dtls1_set_message_header(SSL *s, unsigned char *p, unsigned char mt,
  1143. unsigned long len, unsigned long frag_off, unsigned long frag_len)
  1144. {
  1145. /* Don't change sequence numbers while listening */
  1146. if (frag_off == 0 && !s->d1->listen)
  1147. {
  1148. s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
  1149. s->d1->next_handshake_write_seq++;
  1150. }
  1151. dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
  1152. frag_off, frag_len);
  1153. return p += DTLS1_HM_HEADER_LENGTH;
  1154. }
  1155. /* don't actually do the writing, wait till the MTU has been retrieved */
  1156. static void
  1157. dtls1_set_message_header_int(SSL *s, unsigned char mt,
  1158. unsigned long len, unsigned short seq_num, unsigned long frag_off,
  1159. unsigned long frag_len)
  1160. {
  1161. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1162. msg_hdr->type = mt;
  1163. msg_hdr->msg_len = len;
  1164. msg_hdr->seq = seq_num;
  1165. msg_hdr->frag_off = frag_off;
  1166. msg_hdr->frag_len = frag_len;
  1167. }
  1168. static void
  1169. dtls1_fix_message_header(SSL *s, unsigned long frag_off,
  1170. unsigned long frag_len)
  1171. {
  1172. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1173. msg_hdr->frag_off = frag_off;
  1174. msg_hdr->frag_len = frag_len;
  1175. }
  1176. static unsigned char *
  1177. dtls1_write_message_header(SSL *s, unsigned char *p)
  1178. {
  1179. struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
  1180. *p++ = msg_hdr->type;
  1181. l2n3(msg_hdr->msg_len, p);
  1182. s2n(msg_hdr->seq, p);
  1183. l2n3(msg_hdr->frag_off, p);
  1184. l2n3(msg_hdr->frag_len, p);
  1185. return p;
  1186. }
  1187. unsigned int
  1188. dtls1_min_mtu(void)
  1189. {
  1190. return (g_probable_mtu[(sizeof(g_probable_mtu) /
  1191. sizeof(g_probable_mtu[0])) - 1]);
  1192. }
  1193. static unsigned int
  1194. dtls1_guess_mtu(unsigned int curr_mtu)
  1195. {
  1196. unsigned int i;
  1197. if ( curr_mtu == 0 )
  1198. return g_probable_mtu[0] ;
  1199. for ( i = 0; i < sizeof(g_probable_mtu)/sizeof(g_probable_mtu[0]); i++)
  1200. if ( curr_mtu > g_probable_mtu[i])
  1201. return g_probable_mtu[i];
  1202. return curr_mtu;
  1203. }
  1204. void
  1205. dtls1_get_message_header(unsigned char *data, struct hm_header_st *msg_hdr)
  1206. {
  1207. memset(msg_hdr, 0x00, sizeof(struct hm_header_st));
  1208. msg_hdr->type = *(data++);
  1209. n2l3(data, msg_hdr->msg_len);
  1210. n2s(data, msg_hdr->seq);
  1211. n2l3(data, msg_hdr->frag_off);
  1212. n2l3(data, msg_hdr->frag_len);
  1213. }
  1214. void
  1215. dtls1_get_ccs_header(unsigned char *data, struct ccs_header_st *ccs_hdr)
  1216. {
  1217. memset(ccs_hdr, 0x00, sizeof(struct ccs_header_st));
  1218. ccs_hdr->type = *(data++);
  1219. }
  1220. int dtls1_shutdown(SSL *s)
  1221. {
  1222. int ret;
  1223. #ifndef OPENSSL_NO_SCTP
  1224. if (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
  1225. !(s->shutdown & SSL_SENT_SHUTDOWN))
  1226. {
  1227. ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(s));
  1228. if (ret < 0) return -1;
  1229. if (ret == 0)
  1230. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1, NULL);
  1231. }
  1232. #endif
  1233. ret = ssl3_shutdown(s);
  1234. #ifndef OPENSSL_NO_SCTP
  1235. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
  1236. #endif
  1237. return ret;
  1238. }
  1239. #ifndef OPENSSL_NO_HEARTBEATS
  1240. int
  1241. dtls1_process_heartbeat(SSL *s)
  1242. {
  1243. unsigned char *p = &s->s3->rrec.data[0], *pl;
  1244. unsigned short hbtype;
  1245. unsigned int payload;
  1246. unsigned int padding = 16; /* Use minimum padding */
  1247. if (s->msg_callback)
  1248. s->msg_callback(0, s->version, TLS1_RT_HEARTBEAT,
  1249. &s->s3->rrec.data[0], s->s3->rrec.length,
  1250. s, s->msg_callback_arg);
  1251. /* Read type and payload length first */
  1252. if (1 + 2 + 16 > s->s3->rrec.length)
  1253. return 0; /* silently discard */
  1254. hbtype = *p++;
  1255. n2s(p, payload);
  1256. if (1 + 2 + payload + 16 > s->s3->rrec.length)
  1257. return 0; /* silently discard per RFC 6520 sec. 4 */
  1258. pl = p;
  1259. if (hbtype == TLS1_HB_REQUEST)
  1260. {
  1261. unsigned char *buffer, *bp;
  1262. unsigned int write_length = 1 /* heartbeat type */ +
  1263. 2 /* heartbeat length */ +
  1264. payload + padding;
  1265. int r;
  1266. if (write_length > SSL3_RT_MAX_PLAIN_LENGTH)
  1267. return 0;
  1268. /* Allocate memory for the response, size is 1 byte
  1269. * message type, plus 2 bytes payload length, plus
  1270. * payload, plus padding
  1271. */
  1272. buffer = OPENSSL_malloc(write_length);
  1273. bp = buffer;
  1274. /* Enter response type, length and copy payload */
  1275. *bp++ = TLS1_HB_RESPONSE;
  1276. s2n(payload, bp);
  1277. memcpy(bp, pl, payload);
  1278. bp += payload;
  1279. /* Random padding */
  1280. RAND_pseudo_bytes(bp, padding);
  1281. r = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, write_length);
  1282. if (r >= 0 && s->msg_callback)
  1283. s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
  1284. buffer, write_length,
  1285. s, s->msg_callback_arg);
  1286. OPENSSL_free(buffer);
  1287. if (r < 0)
  1288. return r;
  1289. }
  1290. else if (hbtype == TLS1_HB_RESPONSE)
  1291. {
  1292. unsigned int seq;
  1293. /* We only send sequence numbers (2 bytes unsigned int),
  1294. * and 16 random bytes, so we just try to read the
  1295. * sequence number */
  1296. n2s(pl, seq);
  1297. if (payload == 18 && seq == s->tlsext_hb_seq)
  1298. {
  1299. dtls1_stop_timer(s);
  1300. s->tlsext_hb_seq++;
  1301. s->tlsext_hb_pending = 0;
  1302. }
  1303. }
  1304. return 0;
  1305. }
  1306. int
  1307. dtls1_heartbeat(SSL *s)
  1308. {
  1309. unsigned char *buf, *p;
  1310. int ret;
  1311. unsigned int payload = 18; /* Sequence number + random bytes */
  1312. unsigned int padding = 16; /* Use minimum padding */
  1313. /* Only send if peer supports and accepts HB requests... */
  1314. if (!(s->tlsext_heartbeat & SSL_TLSEXT_HB_ENABLED) ||
  1315. s->tlsext_heartbeat & SSL_TLSEXT_HB_DONT_SEND_REQUESTS)
  1316. {
  1317. SSLerr(SSL_F_DTLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PEER_DOESNT_ACCEPT);
  1318. return -1;
  1319. }
  1320. /* ...and there is none in flight yet... */
  1321. if (s->tlsext_hb_pending)
  1322. {
  1323. SSLerr(SSL_F_DTLS1_HEARTBEAT,SSL_R_TLS_HEARTBEAT_PENDING);
  1324. return -1;
  1325. }
  1326. /* ...and no handshake in progress. */
  1327. if (SSL_in_init(s) || s->in_handshake)
  1328. {
  1329. SSLerr(SSL_F_DTLS1_HEARTBEAT,SSL_R_UNEXPECTED_MESSAGE);
  1330. return -1;
  1331. }
  1332. /* Check if padding is too long, payload and padding
  1333. * must not exceed 2^14 - 3 = 16381 bytes in total.
  1334. */
  1335. OPENSSL_assert(payload + padding <= 16381);
  1336. /* Create HeartBeat message, we just use a sequence number
  1337. * as payload to distuingish different messages and add
  1338. * some random stuff.
  1339. * - Message Type, 1 byte
  1340. * - Payload Length, 2 bytes (unsigned int)
  1341. * - Payload, the sequence number (2 bytes uint)
  1342. * - Payload, random bytes (16 bytes uint)
  1343. * - Padding
  1344. */
  1345. buf = OPENSSL_malloc(1 + 2 + payload + padding);
  1346. p = buf;
  1347. /* Message Type */
  1348. *p++ = TLS1_HB_REQUEST;
  1349. /* Payload length (18 bytes here) */
  1350. s2n(payload, p);
  1351. /* Sequence number */
  1352. s2n(s->tlsext_hb_seq, p);
  1353. /* 16 random bytes */
  1354. RAND_pseudo_bytes(p, 16);
  1355. p += 16;
  1356. /* Random padding */
  1357. RAND_pseudo_bytes(p, padding);
  1358. ret = dtls1_write_bytes(s, TLS1_RT_HEARTBEAT, buf, 3 + payload + padding);
  1359. if (ret >= 0)
  1360. {
  1361. if (s->msg_callback)
  1362. s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
  1363. buf, 3 + payload + padding,
  1364. s, s->msg_callback_arg);
  1365. dtls1_start_timer(s);
  1366. s->tlsext_hb_pending = 1;
  1367. }
  1368. OPENSSL_free(buf);
  1369. return ret;
  1370. }
  1371. #endif