2
0

d1_both.c 53 KB

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