d1_both.c 54 KB

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