d1_pkt.c 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039
  1. /* ssl/d1_pkt.c */
  2. /*
  3. * DTLS implementation written by Nagendra Modadugu
  4. * ([email protected]) for the OpenSSL project 2005.
  5. */
  6. /* ====================================================================
  7. * Copyright (c) 1998-2018 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 <stdio.h>
  116. #include <errno.h>
  117. #define USE_SOCKETS
  118. #include "ssl_locl.h"
  119. #include <openssl/evp.h>
  120. #include <openssl/buffer.h>
  121. #include <openssl/pqueue.h>
  122. #include <openssl/rand.h>
  123. /* mod 128 saturating subtract of two 64-bit values in big-endian order */
  124. static int satsub64be(const unsigned char *v1, const unsigned char *v2)
  125. {
  126. int ret, i;
  127. if (sizeof(long) == 8)
  128. do {
  129. const union {
  130. long one;
  131. char little;
  132. } is_endian = {
  133. 1
  134. };
  135. long l;
  136. if (is_endian.little)
  137. break;
  138. /* not reached on little-endians */
  139. /*
  140. * following test is redundant, because input is always aligned,
  141. * but I take no chances...
  142. */
  143. if (((size_t)v1 | (size_t)v2) & 0x7)
  144. break;
  145. l = *((long *)v1);
  146. l -= *((long *)v2);
  147. if (l > 128)
  148. return 128;
  149. else if (l < -128)
  150. return -128;
  151. else
  152. return (int)l;
  153. } while (0);
  154. ret = 0;
  155. for (i=0; i<7; i++) {
  156. if (v1[i] > v2[i]) {
  157. /* v1 is larger... but by how much? */
  158. if (v1[i] != v2[i] + 1)
  159. return 128;
  160. while (++i <= 6) {
  161. if (v1[i] != 0x00 || v2[i] != 0xff)
  162. return 128; /* too much */
  163. }
  164. /* We checked all the way to the penultimate byte,
  165. * so despite higher bytes changing we actually
  166. * know that it only changed from (e.g.)
  167. * ... (xx) ff ff ff ??
  168. * to ... (xx+1) 00 00 00 ??
  169. * so we add a 'bias' of 256 for the carry that
  170. * happened, and will eventually return
  171. * 256 + v1[7] - v2[7]. */
  172. ret = 256;
  173. break;
  174. } else if (v2[i] > v1[i]) {
  175. /* v2 is larger... but by how much? */
  176. if (v2[i] != v1[i] + 1)
  177. return -128;
  178. while (++i <= 6) {
  179. if (v2[i] != 0x00 || v1[i] != 0xff)
  180. return -128; /* too much */
  181. }
  182. /* Similar to the case above, we know it changed
  183. * from ... (xx) 00 00 00 ??
  184. * to ... (xx-1) ff ff ff ??
  185. * so we add a 'bias' of -256 for the borrow,
  186. * to return -256 + v1[7] - v2[7]. */
  187. ret = -256;
  188. }
  189. }
  190. ret += (int)v1[7] - (int)v2[7];
  191. if (ret > 128)
  192. return 128;
  193. else if (ret < -128)
  194. return -128;
  195. else
  196. return ret;
  197. }
  198. static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  199. int len, int peek);
  200. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
  201. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
  202. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  203. unsigned int *is_next_epoch);
  204. #if 0
  205. static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
  206. unsigned short *priority,
  207. unsigned long *offset);
  208. #endif
  209. static int dtls1_buffer_record(SSL *s, record_pqueue *q,
  210. unsigned char *priority);
  211. static int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap);
  212. /* copy buffered record into SSL structure */
  213. static int dtls1_copy_record(SSL *s, pitem *item)
  214. {
  215. DTLS1_RECORD_DATA *rdata;
  216. rdata = (DTLS1_RECORD_DATA *)item->data;
  217. if (s->s3->rbuf.buf != NULL)
  218. OPENSSL_free(s->s3->rbuf.buf);
  219. s->packet = rdata->packet;
  220. s->packet_length = rdata->packet_length;
  221. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  222. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  223. /* Set proper sequence number for mac calculation */
  224. memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
  225. return (1);
  226. }
  227. static int
  228. dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
  229. {
  230. DTLS1_RECORD_DATA *rdata;
  231. pitem *item;
  232. /* Limit the size of the queue to prevent DOS attacks */
  233. if (pqueue_size(queue->q) >= 100)
  234. return 0;
  235. rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
  236. item = pitem_new(priority, rdata);
  237. if (rdata == NULL || item == NULL) {
  238. if (rdata != NULL)
  239. OPENSSL_free(rdata);
  240. if (item != NULL)
  241. pitem_free(item);
  242. SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
  243. return -1;
  244. }
  245. rdata->packet = s->packet;
  246. rdata->packet_length = s->packet_length;
  247. memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
  248. memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
  249. item->data = rdata;
  250. #ifndef OPENSSL_NO_SCTP
  251. /* Store bio_dgram_sctp_rcvinfo struct */
  252. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  253. (s->state == SSL3_ST_SR_FINISHED_A
  254. || s->state == SSL3_ST_CR_FINISHED_A)) {
  255. BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
  256. sizeof(rdata->recordinfo), &rdata->recordinfo);
  257. }
  258. #endif
  259. s->packet = NULL;
  260. s->packet_length = 0;
  261. memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
  262. memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
  263. if (!ssl3_setup_buffers(s)) {
  264. SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
  265. if (rdata->rbuf.buf != NULL)
  266. OPENSSL_free(rdata->rbuf.buf);
  267. OPENSSL_free(rdata);
  268. pitem_free(item);
  269. return (-1);
  270. }
  271. if (pqueue_insert(queue->q, item) == NULL) {
  272. /* Must be a duplicate so ignore it */
  273. if (rdata->rbuf.buf != NULL)
  274. OPENSSL_free(rdata->rbuf.buf);
  275. OPENSSL_free(rdata);
  276. pitem_free(item);
  277. }
  278. return (1);
  279. }
  280. static int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
  281. {
  282. pitem *item;
  283. item = pqueue_pop(queue->q);
  284. if (item) {
  285. dtls1_copy_record(s, item);
  286. OPENSSL_free(item->data);
  287. pitem_free(item);
  288. return (1);
  289. }
  290. return (0);
  291. }
  292. /*
  293. * retrieve a buffered record that belongs to the new epoch, i.e., not
  294. * processed yet
  295. */
  296. #define dtls1_get_unprocessed_record(s) \
  297. dtls1_retrieve_buffered_record((s), \
  298. &((s)->d1->unprocessed_rcds))
  299. /*
  300. * retrieve a buffered record that belongs to the current epoch, ie,
  301. * processed
  302. */
  303. #define dtls1_get_processed_record(s) \
  304. dtls1_retrieve_buffered_record((s), \
  305. &((s)->d1->processed_rcds))
  306. static int dtls1_process_buffered_records(SSL *s)
  307. {
  308. pitem *item;
  309. SSL3_BUFFER *rb;
  310. SSL3_RECORD *rr;
  311. DTLS1_BITMAP *bitmap;
  312. unsigned int is_next_epoch;
  313. int replayok = 1;
  314. item = pqueue_peek(s->d1->unprocessed_rcds.q);
  315. if (item) {
  316. /* Check if epoch is current. */
  317. if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
  318. return 1; /* Nothing to do. */
  319. rr = &s->s3->rrec;
  320. rb = &s->s3->rbuf;
  321. if (rb->left > 0) {
  322. /*
  323. * We've still got data from the current packet to read. There could
  324. * be a record from the new epoch in it - so don't overwrite it
  325. * with the unprocessed records yet (we'll do it when we've
  326. * finished reading the current packet).
  327. */
  328. return 1;
  329. }
  330. /* Process all the records. */
  331. while (pqueue_peek(s->d1->unprocessed_rcds.q)) {
  332. dtls1_get_unprocessed_record(s);
  333. bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
  334. if (bitmap == NULL) {
  335. /*
  336. * Should not happen. This will only ever be NULL when the
  337. * current record is from a different epoch. But that cannot
  338. * be the case because we already checked the epoch above
  339. */
  340. SSLerr(SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS,
  341. ERR_R_INTERNAL_ERROR);
  342. return 0;
  343. }
  344. #ifndef OPENSSL_NO_SCTP
  345. /* Only do replay check if no SCTP bio */
  346. if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
  347. #endif
  348. {
  349. /*
  350. * Check whether this is a repeat, or aged record. We did this
  351. * check once already when we first received the record - but
  352. * we might have updated the window since then due to
  353. * records we subsequently processed.
  354. */
  355. replayok = dtls1_record_replay_check(s, bitmap);
  356. }
  357. if (!replayok || !dtls1_process_record(s, bitmap)) {
  358. /* dump this record */
  359. rr->length = 0;
  360. s->packet_length = 0;
  361. continue;
  362. }
  363. if (dtls1_buffer_record(s, &(s->d1->processed_rcds),
  364. s->s3->rrec.seq_num) < 0)
  365. return 0;
  366. }
  367. }
  368. /*
  369. * sync epoch numbers once all the unprocessed records have been
  370. * processed
  371. */
  372. s->d1->processed_rcds.epoch = s->d1->r_epoch;
  373. s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
  374. return 1;
  375. }
  376. #if 0
  377. static int dtls1_get_buffered_record(SSL *s)
  378. {
  379. pitem *item;
  380. PQ_64BIT priority =
  381. (((PQ_64BIT) s->d1->handshake_read_seq) << 32) |
  382. ((PQ_64BIT) s->d1->r_msg_hdr.frag_off);
  383. /* if we're not (re)negotiating, nothing buffered */
  384. if (!SSL_in_init(s))
  385. return 0;
  386. item = pqueue_peek(s->d1->rcvd_records);
  387. if (item && item->priority == priority) {
  388. /*
  389. * Check if we've received the record of interest. It must be a
  390. * handshake record, since data records as passed up without
  391. * buffering
  392. */
  393. DTLS1_RECORD_DATA *rdata;
  394. item = pqueue_pop(s->d1->rcvd_records);
  395. rdata = (DTLS1_RECORD_DATA *)item->data;
  396. if (s->s3->rbuf.buf != NULL)
  397. OPENSSL_free(s->s3->rbuf.buf);
  398. s->packet = rdata->packet;
  399. s->packet_length = rdata->packet_length;
  400. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  401. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  402. OPENSSL_free(item->data);
  403. pitem_free(item);
  404. /* s->d1->next_expected_seq_num++; */
  405. return (1);
  406. }
  407. return 0;
  408. }
  409. #endif
  410. static int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
  411. {
  412. int i, al;
  413. int enc_err;
  414. SSL_SESSION *sess;
  415. SSL3_RECORD *rr;
  416. unsigned int mac_size, orig_len;
  417. unsigned char md[EVP_MAX_MD_SIZE];
  418. rr = &(s->s3->rrec);
  419. sess = s->session;
  420. /*
  421. * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
  422. * and we have that many bytes in s->packet
  423. */
  424. rr->input = &(s->packet[DTLS1_RT_HEADER_LENGTH]);
  425. /*
  426. * ok, we can now read from 's->packet' data into 'rr' rr->input points
  427. * at rr->length bytes, which need to be copied into rr->data by either
  428. * the decryption or by the decompression When the data is 'copied' into
  429. * the rr->data buffer, rr->input will be pointed at the new buffer
  430. */
  431. /*
  432. * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
  433. * bytes of encrypted compressed stuff.
  434. */
  435. /* check is not needed I believe */
  436. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  437. al = SSL_AD_RECORD_OVERFLOW;
  438. SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  439. goto f_err;
  440. }
  441. /* decrypt in place in 'rr->input' */
  442. rr->data = rr->input;
  443. enc_err = s->method->ssl3_enc->enc(s, 0);
  444. /*-
  445. * enc_err is:
  446. * 0: (in non-constant time) if the record is publically invalid.
  447. * 1: if the padding is valid
  448. * -1: if the padding is invalid
  449. */
  450. if (enc_err == 0) {
  451. /* For DTLS we simply ignore bad packets. */
  452. rr->length = 0;
  453. s->packet_length = 0;
  454. goto err;
  455. }
  456. #ifdef TLS_DEBUG
  457. printf("dec %d\n", rr->length);
  458. {
  459. unsigned int z;
  460. for (z = 0; z < rr->length; z++)
  461. printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
  462. }
  463. printf("\n");
  464. #endif
  465. /* r->length is now the compressed data plus mac */
  466. if ((sess != NULL) &&
  467. (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
  468. /* s->read_hash != NULL => mac_size != -1 */
  469. unsigned char *mac = NULL;
  470. unsigned char mac_tmp[EVP_MAX_MD_SIZE];
  471. mac_size = EVP_MD_CTX_size(s->read_hash);
  472. OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
  473. /*
  474. * kludge: *_cbc_remove_padding passes padding length in rr->type
  475. */
  476. orig_len = rr->length + ((unsigned int)rr->type >> 8);
  477. /*
  478. * orig_len is the length of the record before any padding was
  479. * removed. This is public information, as is the MAC in use,
  480. * therefore we can safely process the record in a different amount
  481. * of time if it's too short to possibly contain a MAC.
  482. */
  483. if (orig_len < mac_size ||
  484. /* CBC records must have a padding length byte too. */
  485. (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  486. orig_len < mac_size + 1)) {
  487. al = SSL_AD_DECODE_ERROR;
  488. SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
  489. goto f_err;
  490. }
  491. if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
  492. /*
  493. * We update the length so that the TLS header bytes can be
  494. * constructed correctly but we need to extract the MAC in
  495. * constant time from within the record, without leaking the
  496. * contents of the padding bytes.
  497. */
  498. mac = mac_tmp;
  499. ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
  500. rr->length -= mac_size;
  501. } else {
  502. /*
  503. * In this case there's no padding, so |orig_len| equals
  504. * |rec->length| and we checked that there's enough bytes for
  505. * |mac_size| above.
  506. */
  507. rr->length -= mac_size;
  508. mac = &rr->data[rr->length];
  509. }
  510. i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
  511. if (i < 0 || mac == NULL
  512. || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
  513. enc_err = -1;
  514. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
  515. enc_err = -1;
  516. }
  517. if (enc_err < 0) {
  518. /* decryption failed, silently discard message */
  519. rr->length = 0;
  520. s->packet_length = 0;
  521. goto err;
  522. }
  523. /* r->length is now just compressed */
  524. if (s->expand != NULL) {
  525. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
  526. al = SSL_AD_RECORD_OVERFLOW;
  527. SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
  528. SSL_R_COMPRESSED_LENGTH_TOO_LONG);
  529. goto f_err;
  530. }
  531. if (!ssl3_do_uncompress(s)) {
  532. al = SSL_AD_DECOMPRESSION_FAILURE;
  533. SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
  534. goto f_err;
  535. }
  536. }
  537. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
  538. al = SSL_AD_RECORD_OVERFLOW;
  539. SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
  540. goto f_err;
  541. }
  542. rr->off = 0;
  543. /*-
  544. * So at this point the following is true
  545. * ssl->s3->rrec.type is the type of record
  546. * ssl->s3->rrec.length == number of bytes in record
  547. * ssl->s3->rrec.off == offset to first valid byte
  548. * ssl->s3->rrec.data == where to take bytes from, increment
  549. * after use :-).
  550. */
  551. /* we have pulled in a full packet so zero things */
  552. s->packet_length = 0;
  553. /* Mark receipt of record. */
  554. dtls1_record_bitmap_update(s, bitmap);
  555. return (1);
  556. f_err:
  557. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  558. err:
  559. return (0);
  560. }
  561. /*-
  562. * Call this to get a new input record.
  563. * It will return <= 0 if more data is needed, normally due to an error
  564. * or non-blocking IO.
  565. * When it finishes, one packet has been decoded and can be found in
  566. * ssl->s3->rrec.type - is the type of record
  567. * ssl->s3->rrec.data, - data
  568. * ssl->s3->rrec.length, - number of bytes
  569. */
  570. /* used only by dtls1_read_bytes */
  571. int dtls1_get_record(SSL *s)
  572. {
  573. int ssl_major, ssl_minor;
  574. int i, n;
  575. SSL3_RECORD *rr;
  576. unsigned char *p = NULL;
  577. unsigned short version;
  578. DTLS1_BITMAP *bitmap;
  579. unsigned int is_next_epoch;
  580. rr = &(s->s3->rrec);
  581. again:
  582. /*
  583. * The epoch may have changed. If so, process all the pending records.
  584. * This is a non-blocking operation.
  585. */
  586. if (!dtls1_process_buffered_records(s))
  587. return -1;
  588. /* if we're renegotiating, then there may be buffered records */
  589. if (dtls1_get_processed_record(s))
  590. return 1;
  591. /* get something from the wire */
  592. /* check if we have the header */
  593. if ((s->rstate != SSL_ST_READ_BODY) ||
  594. (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
  595. n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  596. /* read timeout is handled by dtls1_read_bytes */
  597. if (n <= 0)
  598. return (n); /* error or non-blocking */
  599. /* this packet contained a partial record, dump it */
  600. if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {
  601. s->packet_length = 0;
  602. goto again;
  603. }
  604. s->rstate = SSL_ST_READ_BODY;
  605. p = s->packet;
  606. if (s->msg_callback)
  607. s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
  608. s, s->msg_callback_arg);
  609. /* Pull apart the header into the DTLS1_RECORD */
  610. rr->type = *(p++);
  611. ssl_major = *(p++);
  612. ssl_minor = *(p++);
  613. version = (ssl_major << 8) | ssl_minor;
  614. /* sequence number is 64 bits, with top 2 bytes = epoch */
  615. n2s(p, rr->epoch);
  616. memcpy(&(s->s3->read_sequence[2]), p, 6);
  617. p += 6;
  618. n2s(p, rr->length);
  619. /*
  620. * Lets check the version. We tolerate alerts that don't have the exact
  621. * version number (e.g. because of protocol version errors)
  622. */
  623. if (!s->first_packet && rr->type != SSL3_RT_ALERT) {
  624. if (version != s->version) {
  625. /* unexpected version, silently discard */
  626. rr->length = 0;
  627. s->packet_length = 0;
  628. goto again;
  629. }
  630. }
  631. if ((version & 0xff00) != (s->version & 0xff00)) {
  632. /* wrong version, silently discard record */
  633. rr->length = 0;
  634. s->packet_length = 0;
  635. goto again;
  636. }
  637. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  638. /* record too long, silently discard it */
  639. rr->length = 0;
  640. s->packet_length = 0;
  641. goto again;
  642. }
  643. /* now s->rstate == SSL_ST_READ_BODY */
  644. }
  645. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  646. if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
  647. /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
  648. i = rr->length;
  649. n = ssl3_read_n(s, i, i, 1);
  650. /* this packet contained a partial record, dump it */
  651. if (n != i) {
  652. rr->length = 0;
  653. s->packet_length = 0;
  654. goto again;
  655. }
  656. /*
  657. * now n == rr->length, and s->packet_length ==
  658. * DTLS1_RT_HEADER_LENGTH + rr->length
  659. */
  660. }
  661. s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
  662. /* match epochs. NULL means the packet is dropped on the floor */
  663. bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
  664. if (bitmap == NULL) {
  665. rr->length = 0;
  666. s->packet_length = 0; /* dump this record */
  667. goto again; /* get another record */
  668. }
  669. #ifndef OPENSSL_NO_SCTP
  670. /* Only do replay check if no SCTP bio */
  671. if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
  672. #endif
  673. /*
  674. * Check whether this is a repeat, or aged record. Don't check if
  675. * we're listening and this message is a ClientHello. They can look
  676. * as if they're replayed, since they arrive from different
  677. * connections and would be dropped unnecessarily.
  678. */
  679. if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
  680. s->packet_length > DTLS1_RT_HEADER_LENGTH &&
  681. s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
  682. !dtls1_record_replay_check(s, bitmap)) {
  683. rr->length = 0;
  684. s->packet_length = 0; /* dump this record */
  685. goto again; /* get another record */
  686. }
  687. #ifndef OPENSSL_NO_SCTP
  688. }
  689. #endif
  690. /* just read a 0 length packet */
  691. if (rr->length == 0)
  692. goto again;
  693. /*
  694. * If this record is from the next epoch (either HM or ALERT), and a
  695. * handshake is currently in progress, buffer it since it cannot be
  696. * processed at this time. However, do not buffer anything while
  697. * listening.
  698. */
  699. if (is_next_epoch) {
  700. if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {
  701. if (dtls1_buffer_record
  702. (s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0)
  703. return -1;
  704. }
  705. rr->length = 0;
  706. s->packet_length = 0;
  707. goto again;
  708. }
  709. if (!dtls1_process_record(s, bitmap)) {
  710. rr->length = 0;
  711. s->packet_length = 0; /* dump this record */
  712. goto again; /* get another record */
  713. }
  714. return (1);
  715. }
  716. /*-
  717. * Return up to 'len' payload bytes received in 'type' records.
  718. * 'type' is one of the following:
  719. *
  720. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  721. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  722. * - 0 (during a shutdown, no data has to be returned)
  723. *
  724. * If we don't have stored data to work from, read a SSL/TLS record first
  725. * (possibly multiple records if we still don't have anything to return).
  726. *
  727. * This function must handle any surprises the peer may have for us, such as
  728. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  729. * a surprise, but handled as if it were), or renegotiation requests.
  730. * Also if record payloads contain fragments too small to process, we store
  731. * them until there is enough for the respective protocol (the record protocol
  732. * may use arbitrary fragmentation and even interleaving):
  733. * Change cipher spec protocol
  734. * just 1 byte needed, no need for keeping anything stored
  735. * Alert protocol
  736. * 2 bytes needed (AlertLevel, AlertDescription)
  737. * Handshake protocol
  738. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  739. * to detect unexpected Client Hello and Hello Request messages
  740. * here, anything else is handled by higher layers
  741. * Application data protocol
  742. * none of our business
  743. */
  744. int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  745. {
  746. int al, i, j, ret;
  747. unsigned int n;
  748. SSL3_RECORD *rr;
  749. void (*cb) (const SSL *ssl, int type2, int val) = NULL;
  750. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  751. if (!ssl3_setup_buffers(s))
  752. return (-1);
  753. /* XXX: check what the second '&& type' is about */
  754. if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
  755. (type != SSL3_RT_HANDSHAKE) && type) ||
  756. (peek && (type != SSL3_RT_APPLICATION_DATA))) {
  757. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  758. return -1;
  759. }
  760. /*
  761. * check whether there's a handshake message (client hello?) waiting
  762. */
  763. if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
  764. return ret;
  765. /*
  766. * Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
  767. */
  768. #ifndef OPENSSL_NO_SCTP
  769. /*
  770. * Continue handshake if it had to be interrupted to read app data with
  771. * SCTP.
  772. */
  773. if ((!s->in_handshake && SSL_in_init(s)) ||
  774. (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  775. (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
  776. || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)
  777. && s->s3->in_read_app_data != 2))
  778. #else
  779. if (!s->in_handshake && SSL_in_init(s))
  780. #endif
  781. {
  782. /* type == SSL3_RT_APPLICATION_DATA */
  783. i = s->handshake_func(s);
  784. if (i < 0)
  785. return (i);
  786. if (i == 0) {
  787. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  788. return (-1);
  789. }
  790. }
  791. start:
  792. s->rwstate = SSL_NOTHING;
  793. /*-
  794. * s->s3->rrec.type - is the type of record
  795. * s->s3->rrec.data, - data
  796. * s->s3->rrec.off, - offset into 'data' for next read
  797. * s->s3->rrec.length, - number of bytes.
  798. */
  799. rr = &(s->s3->rrec);
  800. /*
  801. * We are not handshaking and have no data yet, so process data buffered
  802. * during the last handshake in advance, if any.
  803. */
  804. if (s->state == SSL_ST_OK && rr->length == 0) {
  805. pitem *item;
  806. item = pqueue_pop(s->d1->buffered_app_data.q);
  807. if (item) {
  808. #ifndef OPENSSL_NO_SCTP
  809. /* Restore bio_dgram_sctp_rcvinfo struct */
  810. if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
  811. DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
  812. BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
  813. sizeof(rdata->recordinfo), &rdata->recordinfo);
  814. }
  815. #endif
  816. dtls1_copy_record(s, item);
  817. OPENSSL_free(item->data);
  818. pitem_free(item);
  819. }
  820. }
  821. /* Check for timeout */
  822. if (dtls1_handle_timeout(s) > 0)
  823. goto start;
  824. /* get new packet if necessary */
  825. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
  826. ret = dtls1_get_record(s);
  827. if (ret <= 0) {
  828. ret = dtls1_read_failed(s, ret);
  829. /* anything other than a timeout is an error */
  830. if (ret <= 0)
  831. return (ret);
  832. else
  833. goto start;
  834. }
  835. }
  836. if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) {
  837. rr->length = 0;
  838. goto start;
  839. }
  840. /*
  841. * Reset the count of consecutive warning alerts if we've got a non-empty
  842. * record that isn't an alert.
  843. */
  844. if (rr->type != SSL3_RT_ALERT && rr->length != 0)
  845. s->cert->alert_count = 0;
  846. /* we now have a packet which can be read and processed */
  847. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  848. * reset by ssl3_get_finished */
  849. && (rr->type != SSL3_RT_HANDSHAKE)) {
  850. /*
  851. * We now have application data between CCS and Finished. Most likely
  852. * the packets were reordered on their way, so buffer the application
  853. * data for later processing rather than dropping the connection.
  854. */
  855. if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) <
  856. 0) {
  857. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  858. return -1;
  859. }
  860. rr->length = 0;
  861. goto start;
  862. }
  863. /*
  864. * If the other end has shut down, throw anything we read away (even in
  865. * 'peek' mode)
  866. */
  867. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  868. rr->length = 0;
  869. s->rwstate = SSL_NOTHING;
  870. return (0);
  871. }
  872. if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or
  873. * SSL3_RT_HANDSHAKE */
  874. /*
  875. * make sure that we are not getting application data when we are
  876. * doing a handshake for the first time
  877. */
  878. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  879. (s->enc_read_ctx == NULL)) {
  880. al = SSL_AD_UNEXPECTED_MESSAGE;
  881. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
  882. goto f_err;
  883. }
  884. if (len <= 0)
  885. return (len);
  886. if ((unsigned int)len > rr->length)
  887. n = rr->length;
  888. else
  889. n = (unsigned int)len;
  890. memcpy(buf, &(rr->data[rr->off]), n);
  891. if (!peek) {
  892. rr->length -= n;
  893. rr->off += n;
  894. if (rr->length == 0) {
  895. s->rstate = SSL_ST_READ_HEADER;
  896. rr->off = 0;
  897. }
  898. }
  899. #ifndef OPENSSL_NO_SCTP
  900. /*
  901. * We were about to renegotiate but had to read belated application
  902. * data first, so retry.
  903. */
  904. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  905. rr->type == SSL3_RT_APPLICATION_DATA &&
  906. (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
  907. || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) {
  908. s->rwstate = SSL_READING;
  909. BIO_clear_retry_flags(SSL_get_rbio(s));
  910. BIO_set_retry_read(SSL_get_rbio(s));
  911. }
  912. /*
  913. * We might had to delay a close_notify alert because of reordered
  914. * app data. If there was an alert and there is no message to read
  915. * anymore, finally set shutdown.
  916. */
  917. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  918. s->d1->shutdown_received
  919. && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
  920. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  921. return (0);
  922. }
  923. #endif
  924. return (n);
  925. }
  926. /*
  927. * If we get here, then type != rr->type; if we have a handshake message,
  928. * then it was unexpected (Hello Request or Client Hello).
  929. */
  930. /*
  931. * In case of record types for which we have 'fragment' storage, fill
  932. * that so that we can process the data at a fixed place.
  933. */
  934. {
  935. unsigned int k, dest_maxlen = 0;
  936. unsigned char *dest = NULL;
  937. unsigned int *dest_len = NULL;
  938. if (rr->type == SSL3_RT_HANDSHAKE) {
  939. dest_maxlen = sizeof(s->d1->handshake_fragment);
  940. dest = s->d1->handshake_fragment;
  941. dest_len = &s->d1->handshake_fragment_len;
  942. } else if (rr->type == SSL3_RT_ALERT) {
  943. dest_maxlen = sizeof(s->d1->alert_fragment);
  944. dest = s->d1->alert_fragment;
  945. dest_len = &s->d1->alert_fragment_len;
  946. }
  947. #ifndef OPENSSL_NO_HEARTBEATS
  948. else if (rr->type == TLS1_RT_HEARTBEAT) {
  949. dtls1_process_heartbeat(s);
  950. /* Exit and notify application to read again */
  951. rr->length = 0;
  952. s->rwstate = SSL_READING;
  953. BIO_clear_retry_flags(SSL_get_rbio(s));
  954. BIO_set_retry_read(SSL_get_rbio(s));
  955. return (-1);
  956. }
  957. #endif
  958. /* else it's a CCS message, or application data or wrong */
  959. else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
  960. /*
  961. * Application data while renegotiating is allowed. Try again
  962. * reading.
  963. */
  964. if (rr->type == SSL3_RT_APPLICATION_DATA) {
  965. BIO *bio;
  966. s->s3->in_read_app_data = 2;
  967. bio = SSL_get_rbio(s);
  968. s->rwstate = SSL_READING;
  969. BIO_clear_retry_flags(bio);
  970. BIO_set_retry_read(bio);
  971. return (-1);
  972. }
  973. /* Not certain if this is the right error handling */
  974. al = SSL_AD_UNEXPECTED_MESSAGE;
  975. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  976. goto f_err;
  977. }
  978. if (dest_maxlen > 0) {
  979. /*
  980. * XDTLS: In a pathalogical case, the Client Hello may be
  981. * fragmented--don't always expect dest_maxlen bytes
  982. */
  983. if (rr->length < dest_maxlen) {
  984. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  985. /*
  986. * for normal alerts rr->length is 2, while
  987. * dest_maxlen is 7 if we were to handle this
  988. * non-existing alert...
  989. */
  990. FIX ME
  991. #endif
  992. s->rstate = SSL_ST_READ_HEADER;
  993. rr->length = 0;
  994. goto start;
  995. }
  996. /* now move 'n' bytes: */
  997. for (k = 0; k < dest_maxlen; k++) {
  998. dest[k] = rr->data[rr->off++];
  999. rr->length--;
  1000. }
  1001. *dest_len = dest_maxlen;
  1002. }
  1003. }
  1004. /*-
  1005. * s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
  1006. * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
  1007. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
  1008. */
  1009. /* If we are a client, check for an incoming 'Hello Request': */
  1010. if ((!s->server) &&
  1011. (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  1012. (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  1013. (s->session != NULL) && (s->session->cipher != NULL)) {
  1014. s->d1->handshake_fragment_len = 0;
  1015. if ((s->d1->handshake_fragment[1] != 0) ||
  1016. (s->d1->handshake_fragment[2] != 0) ||
  1017. (s->d1->handshake_fragment[3] != 0)) {
  1018. al = SSL_AD_DECODE_ERROR;
  1019. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
  1020. goto f_err;
  1021. }
  1022. /*
  1023. * no need to check sequence number on HELLO REQUEST messages
  1024. */
  1025. if (s->msg_callback)
  1026. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  1027. s->d1->handshake_fragment, 4, s,
  1028. s->msg_callback_arg);
  1029. if (SSL_is_init_finished(s) &&
  1030. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  1031. !s->s3->renegotiate) {
  1032. s->d1->handshake_read_seq++;
  1033. s->new_session = 1;
  1034. ssl3_renegotiate(s);
  1035. if (ssl3_renegotiate_check(s)) {
  1036. i = s->handshake_func(s);
  1037. if (i < 0)
  1038. return (i);
  1039. if (i == 0) {
  1040. SSLerr(SSL_F_DTLS1_READ_BYTES,
  1041. SSL_R_SSL_HANDSHAKE_FAILURE);
  1042. return (-1);
  1043. }
  1044. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  1045. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  1046. BIO *bio;
  1047. /*
  1048. * In the case where we try to read application data,
  1049. * but we trigger an SSL handshake, we return -1 with
  1050. * the retry option set. Otherwise renegotiation may
  1051. * cause nasty problems in the blocking world
  1052. */
  1053. s->rwstate = SSL_READING;
  1054. bio = SSL_get_rbio(s);
  1055. BIO_clear_retry_flags(bio);
  1056. BIO_set_retry_read(bio);
  1057. return (-1);
  1058. }
  1059. }
  1060. }
  1061. }
  1062. /*
  1063. * we either finished a handshake or ignored the request, now try
  1064. * again to obtain the (application) data we were asked for
  1065. */
  1066. goto start;
  1067. }
  1068. /*
  1069. * If we are a server and get a client hello when renegotiation isn't
  1070. * allowed send back a no renegotiation alert and carry on.
  1071. */
  1072. if (s->server
  1073. && SSL_is_init_finished(s)
  1074. && !s->s3->send_connection_binding
  1075. && s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH
  1076. && s->d1->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO
  1077. && s->s3->previous_client_finished_len != 0
  1078. && (s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0) {
  1079. s->d1->handshake_fragment_len = 0;
  1080. rr->length = 0;
  1081. ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
  1082. goto start;
  1083. }
  1084. if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
  1085. int alert_level = s->d1->alert_fragment[0];
  1086. int alert_descr = s->d1->alert_fragment[1];
  1087. s->d1->alert_fragment_len = 0;
  1088. if (s->msg_callback)
  1089. s->msg_callback(0, s->version, SSL3_RT_ALERT,
  1090. s->d1->alert_fragment, 2, s, s->msg_callback_arg);
  1091. if (s->info_callback != NULL)
  1092. cb = s->info_callback;
  1093. else if (s->ctx->info_callback != NULL)
  1094. cb = s->ctx->info_callback;
  1095. if (cb != NULL) {
  1096. j = (alert_level << 8) | alert_descr;
  1097. cb(s, SSL_CB_READ_ALERT, j);
  1098. }
  1099. if (alert_level == SSL3_AL_WARNING) {
  1100. s->s3->warn_alert = alert_descr;
  1101. s->cert->alert_count++;
  1102. if (s->cert->alert_count == MAX_WARN_ALERT_COUNT) {
  1103. al = SSL_AD_UNEXPECTED_MESSAGE;
  1104. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);
  1105. goto f_err;
  1106. }
  1107. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  1108. #ifndef OPENSSL_NO_SCTP
  1109. /*
  1110. * With SCTP and streams the socket may deliver app data
  1111. * after a close_notify alert. We have to check this first so
  1112. * that nothing gets discarded.
  1113. */
  1114. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  1115. BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
  1116. s->d1->shutdown_received = 1;
  1117. s->rwstate = SSL_READING;
  1118. BIO_clear_retry_flags(SSL_get_rbio(s));
  1119. BIO_set_retry_read(SSL_get_rbio(s));
  1120. return -1;
  1121. }
  1122. #endif
  1123. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1124. return (0);
  1125. }
  1126. #if 0
  1127. /* XXX: this is a possible improvement in the future */
  1128. /* now check if it's a missing record */
  1129. if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
  1130. unsigned short seq;
  1131. unsigned int frag_off;
  1132. unsigned char *p = &(s->d1->alert_fragment[2]);
  1133. n2s(p, seq);
  1134. n2l3(p, frag_off);
  1135. dtls1_retransmit_message(s,
  1136. dtls1_get_queue_priority
  1137. (frag->msg_header.seq, 0), frag_off,
  1138. &found);
  1139. if (!found && SSL_in_init(s)) {
  1140. /*
  1141. * fprintf( stderr,"in init = %d\n", SSL_in_init(s));
  1142. */
  1143. /*
  1144. * requested a message not yet sent, send an alert
  1145. * ourselves
  1146. */
  1147. ssl3_send_alert(s, SSL3_AL_WARNING,
  1148. DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  1149. }
  1150. }
  1151. #endif
  1152. } else if (alert_level == SSL3_AL_FATAL) {
  1153. char tmp[16];
  1154. s->rwstate = SSL_NOTHING;
  1155. s->s3->fatal_alert = alert_descr;
  1156. SSLerr(SSL_F_DTLS1_READ_BYTES,
  1157. SSL_AD_REASON_OFFSET + alert_descr);
  1158. BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
  1159. ERR_add_error_data(2, "SSL alert number ", tmp);
  1160. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1161. SSL_CTX_remove_session(s->session_ctx, s->session);
  1162. return (0);
  1163. } else {
  1164. al = SSL_AD_ILLEGAL_PARAMETER;
  1165. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
  1166. goto f_err;
  1167. }
  1168. goto start;
  1169. }
  1170. if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
  1171. * shutdown */
  1172. s->rwstate = SSL_NOTHING;
  1173. rr->length = 0;
  1174. return (0);
  1175. }
  1176. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1177. struct ccs_header_st ccs_hdr;
  1178. unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
  1179. dtls1_get_ccs_header(rr->data, &ccs_hdr);
  1180. if (s->version == DTLS1_BAD_VER)
  1181. ccs_hdr_len = 3;
  1182. /*
  1183. * 'Change Cipher Spec' is just a single byte, so we know exactly
  1184. * what the record payload has to look like
  1185. */
  1186. /* XDTLS: check that epoch is consistent */
  1187. if ((rr->length != ccs_hdr_len) ||
  1188. (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
  1189. al = SSL_AD_ILLEGAL_PARAMETER;
  1190. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1191. goto f_err;
  1192. }
  1193. rr->length = 0;
  1194. if (s->msg_callback)
  1195. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  1196. rr->data, 1, s, s->msg_callback_arg);
  1197. /*
  1198. * We can't process a CCS now, because previous handshake messages
  1199. * are still missing, so just drop it.
  1200. */
  1201. if (!s->d1->change_cipher_spec_ok) {
  1202. goto start;
  1203. }
  1204. s->d1->change_cipher_spec_ok = 0;
  1205. s->s3->change_cipher_spec = 1;
  1206. if (!ssl3_do_change_cipher_spec(s))
  1207. goto err;
  1208. /* do this whenever CCS is processed */
  1209. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  1210. if (s->version == DTLS1_BAD_VER)
  1211. s->d1->handshake_read_seq++;
  1212. #ifndef OPENSSL_NO_SCTP
  1213. /*
  1214. * Remember that a CCS has been received, so that an old key of
  1215. * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
  1216. * SCTP is used
  1217. */
  1218. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
  1219. #endif
  1220. goto start;
  1221. }
  1222. /*
  1223. * Unexpected handshake message (Client Hello, or protocol violation)
  1224. */
  1225. if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  1226. !s->in_handshake) {
  1227. struct hm_header_st msg_hdr;
  1228. /* this may just be a stale retransmit */
  1229. dtls1_get_message_header(rr->data, &msg_hdr);
  1230. if (rr->epoch != s->d1->r_epoch) {
  1231. rr->length = 0;
  1232. goto start;
  1233. }
  1234. /*
  1235. * If we are server, we may have a repeated FINISHED of the client
  1236. * here, then retransmit our CCS and FINISHED.
  1237. */
  1238. if (msg_hdr.type == SSL3_MT_FINISHED) {
  1239. if (dtls1_check_timeout_num(s) < 0)
  1240. return -1;
  1241. dtls1_retransmit_buffered_messages(s);
  1242. rr->length = 0;
  1243. goto start;
  1244. }
  1245. if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
  1246. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
  1247. #if 0 /* worked only because C operator preferences
  1248. * are not as expected (and because this is
  1249. * not really needed for clients except for
  1250. * detecting protocol violations): */
  1251. s->state = SSL_ST_BEFORE | (s->server)
  1252. ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1253. #else
  1254. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1255. #endif
  1256. s->renegotiate = 1;
  1257. s->new_session = 1;
  1258. }
  1259. i = s->handshake_func(s);
  1260. if (i < 0)
  1261. return (i);
  1262. if (i == 0) {
  1263. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  1264. return (-1);
  1265. }
  1266. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  1267. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  1268. BIO *bio;
  1269. /*
  1270. * In the case where we try to read application data, but we
  1271. * trigger an SSL handshake, we return -1 with the retry
  1272. * option set. Otherwise renegotiation may cause nasty
  1273. * problems in the blocking world
  1274. */
  1275. s->rwstate = SSL_READING;
  1276. bio = SSL_get_rbio(s);
  1277. BIO_clear_retry_flags(bio);
  1278. BIO_set_retry_read(bio);
  1279. return (-1);
  1280. }
  1281. }
  1282. goto start;
  1283. }
  1284. switch (rr->type) {
  1285. default:
  1286. #ifndef OPENSSL_NO_TLS
  1287. /* TLS just ignores unknown message types */
  1288. if (s->version == TLS1_VERSION) {
  1289. rr->length = 0;
  1290. goto start;
  1291. }
  1292. #endif
  1293. al = SSL_AD_UNEXPECTED_MESSAGE;
  1294. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1295. goto f_err;
  1296. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1297. case SSL3_RT_ALERT:
  1298. case SSL3_RT_HANDSHAKE:
  1299. /*
  1300. * we already handled all of these, with the possible exception of
  1301. * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
  1302. * happen when type != rr->type
  1303. */
  1304. al = SSL_AD_UNEXPECTED_MESSAGE;
  1305. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  1306. goto f_err;
  1307. case SSL3_RT_APPLICATION_DATA:
  1308. /*
  1309. * At this point, we were expecting handshake data, but have
  1310. * application data. If the library was running inside ssl3_read()
  1311. * (i.e. in_read_app_data is set) and it makes sense to read
  1312. * application data at this point (session renegotiation not yet
  1313. * started), we will indulge it.
  1314. */
  1315. if (s->s3->in_read_app_data &&
  1316. (s->s3->total_renegotiations != 0) &&
  1317. (((s->state & SSL_ST_CONNECT) &&
  1318. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1319. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1320. ) || ((s->state & SSL_ST_ACCEPT) &&
  1321. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1322. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1323. )
  1324. )) {
  1325. s->s3->in_read_app_data = 2;
  1326. return (-1);
  1327. } else {
  1328. al = SSL_AD_UNEXPECTED_MESSAGE;
  1329. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1330. goto f_err;
  1331. }
  1332. }
  1333. /* not reached */
  1334. f_err:
  1335. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1336. err:
  1337. return (-1);
  1338. }
  1339. int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
  1340. {
  1341. int i;
  1342. #ifndef OPENSSL_NO_SCTP
  1343. /*
  1344. * Check if we have to continue an interrupted handshake for reading
  1345. * belated app data with SCTP.
  1346. */
  1347. if ((SSL_in_init(s) && !s->in_handshake) ||
  1348. (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
  1349. (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
  1350. || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)))
  1351. #else
  1352. if (SSL_in_init(s) && !s->in_handshake)
  1353. #endif
  1354. {
  1355. i = s->handshake_func(s);
  1356. if (i < 0)
  1357. return (i);
  1358. if (i == 0) {
  1359. SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,
  1360. SSL_R_SSL_HANDSHAKE_FAILURE);
  1361. return -1;
  1362. }
  1363. }
  1364. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  1365. SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES, SSL_R_DTLS_MESSAGE_TOO_BIG);
  1366. return -1;
  1367. }
  1368. i = dtls1_write_bytes(s, type, buf_, len);
  1369. return i;
  1370. }
  1371. /*
  1372. * this only happens when a client hello is received and a handshake
  1373. * is started.
  1374. */
  1375. static int
  1376. have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  1377. int len, int peek)
  1378. {
  1379. if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
  1380. /* (partially) satisfy request from storage */
  1381. {
  1382. unsigned char *src = s->d1->handshake_fragment;
  1383. unsigned char *dst = buf;
  1384. unsigned int k, n;
  1385. /* peek == 0 */
  1386. n = 0;
  1387. while ((len > 0) && (s->d1->handshake_fragment_len > 0)) {
  1388. *dst++ = *src++;
  1389. len--;
  1390. s->d1->handshake_fragment_len--;
  1391. n++;
  1392. }
  1393. /* move any remaining fragment bytes: */
  1394. for (k = 0; k < s->d1->handshake_fragment_len; k++)
  1395. s->d1->handshake_fragment[k] = *src++;
  1396. return n;
  1397. }
  1398. return 0;
  1399. }
  1400. /*
  1401. * Call this to write data in records of type 'type' It will return <= 0 if
  1402. * not all data has been sent or non-blocking IO.
  1403. */
  1404. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
  1405. {
  1406. int i;
  1407. OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  1408. s->rwstate = SSL_NOTHING;
  1409. i = do_dtls1_write(s, type, buf, len, 0);
  1410. return i;
  1411. }
  1412. int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
  1413. unsigned int len, int create_empty_fragment)
  1414. {
  1415. unsigned char *p, *pseq;
  1416. int i, mac_size, clear = 0;
  1417. int prefix_len = 0;
  1418. int eivlen;
  1419. SSL3_RECORD *wr;
  1420. SSL3_BUFFER *wb;
  1421. SSL_SESSION *sess;
  1422. /*
  1423. * first check if there is a SSL3_BUFFER still being written out. This
  1424. * will happen with non blocking IO
  1425. */
  1426. if (s->s3->wbuf.left != 0) {
  1427. OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */
  1428. return (ssl3_write_pending(s, type, buf, len));
  1429. }
  1430. /* If we have an alert to send, lets send it */
  1431. if (s->s3->alert_dispatch) {
  1432. i = s->method->ssl_dispatch_alert(s);
  1433. if (i <= 0)
  1434. return (i);
  1435. /* if it went, fall through and send more stuff */
  1436. }
  1437. if (len == 0 && !create_empty_fragment)
  1438. return 0;
  1439. wr = &(s->s3->wrec);
  1440. wb = &(s->s3->wbuf);
  1441. sess = s->session;
  1442. if ((sess == NULL) ||
  1443. (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
  1444. clear = 1;
  1445. if (clear)
  1446. mac_size = 0;
  1447. else {
  1448. mac_size = EVP_MD_CTX_size(s->write_hash);
  1449. if (mac_size < 0)
  1450. goto err;
  1451. }
  1452. /* DTLS implements explicit IV, so no need for empty fragments */
  1453. #if 0
  1454. /*
  1455. * 'create_empty_fragment' is true only when this function calls itself
  1456. */
  1457. if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
  1458. && SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
  1459. {
  1460. /*
  1461. * countermeasure against known-IV weakness in CBC ciphersuites (see
  1462. * http://www.openssl.org/~bodo/tls-cbc.txt)
  1463. */
  1464. if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
  1465. /*
  1466. * recursive function call with 'create_empty_fragment' set; this
  1467. * prepares and buffers the data for an empty fragment (these
  1468. * 'prefix_len' bytes are sent out later together with the actual
  1469. * payload)
  1470. */
  1471. prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
  1472. if (prefix_len <= 0)
  1473. goto err;
  1474. if (s->s3->wbuf.len <
  1475. (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) {
  1476. /* insufficient space */
  1477. SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
  1478. goto err;
  1479. }
  1480. }
  1481. s->s3->empty_fragment_done = 1;
  1482. }
  1483. #endif
  1484. p = wb->buf + prefix_len;
  1485. /* write the header */
  1486. *(p++) = type & 0xff;
  1487. wr->type = type;
  1488. /*
  1489. * Special case: for hello verify request, client version 1.0 and we
  1490. * haven't decided which version to use yet send back using version 1.0
  1491. * header: otherwise some clients will ignore it.
  1492. */
  1493. if (s->method->version == DTLS_ANY_VERSION) {
  1494. *(p++) = DTLS1_VERSION >> 8;
  1495. *(p++) = DTLS1_VERSION & 0xff;
  1496. } else {
  1497. *(p++) = s->version >> 8;
  1498. *(p++) = s->version & 0xff;
  1499. }
  1500. /* field where we are to write out packet epoch, seq num and len */
  1501. pseq = p;
  1502. p += 10;
  1503. /* Explicit IV length, block ciphers appropriate version flag */
  1504. if (s->enc_write_ctx) {
  1505. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  1506. if (mode == EVP_CIPH_CBC_MODE) {
  1507. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  1508. if (eivlen <= 1)
  1509. eivlen = 0;
  1510. }
  1511. /* Need explicit part of IV for GCM mode */
  1512. else if (mode == EVP_CIPH_GCM_MODE)
  1513. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  1514. else
  1515. eivlen = 0;
  1516. } else
  1517. eivlen = 0;
  1518. /* lets setup the record stuff. */
  1519. wr->data = p + eivlen; /* make room for IV in case of CBC */
  1520. wr->length = (int)len;
  1521. wr->input = (unsigned char *)buf;
  1522. /*
  1523. * we now 'read' from wr->input, wr->length bytes into wr->data
  1524. */
  1525. /* first we compress */
  1526. if (s->compress != NULL) {
  1527. if (!ssl3_do_compress(s)) {
  1528. SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
  1529. goto err;
  1530. }
  1531. } else {
  1532. memcpy(wr->data, wr->input, wr->length);
  1533. wr->input = wr->data;
  1534. }
  1535. /*
  1536. * we should still have the output to wr->data and the input from
  1537. * wr->input. Length should be wr->length. wr->data still points in the
  1538. * wb->buf
  1539. */
  1540. if (mac_size != 0) {
  1541. if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0)
  1542. goto err;
  1543. wr->length += mac_size;
  1544. }
  1545. /* this is true regardless of mac size */
  1546. wr->input = p;
  1547. wr->data = p;
  1548. if (eivlen)
  1549. wr->length += eivlen;
  1550. if (s->method->ssl3_enc->enc(s, 1) < 1)
  1551. goto err;
  1552. /* record length after mac and block padding */
  1553. /*
  1554. * if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
  1555. * SSL_in_init(s)))
  1556. */
  1557. /* there's only one epoch between handshake and app data */
  1558. s2n(s->d1->w_epoch, pseq);
  1559. /* XDTLS: ?? */
  1560. /*
  1561. * else s2n(s->d1->handshake_epoch, pseq);
  1562. */
  1563. memcpy(pseq, &(s->s3->write_sequence[2]), 6);
  1564. pseq += 6;
  1565. s2n(wr->length, pseq);
  1566. if (s->msg_callback)
  1567. s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
  1568. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  1569. /*
  1570. * we should now have wr->data pointing to the encrypted data, which is
  1571. * wr->length long
  1572. */
  1573. wr->type = type; /* not needed but helps for debugging */
  1574. wr->length += DTLS1_RT_HEADER_LENGTH;
  1575. #if 0 /* this is now done at the message layer */
  1576. /* buffer the record, making it easy to handle retransmits */
  1577. if (type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1578. dtls1_buffer_record(s, wr->data, wr->length,
  1579. *((PQ_64BIT *) & (s->s3->write_sequence[0])));
  1580. #endif
  1581. ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
  1582. if (create_empty_fragment) {
  1583. /*
  1584. * we are in a recursive call; just return the length, don't write
  1585. * out anything here
  1586. */
  1587. return wr->length;
  1588. }
  1589. /* now let's set up wb */
  1590. wb->left = prefix_len + wr->length;
  1591. wb->offset = 0;
  1592. /*
  1593. * memorize arguments so that ssl3_write_pending can detect bad write
  1594. * retries later
  1595. */
  1596. s->s3->wpend_tot = len;
  1597. s->s3->wpend_buf = buf;
  1598. s->s3->wpend_type = type;
  1599. s->s3->wpend_ret = len;
  1600. /* we now just need to write the buffer */
  1601. return ssl3_write_pending(s, type, buf, len);
  1602. err:
  1603. return -1;
  1604. }
  1605. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
  1606. {
  1607. int cmp;
  1608. unsigned int shift;
  1609. const unsigned char *seq = s->s3->read_sequence;
  1610. cmp = satsub64be(seq, bitmap->max_seq_num);
  1611. if (cmp > 0) {
  1612. memcpy(s->s3->rrec.seq_num, seq, 8);
  1613. return 1; /* this record in new */
  1614. }
  1615. shift = -cmp;
  1616. if (shift >= sizeof(bitmap->map) * 8)
  1617. return 0; /* stale, outside the window */
  1618. else if (bitmap->map & (1UL << shift))
  1619. return 0; /* record previously received */
  1620. memcpy(s->s3->rrec.seq_num, seq, 8);
  1621. return 1;
  1622. }
  1623. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
  1624. {
  1625. int cmp;
  1626. unsigned int shift;
  1627. const unsigned char *seq = s->s3->read_sequence;
  1628. cmp = satsub64be(seq, bitmap->max_seq_num);
  1629. if (cmp > 0) {
  1630. shift = cmp;
  1631. if (shift < sizeof(bitmap->map) * 8)
  1632. bitmap->map <<= shift, bitmap->map |= 1UL;
  1633. else
  1634. bitmap->map = 1UL;
  1635. memcpy(bitmap->max_seq_num, seq, 8);
  1636. } else {
  1637. shift = -cmp;
  1638. if (shift < sizeof(bitmap->map) * 8)
  1639. bitmap->map |= 1UL << shift;
  1640. }
  1641. }
  1642. int dtls1_dispatch_alert(SSL *s)
  1643. {
  1644. int i, j;
  1645. void (*cb) (const SSL *ssl, int type, int val) = NULL;
  1646. unsigned char buf[DTLS1_AL_HEADER_LENGTH];
  1647. unsigned char *ptr = &buf[0];
  1648. s->s3->alert_dispatch = 0;
  1649. memset(buf, 0x00, sizeof(buf));
  1650. *ptr++ = s->s3->send_alert[0];
  1651. *ptr++ = s->s3->send_alert[1];
  1652. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1653. if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
  1654. s2n(s->d1->handshake_read_seq, ptr);
  1655. # if 0
  1656. if (s->d1->r_msg_hdr.frag_off == 0)
  1657. /*
  1658. * waiting for a new msg
  1659. */
  1660. else
  1661. s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
  1662. # endif
  1663. # if 0
  1664. fprintf(stderr,
  1665. "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",
  1666. s->d1->handshake_read_seq, s->d1->r_msg_hdr.seq);
  1667. # endif
  1668. l2n3(s->d1->r_msg_hdr.frag_off, ptr);
  1669. }
  1670. #endif
  1671. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
  1672. if (i <= 0) {
  1673. s->s3->alert_dispatch = 1;
  1674. /* fprintf( stderr, "not done with alert\n" ); */
  1675. } else {
  1676. if (s->s3->send_alert[0] == SSL3_AL_FATAL
  1677. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1678. || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1679. #endif
  1680. )
  1681. (void)BIO_flush(s->wbio);
  1682. if (s->msg_callback)
  1683. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
  1684. 2, s, s->msg_callback_arg);
  1685. if (s->info_callback != NULL)
  1686. cb = s->info_callback;
  1687. else if (s->ctx->info_callback != NULL)
  1688. cb = s->ctx->info_callback;
  1689. if (cb != NULL) {
  1690. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  1691. cb(s, SSL_CB_WRITE_ALERT, j);
  1692. }
  1693. }
  1694. return (i);
  1695. }
  1696. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  1697. unsigned int *is_next_epoch)
  1698. {
  1699. *is_next_epoch = 0;
  1700. /* In current epoch, accept HM, CCS, DATA, & ALERT */
  1701. if (rr->epoch == s->d1->r_epoch)
  1702. return &s->d1->bitmap;
  1703. /*
  1704. * Only HM and ALERT messages can be from the next epoch and only if we
  1705. * have already processed all of the unprocessed records from the last
  1706. * epoch
  1707. */
  1708. else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
  1709. s->d1->unprocessed_rcds.epoch != s->d1->r_epoch &&
  1710. (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
  1711. *is_next_epoch = 1;
  1712. return &s->d1->next_bitmap;
  1713. }
  1714. return NULL;
  1715. }
  1716. #if 0
  1717. static int
  1718. dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
  1719. unsigned short *priority, unsigned long *offset)
  1720. {
  1721. /* alerts are passed up immediately */
  1722. if (rr->type == SSL3_RT_APPLICATION_DATA || rr->type == SSL3_RT_ALERT)
  1723. return 0;
  1724. /*
  1725. * Only need to buffer if a handshake is underway. (this implies that
  1726. * Hello Request and Client Hello are passed up immediately)
  1727. */
  1728. if (SSL_in_init(s)) {
  1729. unsigned char *data = rr->data;
  1730. /* need to extract the HM/CCS sequence number here */
  1731. if (rr->type == SSL3_RT_HANDSHAKE ||
  1732. rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1733. unsigned short seq_num;
  1734. struct hm_header_st msg_hdr;
  1735. struct ccs_header_st ccs_hdr;
  1736. if (rr->type == SSL3_RT_HANDSHAKE) {
  1737. dtls1_get_message_header(data, &msg_hdr);
  1738. seq_num = msg_hdr.seq;
  1739. *offset = msg_hdr.frag_off;
  1740. } else {
  1741. dtls1_get_ccs_header(data, &ccs_hdr);
  1742. seq_num = ccs_hdr.seq;
  1743. *offset = 0;
  1744. }
  1745. /*
  1746. * this is either a record we're waiting for, or a retransmit of
  1747. * something we happened to previously receive (higher layers
  1748. * will drop the repeat silently
  1749. */
  1750. if (seq_num < s->d1->handshake_read_seq)
  1751. return 0;
  1752. if (rr->type == SSL3_RT_HANDSHAKE &&
  1753. seq_num == s->d1->handshake_read_seq &&
  1754. msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
  1755. return 0;
  1756. else if (seq_num == s->d1->handshake_read_seq &&
  1757. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
  1758. msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
  1759. return 0;
  1760. else {
  1761. *priority = seq_num;
  1762. return 1;
  1763. }
  1764. } else /* unknown record type */
  1765. return 0;
  1766. }
  1767. return 0;
  1768. }
  1769. #endif
  1770. void dtls1_reset_seq_numbers(SSL *s, int rw)
  1771. {
  1772. unsigned char *seq;
  1773. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  1774. if (rw & SSL3_CC_READ) {
  1775. seq = s->s3->read_sequence;
  1776. s->d1->r_epoch++;
  1777. memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
  1778. memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
  1779. /*
  1780. * We must not use any buffered messages received from the previous
  1781. * epoch
  1782. */
  1783. dtls1_clear_received_buffer(s);
  1784. } else {
  1785. seq = s->s3->write_sequence;
  1786. memcpy(s->d1->last_write_sequence, seq,
  1787. sizeof(s->s3->write_sequence));
  1788. s->d1->w_epoch++;
  1789. }
  1790. memset(seq, 0x00, seq_bytes);
  1791. }