d1_both.c 51 KB

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