d1_pkt.c 66 KB

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