d1_pkt.c 61 KB

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