d1_pkt.c 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040
  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-2019 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. s->state = SSL_ST_ERR;
  1163. return (0);
  1164. } else {
  1165. al = SSL_AD_ILLEGAL_PARAMETER;
  1166. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
  1167. goto f_err;
  1168. }
  1169. goto start;
  1170. }
  1171. if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
  1172. * shutdown */
  1173. s->rwstate = SSL_NOTHING;
  1174. rr->length = 0;
  1175. return (0);
  1176. }
  1177. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1178. struct ccs_header_st ccs_hdr;
  1179. unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
  1180. dtls1_get_ccs_header(rr->data, &ccs_hdr);
  1181. if (s->version == DTLS1_BAD_VER)
  1182. ccs_hdr_len = 3;
  1183. /*
  1184. * 'Change Cipher Spec' is just a single byte, so we know exactly
  1185. * what the record payload has to look like
  1186. */
  1187. /* XDTLS: check that epoch is consistent */
  1188. if ((rr->length != ccs_hdr_len) ||
  1189. (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
  1190. al = SSL_AD_ILLEGAL_PARAMETER;
  1191. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1192. goto f_err;
  1193. }
  1194. rr->length = 0;
  1195. if (s->msg_callback)
  1196. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  1197. rr->data, 1, s, s->msg_callback_arg);
  1198. /*
  1199. * We can't process a CCS now, because previous handshake messages
  1200. * are still missing, so just drop it.
  1201. */
  1202. if (!s->d1->change_cipher_spec_ok) {
  1203. goto start;
  1204. }
  1205. s->d1->change_cipher_spec_ok = 0;
  1206. s->s3->change_cipher_spec = 1;
  1207. if (!ssl3_do_change_cipher_spec(s))
  1208. goto err;
  1209. /* do this whenever CCS is processed */
  1210. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  1211. if (s->version == DTLS1_BAD_VER)
  1212. s->d1->handshake_read_seq++;
  1213. #ifndef OPENSSL_NO_SCTP
  1214. /*
  1215. * Remember that a CCS has been received, so that an old key of
  1216. * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
  1217. * SCTP is used
  1218. */
  1219. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
  1220. #endif
  1221. goto start;
  1222. }
  1223. /*
  1224. * Unexpected handshake message (Client Hello, or protocol violation)
  1225. */
  1226. if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  1227. !s->in_handshake) {
  1228. struct hm_header_st msg_hdr;
  1229. /* this may just be a stale retransmit */
  1230. dtls1_get_message_header(rr->data, &msg_hdr);
  1231. if (rr->epoch != s->d1->r_epoch) {
  1232. rr->length = 0;
  1233. goto start;
  1234. }
  1235. /*
  1236. * If we are server, we may have a repeated FINISHED of the client
  1237. * here, then retransmit our CCS and FINISHED.
  1238. */
  1239. if (msg_hdr.type == SSL3_MT_FINISHED) {
  1240. if (dtls1_check_timeout_num(s) < 0)
  1241. return -1;
  1242. dtls1_retransmit_buffered_messages(s);
  1243. rr->length = 0;
  1244. goto start;
  1245. }
  1246. if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
  1247. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
  1248. #if 0 /* worked only because C operator preferences
  1249. * are not as expected (and because this is
  1250. * not really needed for clients except for
  1251. * detecting protocol violations): */
  1252. s->state = SSL_ST_BEFORE | (s->server)
  1253. ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1254. #else
  1255. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1256. #endif
  1257. s->renegotiate = 1;
  1258. s->new_session = 1;
  1259. }
  1260. i = s->handshake_func(s);
  1261. if (i < 0)
  1262. return (i);
  1263. if (i == 0) {
  1264. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  1265. return (-1);
  1266. }
  1267. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  1268. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  1269. BIO *bio;
  1270. /*
  1271. * In the case where we try to read application data, but we
  1272. * trigger an SSL handshake, we return -1 with the retry
  1273. * option set. Otherwise renegotiation may cause nasty
  1274. * problems in the blocking world
  1275. */
  1276. s->rwstate = SSL_READING;
  1277. bio = SSL_get_rbio(s);
  1278. BIO_clear_retry_flags(bio);
  1279. BIO_set_retry_read(bio);
  1280. return (-1);
  1281. }
  1282. }
  1283. goto start;
  1284. }
  1285. switch (rr->type) {
  1286. default:
  1287. #ifndef OPENSSL_NO_TLS
  1288. /* TLS just ignores unknown message types */
  1289. if (s->version == TLS1_VERSION) {
  1290. rr->length = 0;
  1291. goto start;
  1292. }
  1293. #endif
  1294. al = SSL_AD_UNEXPECTED_MESSAGE;
  1295. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1296. goto f_err;
  1297. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1298. case SSL3_RT_ALERT:
  1299. case SSL3_RT_HANDSHAKE:
  1300. /*
  1301. * we already handled all of these, with the possible exception of
  1302. * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
  1303. * happen when type != rr->type
  1304. */
  1305. al = SSL_AD_UNEXPECTED_MESSAGE;
  1306. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  1307. goto f_err;
  1308. case SSL3_RT_APPLICATION_DATA:
  1309. /*
  1310. * At this point, we were expecting handshake data, but have
  1311. * application data. If the library was running inside ssl3_read()
  1312. * (i.e. in_read_app_data is set) and it makes sense to read
  1313. * application data at this point (session renegotiation not yet
  1314. * started), we will indulge it.
  1315. */
  1316. if (s->s3->in_read_app_data &&
  1317. (s->s3->total_renegotiations != 0) &&
  1318. (((s->state & SSL_ST_CONNECT) &&
  1319. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1320. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1321. ) || ((s->state & SSL_ST_ACCEPT) &&
  1322. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1323. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1324. )
  1325. )) {
  1326. s->s3->in_read_app_data = 2;
  1327. return (-1);
  1328. } else {
  1329. al = SSL_AD_UNEXPECTED_MESSAGE;
  1330. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1331. goto f_err;
  1332. }
  1333. }
  1334. /* not reached */
  1335. f_err:
  1336. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1337. err:
  1338. return (-1);
  1339. }
  1340. int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
  1341. {
  1342. int i;
  1343. #ifndef OPENSSL_NO_SCTP
  1344. /*
  1345. * Check if we have to continue an interrupted handshake for reading
  1346. * belated app data with SCTP.
  1347. */
  1348. if ((SSL_in_init(s) && !s->in_handshake) ||
  1349. (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
  1350. (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
  1351. || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)))
  1352. #else
  1353. if (SSL_in_init(s) && !s->in_handshake)
  1354. #endif
  1355. {
  1356. i = s->handshake_func(s);
  1357. if (i < 0)
  1358. return (i);
  1359. if (i == 0) {
  1360. SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,
  1361. SSL_R_SSL_HANDSHAKE_FAILURE);
  1362. return -1;
  1363. }
  1364. }
  1365. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  1366. SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES, SSL_R_DTLS_MESSAGE_TOO_BIG);
  1367. return -1;
  1368. }
  1369. i = dtls1_write_bytes(s, type, buf_, len);
  1370. return i;
  1371. }
  1372. /*
  1373. * this only happens when a client hello is received and a handshake
  1374. * is started.
  1375. */
  1376. static int
  1377. have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  1378. int len, int peek)
  1379. {
  1380. if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
  1381. /* (partially) satisfy request from storage */
  1382. {
  1383. unsigned char *src = s->d1->handshake_fragment;
  1384. unsigned char *dst = buf;
  1385. unsigned int k, n;
  1386. /* peek == 0 */
  1387. n = 0;
  1388. while ((len > 0) && (s->d1->handshake_fragment_len > 0)) {
  1389. *dst++ = *src++;
  1390. len--;
  1391. s->d1->handshake_fragment_len--;
  1392. n++;
  1393. }
  1394. /* move any remaining fragment bytes: */
  1395. for (k = 0; k < s->d1->handshake_fragment_len; k++)
  1396. s->d1->handshake_fragment[k] = *src++;
  1397. return n;
  1398. }
  1399. return 0;
  1400. }
  1401. /*
  1402. * Call this to write data in records of type 'type' It will return <= 0 if
  1403. * not all data has been sent or non-blocking IO.
  1404. */
  1405. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
  1406. {
  1407. int i;
  1408. OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  1409. s->rwstate = SSL_NOTHING;
  1410. i = do_dtls1_write(s, type, buf, len, 0);
  1411. return i;
  1412. }
  1413. int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
  1414. unsigned int len, int create_empty_fragment)
  1415. {
  1416. unsigned char *p, *pseq;
  1417. int i, mac_size, clear = 0;
  1418. int prefix_len = 0;
  1419. int eivlen;
  1420. SSL3_RECORD *wr;
  1421. SSL3_BUFFER *wb;
  1422. SSL_SESSION *sess;
  1423. /*
  1424. * first check if there is a SSL3_BUFFER still being written out. This
  1425. * will happen with non blocking IO
  1426. */
  1427. if (s->s3->wbuf.left != 0) {
  1428. OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */
  1429. return (ssl3_write_pending(s, type, buf, len));
  1430. }
  1431. /* If we have an alert to send, lets send it */
  1432. if (s->s3->alert_dispatch) {
  1433. i = s->method->ssl_dispatch_alert(s);
  1434. if (i <= 0)
  1435. return (i);
  1436. /* if it went, fall through and send more stuff */
  1437. }
  1438. if (len == 0 && !create_empty_fragment)
  1439. return 0;
  1440. wr = &(s->s3->wrec);
  1441. wb = &(s->s3->wbuf);
  1442. sess = s->session;
  1443. if ((sess == NULL) ||
  1444. (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
  1445. clear = 1;
  1446. if (clear)
  1447. mac_size = 0;
  1448. else {
  1449. mac_size = EVP_MD_CTX_size(s->write_hash);
  1450. if (mac_size < 0)
  1451. goto err;
  1452. }
  1453. /* DTLS implements explicit IV, so no need for empty fragments */
  1454. #if 0
  1455. /*
  1456. * 'create_empty_fragment' is true only when this function calls itself
  1457. */
  1458. if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
  1459. && SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
  1460. {
  1461. /*
  1462. * countermeasure against known-IV weakness in CBC ciphersuites (see
  1463. * http://www.openssl.org/~bodo/tls-cbc.txt)
  1464. */
  1465. if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
  1466. /*
  1467. * recursive function call with 'create_empty_fragment' set; this
  1468. * prepares and buffers the data for an empty fragment (these
  1469. * 'prefix_len' bytes are sent out later together with the actual
  1470. * payload)
  1471. */
  1472. prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
  1473. if (prefix_len <= 0)
  1474. goto err;
  1475. if (s->s3->wbuf.len <
  1476. (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) {
  1477. /* insufficient space */
  1478. SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
  1479. goto err;
  1480. }
  1481. }
  1482. s->s3->empty_fragment_done = 1;
  1483. }
  1484. #endif
  1485. p = wb->buf + prefix_len;
  1486. /* write the header */
  1487. *(p++) = type & 0xff;
  1488. wr->type = type;
  1489. /*
  1490. * Special case: for hello verify request, client version 1.0 and we
  1491. * haven't decided which version to use yet send back using version 1.0
  1492. * header: otherwise some clients will ignore it.
  1493. */
  1494. if (s->method->version == DTLS_ANY_VERSION) {
  1495. *(p++) = DTLS1_VERSION >> 8;
  1496. *(p++) = DTLS1_VERSION & 0xff;
  1497. } else {
  1498. *(p++) = s->version >> 8;
  1499. *(p++) = s->version & 0xff;
  1500. }
  1501. /* field where we are to write out packet epoch, seq num and len */
  1502. pseq = p;
  1503. p += 10;
  1504. /* Explicit IV length, block ciphers appropriate version flag */
  1505. if (s->enc_write_ctx) {
  1506. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  1507. if (mode == EVP_CIPH_CBC_MODE) {
  1508. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  1509. if (eivlen <= 1)
  1510. eivlen = 0;
  1511. }
  1512. /* Need explicit part of IV for GCM mode */
  1513. else if (mode == EVP_CIPH_GCM_MODE)
  1514. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  1515. else
  1516. eivlen = 0;
  1517. } else
  1518. eivlen = 0;
  1519. /* lets setup the record stuff. */
  1520. wr->data = p + eivlen; /* make room for IV in case of CBC */
  1521. wr->length = (int)len;
  1522. wr->input = (unsigned char *)buf;
  1523. /*
  1524. * we now 'read' from wr->input, wr->length bytes into wr->data
  1525. */
  1526. /* first we compress */
  1527. if (s->compress != NULL) {
  1528. if (!ssl3_do_compress(s)) {
  1529. SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
  1530. goto err;
  1531. }
  1532. } else {
  1533. memcpy(wr->data, wr->input, wr->length);
  1534. wr->input = wr->data;
  1535. }
  1536. /*
  1537. * we should still have the output to wr->data and the input from
  1538. * wr->input. Length should be wr->length. wr->data still points in the
  1539. * wb->buf
  1540. */
  1541. if (mac_size != 0) {
  1542. if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0)
  1543. goto err;
  1544. wr->length += mac_size;
  1545. }
  1546. /* this is true regardless of mac size */
  1547. wr->input = p;
  1548. wr->data = p;
  1549. if (eivlen)
  1550. wr->length += eivlen;
  1551. if (s->method->ssl3_enc->enc(s, 1) < 1)
  1552. goto err;
  1553. /* record length after mac and block padding */
  1554. /*
  1555. * if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
  1556. * SSL_in_init(s)))
  1557. */
  1558. /* there's only one epoch between handshake and app data */
  1559. s2n(s->d1->w_epoch, pseq);
  1560. /* XDTLS: ?? */
  1561. /*
  1562. * else s2n(s->d1->handshake_epoch, pseq);
  1563. */
  1564. memcpy(pseq, &(s->s3->write_sequence[2]), 6);
  1565. pseq += 6;
  1566. s2n(wr->length, pseq);
  1567. if (s->msg_callback)
  1568. s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
  1569. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  1570. /*
  1571. * we should now have wr->data pointing to the encrypted data, which is
  1572. * wr->length long
  1573. */
  1574. wr->type = type; /* not needed but helps for debugging */
  1575. wr->length += DTLS1_RT_HEADER_LENGTH;
  1576. #if 0 /* this is now done at the message layer */
  1577. /* buffer the record, making it easy to handle retransmits */
  1578. if (type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1579. dtls1_buffer_record(s, wr->data, wr->length,
  1580. *((PQ_64BIT *) & (s->s3->write_sequence[0])));
  1581. #endif
  1582. ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
  1583. if (create_empty_fragment) {
  1584. /*
  1585. * we are in a recursive call; just return the length, don't write
  1586. * out anything here
  1587. */
  1588. return wr->length;
  1589. }
  1590. /* now let's set up wb */
  1591. wb->left = prefix_len + wr->length;
  1592. wb->offset = 0;
  1593. /*
  1594. * memorize arguments so that ssl3_write_pending can detect bad write
  1595. * retries later
  1596. */
  1597. s->s3->wpend_tot = len;
  1598. s->s3->wpend_buf = buf;
  1599. s->s3->wpend_type = type;
  1600. s->s3->wpend_ret = len;
  1601. /* we now just need to write the buffer */
  1602. return ssl3_write_pending(s, type, buf, len);
  1603. err:
  1604. return -1;
  1605. }
  1606. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
  1607. {
  1608. int cmp;
  1609. unsigned int shift;
  1610. const unsigned char *seq = s->s3->read_sequence;
  1611. cmp = satsub64be(seq, bitmap->max_seq_num);
  1612. if (cmp > 0) {
  1613. memcpy(s->s3->rrec.seq_num, seq, 8);
  1614. return 1; /* this record in new */
  1615. }
  1616. shift = -cmp;
  1617. if (shift >= sizeof(bitmap->map) * 8)
  1618. return 0; /* stale, outside the window */
  1619. else if (bitmap->map & (1UL << shift))
  1620. return 0; /* record previously received */
  1621. memcpy(s->s3->rrec.seq_num, seq, 8);
  1622. return 1;
  1623. }
  1624. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
  1625. {
  1626. int cmp;
  1627. unsigned int shift;
  1628. const unsigned char *seq = s->s3->read_sequence;
  1629. cmp = satsub64be(seq, bitmap->max_seq_num);
  1630. if (cmp > 0) {
  1631. shift = cmp;
  1632. if (shift < sizeof(bitmap->map) * 8)
  1633. bitmap->map <<= shift, bitmap->map |= 1UL;
  1634. else
  1635. bitmap->map = 1UL;
  1636. memcpy(bitmap->max_seq_num, seq, 8);
  1637. } else {
  1638. shift = -cmp;
  1639. if (shift < sizeof(bitmap->map) * 8)
  1640. bitmap->map |= 1UL << shift;
  1641. }
  1642. }
  1643. int dtls1_dispatch_alert(SSL *s)
  1644. {
  1645. int i, j;
  1646. void (*cb) (const SSL *ssl, int type, int val) = NULL;
  1647. unsigned char buf[DTLS1_AL_HEADER_LENGTH];
  1648. unsigned char *ptr = &buf[0];
  1649. s->s3->alert_dispatch = 0;
  1650. memset(buf, 0x00, sizeof(buf));
  1651. *ptr++ = s->s3->send_alert[0];
  1652. *ptr++ = s->s3->send_alert[1];
  1653. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1654. if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
  1655. s2n(s->d1->handshake_read_seq, ptr);
  1656. # if 0
  1657. if (s->d1->r_msg_hdr.frag_off == 0)
  1658. /*
  1659. * waiting for a new msg
  1660. */
  1661. else
  1662. s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
  1663. # endif
  1664. # if 0
  1665. fprintf(stderr,
  1666. "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",
  1667. s->d1->handshake_read_seq, s->d1->r_msg_hdr.seq);
  1668. # endif
  1669. l2n3(s->d1->r_msg_hdr.frag_off, ptr);
  1670. }
  1671. #endif
  1672. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
  1673. if (i <= 0) {
  1674. s->s3->alert_dispatch = 1;
  1675. /* fprintf( stderr, "not done with alert\n" ); */
  1676. } else {
  1677. if (s->s3->send_alert[0] == SSL3_AL_FATAL
  1678. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1679. || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1680. #endif
  1681. )
  1682. (void)BIO_flush(s->wbio);
  1683. if (s->msg_callback)
  1684. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
  1685. 2, s, s->msg_callback_arg);
  1686. if (s->info_callback != NULL)
  1687. cb = s->info_callback;
  1688. else if (s->ctx->info_callback != NULL)
  1689. cb = s->ctx->info_callback;
  1690. if (cb != NULL) {
  1691. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  1692. cb(s, SSL_CB_WRITE_ALERT, j);
  1693. }
  1694. }
  1695. return (i);
  1696. }
  1697. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  1698. unsigned int *is_next_epoch)
  1699. {
  1700. *is_next_epoch = 0;
  1701. /* In current epoch, accept HM, CCS, DATA, & ALERT */
  1702. if (rr->epoch == s->d1->r_epoch)
  1703. return &s->d1->bitmap;
  1704. /*
  1705. * Only HM and ALERT messages can be from the next epoch and only if we
  1706. * have already processed all of the unprocessed records from the last
  1707. * epoch
  1708. */
  1709. else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
  1710. s->d1->unprocessed_rcds.epoch != s->d1->r_epoch &&
  1711. (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
  1712. *is_next_epoch = 1;
  1713. return &s->d1->next_bitmap;
  1714. }
  1715. return NULL;
  1716. }
  1717. #if 0
  1718. static int
  1719. dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
  1720. unsigned short *priority, unsigned long *offset)
  1721. {
  1722. /* alerts are passed up immediately */
  1723. if (rr->type == SSL3_RT_APPLICATION_DATA || rr->type == SSL3_RT_ALERT)
  1724. return 0;
  1725. /*
  1726. * Only need to buffer if a handshake is underway. (this implies that
  1727. * Hello Request and Client Hello are passed up immediately)
  1728. */
  1729. if (SSL_in_init(s)) {
  1730. unsigned char *data = rr->data;
  1731. /* need to extract the HM/CCS sequence number here */
  1732. if (rr->type == SSL3_RT_HANDSHAKE ||
  1733. rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1734. unsigned short seq_num;
  1735. struct hm_header_st msg_hdr;
  1736. struct ccs_header_st ccs_hdr;
  1737. if (rr->type == SSL3_RT_HANDSHAKE) {
  1738. dtls1_get_message_header(data, &msg_hdr);
  1739. seq_num = msg_hdr.seq;
  1740. *offset = msg_hdr.frag_off;
  1741. } else {
  1742. dtls1_get_ccs_header(data, &ccs_hdr);
  1743. seq_num = ccs_hdr.seq;
  1744. *offset = 0;
  1745. }
  1746. /*
  1747. * this is either a record we're waiting for, or a retransmit of
  1748. * something we happened to previously receive (higher layers
  1749. * will drop the repeat silently
  1750. */
  1751. if (seq_num < s->d1->handshake_read_seq)
  1752. return 0;
  1753. if (rr->type == SSL3_RT_HANDSHAKE &&
  1754. seq_num == s->d1->handshake_read_seq &&
  1755. msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
  1756. return 0;
  1757. else if (seq_num == s->d1->handshake_read_seq &&
  1758. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
  1759. msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
  1760. return 0;
  1761. else {
  1762. *priority = seq_num;
  1763. return 1;
  1764. }
  1765. } else /* unknown record type */
  1766. return 0;
  1767. }
  1768. return 0;
  1769. }
  1770. #endif
  1771. void dtls1_reset_seq_numbers(SSL *s, int rw)
  1772. {
  1773. unsigned char *seq;
  1774. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  1775. if (rw & SSL3_CC_READ) {
  1776. seq = s->s3->read_sequence;
  1777. s->d1->r_epoch++;
  1778. memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
  1779. memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
  1780. /*
  1781. * We must not use any buffered messages received from the previous
  1782. * epoch
  1783. */
  1784. dtls1_clear_received_buffer(s);
  1785. } else {
  1786. seq = s->s3->write_sequence;
  1787. memcpy(s->d1->last_write_sequence, seq,
  1788. sizeof(s->s3->write_sequence));
  1789. s->d1->w_epoch++;
  1790. }
  1791. memset(seq, 0x00, seq_bytes);
  1792. }