d1_both.c 55 KB

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