d1_both.c 43 KB

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