d1_pkt.c 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921
  1. /* ssl/d1_pkt.c */
  2. /*
  3. * DTLS implementation written by Nagendra Modadugu
  4. * (nagendra@cs.stanford.edu) 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. * openssl-core@openssl.org.
  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. * (eay@cryptsoft.com). This product includes software written by Tim
  56. * Hudson (tjh@cryptsoft.com).
  57. *
  58. */
  59. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  60. * All rights reserved.
  61. *
  62. * This package is an SSL implementation written
  63. * by Eric Young (eay@cryptsoft.com).
  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 (tjh@cryptsoft.com).
  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 (eay@cryptsoft.com)"
  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 (tjh@cryptsoft.com)"
  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. if (s->msg_callback)
  541. s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
  542. s, s->msg_callback_arg);
  543. /* Pull apart the header into the DTLS1_RECORD */
  544. rr->type = *(p++);
  545. ssl_major = *(p++);
  546. ssl_minor = *(p++);
  547. version = (ssl_major << 8) | ssl_minor;
  548. /* sequence number is 64 bits, with top 2 bytes = epoch */
  549. n2s(p, rr->epoch);
  550. memcpy(&(s->s3->read_sequence[2]), p, 6);
  551. p += 6;
  552. n2s(p, rr->length);
  553. /* Lets check version */
  554. if (!s->first_packet) {
  555. if (version != s->version) {
  556. /* unexpected version, silently discard */
  557. rr->length = 0;
  558. s->packet_length = 0;
  559. goto again;
  560. }
  561. }
  562. if ((version & 0xff00) != (s->version & 0xff00)) {
  563. /* wrong version, silently discard record */
  564. rr->length = 0;
  565. s->packet_length = 0;
  566. goto again;
  567. }
  568. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  569. /* record too long, silently discard it */
  570. rr->length = 0;
  571. s->packet_length = 0;
  572. goto again;
  573. }
  574. /* now s->rstate == SSL_ST_READ_BODY */
  575. }
  576. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  577. if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
  578. /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
  579. i = rr->length;
  580. n = ssl3_read_n(s, i, i, 1);
  581. /* this packet contained a partial record, dump it */
  582. if (n != i) {
  583. rr->length = 0;
  584. s->packet_length = 0;
  585. goto again;
  586. }
  587. /*
  588. * now n == rr->length, and s->packet_length ==
  589. * DTLS1_RT_HEADER_LENGTH + rr->length
  590. */
  591. }
  592. s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
  593. /* match epochs. NULL means the packet is dropped on the floor */
  594. bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
  595. if (bitmap == NULL) {
  596. rr->length = 0;
  597. s->packet_length = 0; /* dump this record */
  598. goto again; /* get another record */
  599. }
  600. #ifndef OPENSSL_NO_SCTP
  601. /* Only do replay check if no SCTP bio */
  602. if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
  603. #endif
  604. /*
  605. * Check whether this is a repeat, or aged record. Don't check if
  606. * we're listening and this message is a ClientHello. They can look
  607. * as if they're replayed, since they arrive from different
  608. * connections and would be dropped unnecessarily.
  609. */
  610. if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
  611. s->packet_length > DTLS1_RT_HEADER_LENGTH &&
  612. s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
  613. !dtls1_record_replay_check(s, bitmap)) {
  614. rr->length = 0;
  615. s->packet_length = 0; /* dump this record */
  616. goto again; /* get another record */
  617. }
  618. #ifndef OPENSSL_NO_SCTP
  619. }
  620. #endif
  621. /* just read a 0 length packet */
  622. if (rr->length == 0)
  623. goto again;
  624. /*
  625. * If this record is from the next epoch (either HM or ALERT), and a
  626. * handshake is currently in progress, buffer it since it cannot be
  627. * processed at this time. However, do not buffer anything while
  628. * listening.
  629. */
  630. if (is_next_epoch) {
  631. if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {
  632. if (dtls1_buffer_record
  633. (s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0)
  634. return -1;
  635. /* Mark receipt of record. */
  636. dtls1_record_bitmap_update(s, bitmap);
  637. }
  638. rr->length = 0;
  639. s->packet_length = 0;
  640. goto again;
  641. }
  642. if (!dtls1_process_record(s)) {
  643. rr->length = 0;
  644. s->packet_length = 0; /* dump this record */
  645. goto again; /* get another record */
  646. }
  647. dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
  648. return (1);
  649. }
  650. /*-
  651. * Return up to 'len' payload bytes received in 'type' records.
  652. * 'type' is one of the following:
  653. *
  654. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  655. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  656. * - 0 (during a shutdown, no data has to be returned)
  657. *
  658. * If we don't have stored data to work from, read a SSL/TLS record first
  659. * (possibly multiple records if we still don't have anything to return).
  660. *
  661. * This function must handle any surprises the peer may have for us, such as
  662. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  663. * a surprise, but handled as if it were), or renegotiation requests.
  664. * Also if record payloads contain fragments too small to process, we store
  665. * them until there is enough for the respective protocol (the record protocol
  666. * may use arbitrary fragmentation and even interleaving):
  667. * Change cipher spec protocol
  668. * just 1 byte needed, no need for keeping anything stored
  669. * Alert protocol
  670. * 2 bytes needed (AlertLevel, AlertDescription)
  671. * Handshake protocol
  672. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  673. * to detect unexpected Client Hello and Hello Request messages
  674. * here, anything else is handled by higher layers
  675. * Application data protocol
  676. * none of our business
  677. */
  678. int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  679. {
  680. int al, i, j, ret;
  681. unsigned int n;
  682. SSL3_RECORD *rr;
  683. void (*cb) (const SSL *ssl, int type2, int val) = NULL;
  684. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  685. if (!ssl3_setup_buffers(s))
  686. return (-1);
  687. /* XXX: check what the second '&& type' is about */
  688. if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
  689. (type != SSL3_RT_HANDSHAKE) && type) ||
  690. (peek && (type != SSL3_RT_APPLICATION_DATA))) {
  691. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  692. return -1;
  693. }
  694. /*
  695. * check whether there's a handshake message (client hello?) waiting
  696. */
  697. if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
  698. return ret;
  699. /*
  700. * Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
  701. */
  702. #ifndef OPENSSL_NO_SCTP
  703. /*
  704. * Continue handshake if it had to be interrupted to read app data with
  705. * SCTP.
  706. */
  707. if ((!s->in_handshake && SSL_in_init(s)) ||
  708. (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  709. (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
  710. || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)
  711. && s->s3->in_read_app_data != 2))
  712. #else
  713. if (!s->in_handshake && SSL_in_init(s))
  714. #endif
  715. {
  716. /* type == SSL3_RT_APPLICATION_DATA */
  717. i = s->handshake_func(s);
  718. if (i < 0)
  719. return (i);
  720. if (i == 0) {
  721. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  722. return (-1);
  723. }
  724. }
  725. start:
  726. s->rwstate = SSL_NOTHING;
  727. /*-
  728. * s->s3->rrec.type - is the type of record
  729. * s->s3->rrec.data, - data
  730. * s->s3->rrec.off, - offset into 'data' for next read
  731. * s->s3->rrec.length, - number of bytes.
  732. */
  733. rr = &(s->s3->rrec);
  734. /*
  735. * We are not handshaking and have no data yet, so process data buffered
  736. * during the last handshake in advance, if any.
  737. */
  738. if (s->state == SSL_ST_OK && rr->length == 0) {
  739. pitem *item;
  740. item = pqueue_pop(s->d1->buffered_app_data.q);
  741. if (item) {
  742. #ifndef OPENSSL_NO_SCTP
  743. /* Restore bio_dgram_sctp_rcvinfo struct */
  744. if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
  745. DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
  746. BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
  747. sizeof(rdata->recordinfo), &rdata->recordinfo);
  748. }
  749. #endif
  750. dtls1_copy_record(s, item);
  751. OPENSSL_free(item->data);
  752. pitem_free(item);
  753. }
  754. }
  755. /* Check for timeout */
  756. if (dtls1_handle_timeout(s) > 0)
  757. goto start;
  758. /* get new packet if necessary */
  759. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
  760. ret = dtls1_get_record(s);
  761. if (ret <= 0) {
  762. ret = dtls1_read_failed(s, ret);
  763. /* anything other than a timeout is an error */
  764. if (ret <= 0)
  765. return (ret);
  766. else
  767. goto start;
  768. }
  769. }
  770. if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) {
  771. rr->length = 0;
  772. goto start;
  773. }
  774. /* we now have a packet which can be read and processed */
  775. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  776. * reset by ssl3_get_finished */
  777. && (rr->type != SSL3_RT_HANDSHAKE)) {
  778. /*
  779. * We now have application data between CCS and Finished. Most likely
  780. * the packets were reordered on their way, so buffer the application
  781. * data for later processing rather than dropping the connection.
  782. */
  783. if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) <
  784. 0) {
  785. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  786. return -1;
  787. }
  788. rr->length = 0;
  789. goto start;
  790. }
  791. /*
  792. * If the other end has shut down, throw anything we read away (even in
  793. * 'peek' mode)
  794. */
  795. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  796. rr->length = 0;
  797. s->rwstate = SSL_NOTHING;
  798. return (0);
  799. }
  800. if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or
  801. * SSL3_RT_HANDSHAKE */
  802. /*
  803. * make sure that we are not getting application data when we are
  804. * doing a handshake for the first time
  805. */
  806. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  807. (s->enc_read_ctx == NULL)) {
  808. al = SSL_AD_UNEXPECTED_MESSAGE;
  809. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
  810. goto f_err;
  811. }
  812. if (len <= 0)
  813. return (len);
  814. if ((unsigned int)len > rr->length)
  815. n = rr->length;
  816. else
  817. n = (unsigned int)len;
  818. memcpy(buf, &(rr->data[rr->off]), n);
  819. if (!peek) {
  820. rr->length -= n;
  821. rr->off += n;
  822. if (rr->length == 0) {
  823. s->rstate = SSL_ST_READ_HEADER;
  824. rr->off = 0;
  825. }
  826. }
  827. #ifndef OPENSSL_NO_SCTP
  828. /*
  829. * We were about to renegotiate but had to read belated application
  830. * data first, so retry.
  831. */
  832. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  833. rr->type == SSL3_RT_APPLICATION_DATA &&
  834. (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
  835. || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) {
  836. s->rwstate = SSL_READING;
  837. BIO_clear_retry_flags(SSL_get_rbio(s));
  838. BIO_set_retry_read(SSL_get_rbio(s));
  839. }
  840. /*
  841. * We might had to delay a close_notify alert because of reordered
  842. * app data. If there was an alert and there is no message to read
  843. * anymore, finally set shutdown.
  844. */
  845. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  846. s->d1->shutdown_received
  847. && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
  848. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  849. return (0);
  850. }
  851. #endif
  852. return (n);
  853. }
  854. /*
  855. * If we get here, then type != rr->type; if we have a handshake message,
  856. * then it was unexpected (Hello Request or Client Hello).
  857. */
  858. /*
  859. * In case of record types for which we have 'fragment' storage, fill
  860. * that so that we can process the data at a fixed place.
  861. */
  862. {
  863. unsigned int k, dest_maxlen = 0;
  864. unsigned char *dest = NULL;
  865. unsigned int *dest_len = NULL;
  866. if (rr->type == SSL3_RT_HANDSHAKE) {
  867. dest_maxlen = sizeof s->d1->handshake_fragment;
  868. dest = s->d1->handshake_fragment;
  869. dest_len = &s->d1->handshake_fragment_len;
  870. } else if (rr->type == SSL3_RT_ALERT) {
  871. dest_maxlen = sizeof(s->d1->alert_fragment);
  872. dest = s->d1->alert_fragment;
  873. dest_len = &s->d1->alert_fragment_len;
  874. }
  875. #ifndef OPENSSL_NO_HEARTBEATS
  876. else if (rr->type == TLS1_RT_HEARTBEAT) {
  877. dtls1_process_heartbeat(s);
  878. /* Exit and notify application to read again */
  879. rr->length = 0;
  880. s->rwstate = SSL_READING;
  881. BIO_clear_retry_flags(SSL_get_rbio(s));
  882. BIO_set_retry_read(SSL_get_rbio(s));
  883. return (-1);
  884. }
  885. #endif
  886. /* else it's a CCS message, or application data or wrong */
  887. else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
  888. /*
  889. * Application data while renegotiating is allowed. Try again
  890. * reading.
  891. */
  892. if (rr->type == SSL3_RT_APPLICATION_DATA) {
  893. BIO *bio;
  894. s->s3->in_read_app_data = 2;
  895. bio = SSL_get_rbio(s);
  896. s->rwstate = SSL_READING;
  897. BIO_clear_retry_flags(bio);
  898. BIO_set_retry_read(bio);
  899. return (-1);
  900. }
  901. /* Not certain if this is the right error handling */
  902. al = SSL_AD_UNEXPECTED_MESSAGE;
  903. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  904. goto f_err;
  905. }
  906. if (dest_maxlen > 0) {
  907. /*
  908. * XDTLS: In a pathalogical case, the Client Hello may be
  909. * fragmented--don't always expect dest_maxlen bytes
  910. */
  911. if (rr->length < dest_maxlen) {
  912. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  913. /*
  914. * for normal alerts rr->length is 2, while
  915. * dest_maxlen is 7 if we were to handle this
  916. * non-existing alert...
  917. */
  918. FIX ME
  919. #endif
  920. s->rstate = SSL_ST_READ_HEADER;
  921. rr->length = 0;
  922. goto start;
  923. }
  924. /* now move 'n' bytes: */
  925. for (k = 0; k < dest_maxlen; k++) {
  926. dest[k] = rr->data[rr->off++];
  927. rr->length--;
  928. }
  929. *dest_len = dest_maxlen;
  930. }
  931. }
  932. /*-
  933. * s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
  934. * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
  935. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
  936. */
  937. /* If we are a client, check for an incoming 'Hello Request': */
  938. if ((!s->server) &&
  939. (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  940. (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  941. (s->session != NULL) && (s->session->cipher != NULL)) {
  942. s->d1->handshake_fragment_len = 0;
  943. if ((s->d1->handshake_fragment[1] != 0) ||
  944. (s->d1->handshake_fragment[2] != 0) ||
  945. (s->d1->handshake_fragment[3] != 0)) {
  946. al = SSL_AD_DECODE_ERROR;
  947. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
  948. goto f_err;
  949. }
  950. /*
  951. * no need to check sequence number on HELLO REQUEST messages
  952. */
  953. if (s->msg_callback)
  954. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  955. s->d1->handshake_fragment, 4, s,
  956. s->msg_callback_arg);
  957. if (SSL_is_init_finished(s) &&
  958. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  959. !s->s3->renegotiate) {
  960. s->d1->handshake_read_seq++;
  961. s->new_session = 1;
  962. ssl3_renegotiate(s);
  963. if (ssl3_renegotiate_check(s)) {
  964. i = s->handshake_func(s);
  965. if (i < 0)
  966. return (i);
  967. if (i == 0) {
  968. SSLerr(SSL_F_DTLS1_READ_BYTES,
  969. SSL_R_SSL_HANDSHAKE_FAILURE);
  970. return (-1);
  971. }
  972. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  973. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  974. BIO *bio;
  975. /*
  976. * In the case where we try to read application data,
  977. * but we trigger an SSL handshake, we return -1 with
  978. * the retry option set. Otherwise renegotiation may
  979. * cause nasty problems in the blocking world
  980. */
  981. s->rwstate = SSL_READING;
  982. bio = SSL_get_rbio(s);
  983. BIO_clear_retry_flags(bio);
  984. BIO_set_retry_read(bio);
  985. return (-1);
  986. }
  987. }
  988. }
  989. }
  990. /*
  991. * we either finished a handshake or ignored the request, now try
  992. * again to obtain the (application) data we were asked for
  993. */
  994. goto start;
  995. }
  996. if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
  997. int alert_level = s->d1->alert_fragment[0];
  998. int alert_descr = s->d1->alert_fragment[1];
  999. s->d1->alert_fragment_len = 0;
  1000. if (s->msg_callback)
  1001. s->msg_callback(0, s->version, SSL3_RT_ALERT,
  1002. s->d1->alert_fragment, 2, s, s->msg_callback_arg);
  1003. if (s->info_callback != NULL)
  1004. cb = s->info_callback;
  1005. else if (s->ctx->info_callback != NULL)
  1006. cb = s->ctx->info_callback;
  1007. if (cb != NULL) {
  1008. j = (alert_level << 8) | alert_descr;
  1009. cb(s, SSL_CB_READ_ALERT, j);
  1010. }
  1011. if (alert_level == SSL3_AL_WARNING) {
  1012. s->s3->warn_alert = alert_descr;
  1013. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  1014. #ifndef OPENSSL_NO_SCTP
  1015. /*
  1016. * With SCTP and streams the socket may deliver app data
  1017. * after a close_notify alert. We have to check this first so
  1018. * that nothing gets discarded.
  1019. */
  1020. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  1021. BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
  1022. s->d1->shutdown_received = 1;
  1023. s->rwstate = SSL_READING;
  1024. BIO_clear_retry_flags(SSL_get_rbio(s));
  1025. BIO_set_retry_read(SSL_get_rbio(s));
  1026. return -1;
  1027. }
  1028. #endif
  1029. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1030. return (0);
  1031. }
  1032. #if 0
  1033. /* XXX: this is a possible improvement in the future */
  1034. /* now check if it's a missing record */
  1035. if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
  1036. unsigned short seq;
  1037. unsigned int frag_off;
  1038. unsigned char *p = &(s->d1->alert_fragment[2]);
  1039. n2s(p, seq);
  1040. n2l3(p, frag_off);
  1041. dtls1_retransmit_message(s,
  1042. dtls1_get_queue_priority
  1043. (frag->msg_header.seq, 0), frag_off,
  1044. &found);
  1045. if (!found && SSL_in_init(s)) {
  1046. /*
  1047. * fprintf( stderr,"in init = %d\n", SSL_in_init(s));
  1048. */
  1049. /*
  1050. * requested a message not yet sent, send an alert
  1051. * ourselves
  1052. */
  1053. ssl3_send_alert(s, SSL3_AL_WARNING,
  1054. DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  1055. }
  1056. }
  1057. #endif
  1058. } else if (alert_level == SSL3_AL_FATAL) {
  1059. char tmp[16];
  1060. s->rwstate = SSL_NOTHING;
  1061. s->s3->fatal_alert = alert_descr;
  1062. SSLerr(SSL_F_DTLS1_READ_BYTES,
  1063. SSL_AD_REASON_OFFSET + alert_descr);
  1064. BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
  1065. ERR_add_error_data(2, "SSL alert number ", tmp);
  1066. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  1067. SSL_CTX_remove_session(s->ctx, s->session);
  1068. return (0);
  1069. } else {
  1070. al = SSL_AD_ILLEGAL_PARAMETER;
  1071. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
  1072. goto f_err;
  1073. }
  1074. goto start;
  1075. }
  1076. if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
  1077. * shutdown */
  1078. s->rwstate = SSL_NOTHING;
  1079. rr->length = 0;
  1080. return (0);
  1081. }
  1082. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1083. struct ccs_header_st ccs_hdr;
  1084. unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
  1085. dtls1_get_ccs_header(rr->data, &ccs_hdr);
  1086. if (s->version == DTLS1_BAD_VER)
  1087. ccs_hdr_len = 3;
  1088. /*
  1089. * 'Change Cipher Spec' is just a single byte, so we know exactly
  1090. * what the record payload has to look like
  1091. */
  1092. /* XDTLS: check that epoch is consistent */
  1093. if ((rr->length != ccs_hdr_len) ||
  1094. (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
  1095. i = SSL_AD_ILLEGAL_PARAMETER;
  1096. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  1097. goto err;
  1098. }
  1099. rr->length = 0;
  1100. if (s->msg_callback)
  1101. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  1102. rr->data, 1, s, s->msg_callback_arg);
  1103. /*
  1104. * We can't process a CCS now, because previous handshake messages
  1105. * are still missing, so just drop it.
  1106. */
  1107. if (!s->d1->change_cipher_spec_ok) {
  1108. goto start;
  1109. }
  1110. s->d1->change_cipher_spec_ok = 0;
  1111. s->s3->change_cipher_spec = 1;
  1112. if (!ssl3_do_change_cipher_spec(s))
  1113. goto err;
  1114. /* do this whenever CCS is processed */
  1115. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  1116. if (s->version == DTLS1_BAD_VER)
  1117. s->d1->handshake_read_seq++;
  1118. #ifndef OPENSSL_NO_SCTP
  1119. /*
  1120. * Remember that a CCS has been received, so that an old key of
  1121. * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
  1122. * SCTP is used
  1123. */
  1124. BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
  1125. #endif
  1126. goto start;
  1127. }
  1128. /*
  1129. * Unexpected handshake message (Client Hello, or protocol violation)
  1130. */
  1131. if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  1132. !s->in_handshake) {
  1133. struct hm_header_st msg_hdr;
  1134. /* this may just be a stale retransmit */
  1135. dtls1_get_message_header(rr->data, &msg_hdr);
  1136. if (rr->epoch != s->d1->r_epoch) {
  1137. rr->length = 0;
  1138. goto start;
  1139. }
  1140. /*
  1141. * If we are server, we may have a repeated FINISHED of the client
  1142. * here, then retransmit our CCS and FINISHED.
  1143. */
  1144. if (msg_hdr.type == SSL3_MT_FINISHED) {
  1145. if (dtls1_check_timeout_num(s) < 0)
  1146. return -1;
  1147. dtls1_retransmit_buffered_messages(s);
  1148. rr->length = 0;
  1149. goto start;
  1150. }
  1151. if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
  1152. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
  1153. #if 0 /* worked only because C operator preferences
  1154. * are not as expected (and because this is
  1155. * not really needed for clients except for
  1156. * detecting protocol violations): */
  1157. s->state = SSL_ST_BEFORE | (s->server)
  1158. ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1159. #else
  1160. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1161. #endif
  1162. s->renegotiate = 1;
  1163. s->new_session = 1;
  1164. }
  1165. i = s->handshake_func(s);
  1166. if (i < 0)
  1167. return (i);
  1168. if (i == 0) {
  1169. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  1170. return (-1);
  1171. }
  1172. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  1173. if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
  1174. BIO *bio;
  1175. /*
  1176. * In the case where we try to read application data, but we
  1177. * trigger an SSL handshake, we return -1 with the retry
  1178. * option set. Otherwise renegotiation may cause nasty
  1179. * problems in the blocking world
  1180. */
  1181. s->rwstate = SSL_READING;
  1182. bio = SSL_get_rbio(s);
  1183. BIO_clear_retry_flags(bio);
  1184. BIO_set_retry_read(bio);
  1185. return (-1);
  1186. }
  1187. }
  1188. goto start;
  1189. }
  1190. switch (rr->type) {
  1191. default:
  1192. #ifndef OPENSSL_NO_TLS
  1193. /* TLS just ignores unknown message types */
  1194. if (s->version == TLS1_VERSION) {
  1195. rr->length = 0;
  1196. goto start;
  1197. }
  1198. #endif
  1199. al = SSL_AD_UNEXPECTED_MESSAGE;
  1200. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1201. goto f_err;
  1202. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1203. case SSL3_RT_ALERT:
  1204. case SSL3_RT_HANDSHAKE:
  1205. /*
  1206. * we already handled all of these, with the possible exception of
  1207. * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
  1208. * happen when type != rr->type
  1209. */
  1210. al = SSL_AD_UNEXPECTED_MESSAGE;
  1211. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  1212. goto f_err;
  1213. case SSL3_RT_APPLICATION_DATA:
  1214. /*
  1215. * At this point, we were expecting handshake data, but have
  1216. * application data. If the library was running inside ssl3_read()
  1217. * (i.e. in_read_app_data is set) and it makes sense to read
  1218. * application data at this point (session renegotiation not yet
  1219. * started), we will indulge it.
  1220. */
  1221. if (s->s3->in_read_app_data &&
  1222. (s->s3->total_renegotiations != 0) &&
  1223. (((s->state & SSL_ST_CONNECT) &&
  1224. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1225. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1226. ) || ((s->state & SSL_ST_ACCEPT) &&
  1227. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1228. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1229. )
  1230. )) {
  1231. s->s3->in_read_app_data = 2;
  1232. return (-1);
  1233. } else {
  1234. al = SSL_AD_UNEXPECTED_MESSAGE;
  1235. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  1236. goto f_err;
  1237. }
  1238. }
  1239. /* not reached */
  1240. f_err:
  1241. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1242. err:
  1243. return (-1);
  1244. }
  1245. int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
  1246. {
  1247. int i;
  1248. #ifndef OPENSSL_NO_SCTP
  1249. /*
  1250. * Check if we have to continue an interrupted handshake for reading
  1251. * belated app data with SCTP.
  1252. */
  1253. if ((SSL_in_init(s) && !s->in_handshake) ||
  1254. (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
  1255. (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
  1256. || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)))
  1257. #else
  1258. if (SSL_in_init(s) && !s->in_handshake)
  1259. #endif
  1260. {
  1261. i = s->handshake_func(s);
  1262. if (i < 0)
  1263. return (i);
  1264. if (i == 0) {
  1265. SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,
  1266. SSL_R_SSL_HANDSHAKE_FAILURE);
  1267. return -1;
  1268. }
  1269. }
  1270. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  1271. SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES, SSL_R_DTLS_MESSAGE_TOO_BIG);
  1272. return -1;
  1273. }
  1274. i = dtls1_write_bytes(s, type, buf_, len);
  1275. return i;
  1276. }
  1277. /*
  1278. * this only happens when a client hello is received and a handshake
  1279. * is started.
  1280. */
  1281. static int
  1282. have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  1283. int len, int peek)
  1284. {
  1285. if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
  1286. /* (partially) satisfy request from storage */
  1287. {
  1288. unsigned char *src = s->d1->handshake_fragment;
  1289. unsigned char *dst = buf;
  1290. unsigned int k, n;
  1291. /* peek == 0 */
  1292. n = 0;
  1293. while ((len > 0) && (s->d1->handshake_fragment_len > 0)) {
  1294. *dst++ = *src++;
  1295. len--;
  1296. s->d1->handshake_fragment_len--;
  1297. n++;
  1298. }
  1299. /* move any remaining fragment bytes: */
  1300. for (k = 0; k < s->d1->handshake_fragment_len; k++)
  1301. s->d1->handshake_fragment[k] = *src++;
  1302. return n;
  1303. }
  1304. return 0;
  1305. }
  1306. /*
  1307. * Call this to write data in records of type 'type' It will return <= 0 if
  1308. * not all data has been sent or non-blocking IO.
  1309. */
  1310. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
  1311. {
  1312. int i;
  1313. OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  1314. s->rwstate = SSL_NOTHING;
  1315. i = do_dtls1_write(s, type, buf, len, 0);
  1316. return i;
  1317. }
  1318. int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
  1319. unsigned int len, int create_empty_fragment)
  1320. {
  1321. unsigned char *p, *pseq;
  1322. int i, mac_size, clear = 0;
  1323. int prefix_len = 0;
  1324. int eivlen;
  1325. SSL3_RECORD *wr;
  1326. SSL3_BUFFER *wb;
  1327. SSL_SESSION *sess;
  1328. /*
  1329. * first check if there is a SSL3_BUFFER still being written out. This
  1330. * will happen with non blocking IO
  1331. */
  1332. if (s->s3->wbuf.left != 0) {
  1333. OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */
  1334. return (ssl3_write_pending(s, type, buf, len));
  1335. }
  1336. /* If we have an alert to send, lets send it */
  1337. if (s->s3->alert_dispatch) {
  1338. i = s->method->ssl_dispatch_alert(s);
  1339. if (i <= 0)
  1340. return (i);
  1341. /* if it went, fall through and send more stuff */
  1342. }
  1343. if (len == 0 && !create_empty_fragment)
  1344. return 0;
  1345. wr = &(s->s3->wrec);
  1346. wb = &(s->s3->wbuf);
  1347. sess = s->session;
  1348. if ((sess == NULL) ||
  1349. (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
  1350. clear = 1;
  1351. if (clear)
  1352. mac_size = 0;
  1353. else {
  1354. mac_size = EVP_MD_CTX_size(s->write_hash);
  1355. if (mac_size < 0)
  1356. goto err;
  1357. }
  1358. /* DTLS implements explicit IV, so no need for empty fragments */
  1359. #if 0
  1360. /*
  1361. * 'create_empty_fragment' is true only when this function calls itself
  1362. */
  1363. if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
  1364. && SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
  1365. {
  1366. /*
  1367. * countermeasure against known-IV weakness in CBC ciphersuites (see
  1368. * http://www.openssl.org/~bodo/tls-cbc.txt)
  1369. */
  1370. if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
  1371. /*
  1372. * recursive function call with 'create_empty_fragment' set; this
  1373. * prepares and buffers the data for an empty fragment (these
  1374. * 'prefix_len' bytes are sent out later together with the actual
  1375. * payload)
  1376. */
  1377. prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
  1378. if (prefix_len <= 0)
  1379. goto err;
  1380. if (s->s3->wbuf.len <
  1381. (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) {
  1382. /* insufficient space */
  1383. SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
  1384. goto err;
  1385. }
  1386. }
  1387. s->s3->empty_fragment_done = 1;
  1388. }
  1389. #endif
  1390. p = wb->buf + prefix_len;
  1391. /* write the header */
  1392. *(p++) = type & 0xff;
  1393. wr->type = type;
  1394. /*
  1395. * Special case: for hello verify request, client version 1.0 and we
  1396. * haven't decided which version to use yet send back using version 1.0
  1397. * header: otherwise some clients will ignore it.
  1398. */
  1399. if (s->method->version == DTLS_ANY_VERSION) {
  1400. *(p++) = DTLS1_VERSION >> 8;
  1401. *(p++) = DTLS1_VERSION & 0xff;
  1402. } else {
  1403. *(p++) = s->version >> 8;
  1404. *(p++) = s->version & 0xff;
  1405. }
  1406. /* field where we are to write out packet epoch, seq num and len */
  1407. pseq = p;
  1408. p += 10;
  1409. /* Explicit IV length, block ciphers appropriate version flag */
  1410. if (s->enc_write_ctx) {
  1411. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  1412. if (mode == EVP_CIPH_CBC_MODE) {
  1413. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  1414. if (eivlen <= 1)
  1415. eivlen = 0;
  1416. }
  1417. /* Need explicit part of IV for GCM mode */
  1418. else if (mode == EVP_CIPH_GCM_MODE)
  1419. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  1420. else
  1421. eivlen = 0;
  1422. } else
  1423. eivlen = 0;
  1424. /* lets setup the record stuff. */
  1425. wr->data = p + eivlen; /* make room for IV in case of CBC */
  1426. wr->length = (int)len;
  1427. wr->input = (unsigned char *)buf;
  1428. /*
  1429. * we now 'read' from wr->input, wr->length bytes into wr->data
  1430. */
  1431. /* first we compress */
  1432. if (s->compress != NULL) {
  1433. if (!ssl3_do_compress(s)) {
  1434. SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
  1435. goto err;
  1436. }
  1437. } else {
  1438. memcpy(wr->data, wr->input, wr->length);
  1439. wr->input = wr->data;
  1440. }
  1441. /*
  1442. * we should still have the output to wr->data and the input from
  1443. * wr->input. Length should be wr->length. wr->data still points in the
  1444. * wb->buf
  1445. */
  1446. if (mac_size != 0) {
  1447. if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0)
  1448. goto err;
  1449. wr->length += mac_size;
  1450. }
  1451. /* this is true regardless of mac size */
  1452. wr->input = p;
  1453. wr->data = p;
  1454. if (eivlen)
  1455. wr->length += eivlen;
  1456. if (s->method->ssl3_enc->enc(s, 1) < 1)
  1457. goto err;
  1458. /* record length after mac and block padding */
  1459. /*
  1460. * if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
  1461. * SSL_in_init(s)))
  1462. */
  1463. /* there's only one epoch between handshake and app data */
  1464. s2n(s->d1->w_epoch, pseq);
  1465. /* XDTLS: ?? */
  1466. /*
  1467. * else s2n(s->d1->handshake_epoch, pseq);
  1468. */
  1469. memcpy(pseq, &(s->s3->write_sequence[2]), 6);
  1470. pseq += 6;
  1471. s2n(wr->length, pseq);
  1472. if (s->msg_callback)
  1473. s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
  1474. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  1475. /*
  1476. * we should now have wr->data pointing to the encrypted data, which is
  1477. * wr->length long
  1478. */
  1479. wr->type = type; /* not needed but helps for debugging */
  1480. wr->length += DTLS1_RT_HEADER_LENGTH;
  1481. #if 0 /* this is now done at the message layer */
  1482. /* buffer the record, making it easy to handle retransmits */
  1483. if (type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1484. dtls1_buffer_record(s, wr->data, wr->length,
  1485. *((PQ_64BIT *) & (s->s3->write_sequence[0])));
  1486. #endif
  1487. ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
  1488. if (create_empty_fragment) {
  1489. /*
  1490. * we are in a recursive call; just return the length, don't write
  1491. * out anything here
  1492. */
  1493. return wr->length;
  1494. }
  1495. /* now let's set up wb */
  1496. wb->left = prefix_len + wr->length;
  1497. wb->offset = 0;
  1498. /*
  1499. * memorize arguments so that ssl3_write_pending can detect bad write
  1500. * retries later
  1501. */
  1502. s->s3->wpend_tot = len;
  1503. s->s3->wpend_buf = buf;
  1504. s->s3->wpend_type = type;
  1505. s->s3->wpend_ret = len;
  1506. /* we now just need to write the buffer */
  1507. return ssl3_write_pending(s, type, buf, len);
  1508. err:
  1509. return -1;
  1510. }
  1511. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
  1512. {
  1513. int cmp;
  1514. unsigned int shift;
  1515. const unsigned char *seq = s->s3->read_sequence;
  1516. cmp = satsub64be(seq, bitmap->max_seq_num);
  1517. if (cmp > 0) {
  1518. memcpy(s->s3->rrec.seq_num, seq, 8);
  1519. return 1; /* this record in new */
  1520. }
  1521. shift = -cmp;
  1522. if (shift >= sizeof(bitmap->map) * 8)
  1523. return 0; /* stale, outside the window */
  1524. else if (bitmap->map & (1UL << shift))
  1525. return 0; /* record previously received */
  1526. memcpy(s->s3->rrec.seq_num, seq, 8);
  1527. return 1;
  1528. }
  1529. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
  1530. {
  1531. int cmp;
  1532. unsigned int shift;
  1533. const unsigned char *seq = s->s3->read_sequence;
  1534. cmp = satsub64be(seq, bitmap->max_seq_num);
  1535. if (cmp > 0) {
  1536. shift = cmp;
  1537. if (shift < sizeof(bitmap->map) * 8)
  1538. bitmap->map <<= shift, bitmap->map |= 1UL;
  1539. else
  1540. bitmap->map = 1UL;
  1541. memcpy(bitmap->max_seq_num, seq, 8);
  1542. } else {
  1543. shift = -cmp;
  1544. if (shift < sizeof(bitmap->map) * 8)
  1545. bitmap->map |= 1UL << shift;
  1546. }
  1547. }
  1548. int dtls1_dispatch_alert(SSL *s)
  1549. {
  1550. int i, j;
  1551. void (*cb) (const SSL *ssl, int type, int val) = NULL;
  1552. unsigned char buf[DTLS1_AL_HEADER_LENGTH];
  1553. unsigned char *ptr = &buf[0];
  1554. s->s3->alert_dispatch = 0;
  1555. memset(buf, 0x00, sizeof(buf));
  1556. *ptr++ = s->s3->send_alert[0];
  1557. *ptr++ = s->s3->send_alert[1];
  1558. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1559. if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
  1560. s2n(s->d1->handshake_read_seq, ptr);
  1561. # if 0
  1562. if (s->d1->r_msg_hdr.frag_off == 0)
  1563. /*
  1564. * waiting for a new msg
  1565. */
  1566. else
  1567. s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
  1568. # endif
  1569. # if 0
  1570. fprintf(stderr,
  1571. "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",
  1572. s->d1->handshake_read_seq, s->d1->r_msg_hdr.seq);
  1573. # endif
  1574. l2n3(s->d1->r_msg_hdr.frag_off, ptr);
  1575. }
  1576. #endif
  1577. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
  1578. if (i <= 0) {
  1579. s->s3->alert_dispatch = 1;
  1580. /* fprintf( stderr, "not done with alert\n" ); */
  1581. } else {
  1582. if (s->s3->send_alert[0] == SSL3_AL_FATAL
  1583. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1584. || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1585. #endif
  1586. )
  1587. (void)BIO_flush(s->wbio);
  1588. if (s->msg_callback)
  1589. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
  1590. 2, s, s->msg_callback_arg);
  1591. if (s->info_callback != NULL)
  1592. cb = s->info_callback;
  1593. else if (s->ctx->info_callback != NULL)
  1594. cb = s->ctx->info_callback;
  1595. if (cb != NULL) {
  1596. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  1597. cb(s, SSL_CB_WRITE_ALERT, j);
  1598. }
  1599. }
  1600. return (i);
  1601. }
  1602. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  1603. unsigned int *is_next_epoch)
  1604. {
  1605. *is_next_epoch = 0;
  1606. /* In current epoch, accept HM, CCS, DATA, & ALERT */
  1607. if (rr->epoch == s->d1->r_epoch)
  1608. return &s->d1->bitmap;
  1609. /* Only HM and ALERT messages can be from the next epoch */
  1610. else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
  1611. (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
  1612. *is_next_epoch = 1;
  1613. return &s->d1->next_bitmap;
  1614. }
  1615. return NULL;
  1616. }
  1617. #if 0
  1618. static int
  1619. dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
  1620. unsigned short *priority, unsigned long *offset)
  1621. {
  1622. /* alerts are passed up immediately */
  1623. if (rr->type == SSL3_RT_APPLICATION_DATA || rr->type == SSL3_RT_ALERT)
  1624. return 0;
  1625. /*
  1626. * Only need to buffer if a handshake is underway. (this implies that
  1627. * Hello Request and Client Hello are passed up immediately)
  1628. */
  1629. if (SSL_in_init(s)) {
  1630. unsigned char *data = rr->data;
  1631. /* need to extract the HM/CCS sequence number here */
  1632. if (rr->type == SSL3_RT_HANDSHAKE ||
  1633. rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  1634. unsigned short seq_num;
  1635. struct hm_header_st msg_hdr;
  1636. struct ccs_header_st ccs_hdr;
  1637. if (rr->type == SSL3_RT_HANDSHAKE) {
  1638. dtls1_get_message_header(data, &msg_hdr);
  1639. seq_num = msg_hdr.seq;
  1640. *offset = msg_hdr.frag_off;
  1641. } else {
  1642. dtls1_get_ccs_header(data, &ccs_hdr);
  1643. seq_num = ccs_hdr.seq;
  1644. *offset = 0;
  1645. }
  1646. /*
  1647. * this is either a record we're waiting for, or a retransmit of
  1648. * something we happened to previously receive (higher layers
  1649. * will drop the repeat silently
  1650. */
  1651. if (seq_num < s->d1->handshake_read_seq)
  1652. return 0;
  1653. if (rr->type == SSL3_RT_HANDSHAKE &&
  1654. seq_num == s->d1->handshake_read_seq &&
  1655. msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
  1656. return 0;
  1657. else if (seq_num == s->d1->handshake_read_seq &&
  1658. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
  1659. msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
  1660. return 0;
  1661. else {
  1662. *priority = seq_num;
  1663. return 1;
  1664. }
  1665. } else /* unknown record type */
  1666. return 0;
  1667. }
  1668. return 0;
  1669. }
  1670. #endif
  1671. void dtls1_reset_seq_numbers(SSL *s, int rw)
  1672. {
  1673. unsigned char *seq;
  1674. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  1675. if (rw & SSL3_CC_READ) {
  1676. seq = s->s3->read_sequence;
  1677. s->d1->r_epoch++;
  1678. memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
  1679. memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
  1680. } else {
  1681. seq = s->s3->write_sequence;
  1682. memcpy(s->d1->last_write_sequence, seq,
  1683. sizeof(s->s3->write_sequence));
  1684. s->d1->w_epoch++;
  1685. }
  1686. memset(seq, 0x00, seq_bytes);
  1687. }