d1_pkt.c 65 KB

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