d1_pkt.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  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. { int ret,sat,brw,i;
  126. if (sizeof(long) == 8) do
  127. { const union { long one; char little; } is_endian = {1};
  128. long l;
  129. if (is_endian.little) break;
  130. /* not reached on little-endians */
  131. /* following test is redundant, because input is
  132. * always aligned, but I take no chances... */
  133. if (((size_t)v1|(size_t)v2)&0x7) break;
  134. l = *((long *)v1);
  135. l -= *((long *)v2);
  136. if (l>128) return 128;
  137. else if (l<-128) return -128;
  138. else return (int)l;
  139. } while (0);
  140. ret = (int)v1[7]-(int)v2[7];
  141. sat = 0;
  142. brw = ret>>8; /* brw is either 0 or -1 */
  143. if (ret & 0x80)
  144. { for (i=6;i>=0;i--)
  145. { brw += (int)v1[i]-(int)v2[i];
  146. sat |= ~brw;
  147. brw >>= 8;
  148. }
  149. }
  150. else
  151. { for (i=6;i>=0;i--)
  152. { brw += (int)v1[i]-(int)v2[i];
  153. sat |= brw;
  154. brw >>= 8;
  155. }
  156. }
  157. brw <<= 8; /* brw is either 0 or -256 */
  158. if (sat&0xff) return brw | 0x80;
  159. else return brw + (ret&0xFF);
  160. }
  161. static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  162. int len, int peek);
  163. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
  164. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
  165. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  166. unsigned int *is_next_epoch);
  167. #if 0
  168. static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
  169. unsigned short *priority, unsigned long *offset);
  170. #endif
  171. static int dtls1_buffer_record(SSL *s, record_pqueue *q,
  172. unsigned char *priority);
  173. static int dtls1_process_record(SSL *s);
  174. static void dtls1_clear_timeouts(SSL *s);
  175. /* copy buffered record into SSL structure */
  176. static int
  177. dtls1_copy_record(SSL *s, pitem *item)
  178. {
  179. DTLS1_RECORD_DATA *rdata;
  180. rdata = (DTLS1_RECORD_DATA *)item->data;
  181. if (s->s3->rbuf.buf != NULL)
  182. OPENSSL_free(s->s3->rbuf.buf);
  183. s->packet = rdata->packet;
  184. s->packet_length = rdata->packet_length;
  185. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  186. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  187. /* Set proper sequence number for mac calculation */
  188. memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
  189. return(1);
  190. }
  191. static int
  192. dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
  193. {
  194. DTLS1_RECORD_DATA *rdata;
  195. pitem *item;
  196. /* Limit the size of the queue to prevent DOS attacks */
  197. if (pqueue_size(queue->q) >= 100)
  198. return 0;
  199. rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
  200. item = pitem_new(priority, rdata);
  201. if (rdata == NULL || item == NULL)
  202. {
  203. if (rdata != NULL) OPENSSL_free(rdata);
  204. if (item != NULL) pitem_free(item);
  205. SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
  206. return(0);
  207. }
  208. rdata->packet = s->packet;
  209. rdata->packet_length = s->packet_length;
  210. memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
  211. memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
  212. item->data = rdata;
  213. /* insert should not fail, since duplicates are dropped */
  214. if (pqueue_insert(queue->q, item) == NULL)
  215. {
  216. OPENSSL_free(rdata);
  217. pitem_free(item);
  218. return(0);
  219. }
  220. s->packet = NULL;
  221. s->packet_length = 0;
  222. memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
  223. memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
  224. if (!ssl3_setup_buffers(s))
  225. {
  226. SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
  227. OPENSSL_free(rdata);
  228. pitem_free(item);
  229. return(0);
  230. }
  231. return(1);
  232. }
  233. static int
  234. dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
  235. {
  236. pitem *item;
  237. item = pqueue_pop(queue->q);
  238. if (item)
  239. {
  240. dtls1_copy_record(s, item);
  241. OPENSSL_free(item->data);
  242. pitem_free(item);
  243. return(1);
  244. }
  245. return(0);
  246. }
  247. /* retrieve a buffered record that belongs to the new epoch, i.e., not processed
  248. * yet */
  249. #define dtls1_get_unprocessed_record(s) \
  250. dtls1_retrieve_buffered_record((s), \
  251. &((s)->d1->unprocessed_rcds))
  252. /* retrieve a buffered record that belongs to the current epoch, ie, processed */
  253. #define dtls1_get_processed_record(s) \
  254. dtls1_retrieve_buffered_record((s), \
  255. &((s)->d1->processed_rcds))
  256. static int
  257. dtls1_process_buffered_records(SSL *s)
  258. {
  259. pitem *item;
  260. item = pqueue_peek(s->d1->unprocessed_rcds.q);
  261. if (item)
  262. {
  263. /* Check if epoch is current. */
  264. if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
  265. return(1); /* Nothing to do. */
  266. /* Process all the records. */
  267. while (pqueue_peek(s->d1->unprocessed_rcds.q))
  268. {
  269. dtls1_get_unprocessed_record(s);
  270. if ( ! dtls1_process_record(s))
  271. return(0);
  272. dtls1_buffer_record(s, &(s->d1->processed_rcds),
  273. s->s3->rrec.seq_num);
  274. }
  275. }
  276. /* sync epoch numbers once all the unprocessed records
  277. * have been processed */
  278. s->d1->processed_rcds.epoch = s->d1->r_epoch;
  279. s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
  280. return(1);
  281. }
  282. #if 0
  283. static int
  284. dtls1_get_buffered_record(SSL *s)
  285. {
  286. pitem *item;
  287. PQ_64BIT priority =
  288. (((PQ_64BIT)s->d1->handshake_read_seq) << 32) |
  289. ((PQ_64BIT)s->d1->r_msg_hdr.frag_off);
  290. if ( ! SSL_in_init(s)) /* if we're not (re)negotiating,
  291. nothing buffered */
  292. return 0;
  293. item = pqueue_peek(s->d1->rcvd_records);
  294. if (item && item->priority == priority)
  295. {
  296. /* Check if we've received the record of interest. It must be
  297. * a handshake record, since data records as passed up without
  298. * buffering */
  299. DTLS1_RECORD_DATA *rdata;
  300. item = pqueue_pop(s->d1->rcvd_records);
  301. rdata = (DTLS1_RECORD_DATA *)item->data;
  302. if (s->s3->rbuf.buf != NULL)
  303. OPENSSL_free(s->s3->rbuf.buf);
  304. s->packet = rdata->packet;
  305. s->packet_length = rdata->packet_length;
  306. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  307. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  308. OPENSSL_free(item->data);
  309. pitem_free(item);
  310. /* s->d1->next_expected_seq_num++; */
  311. return(1);
  312. }
  313. return 0;
  314. }
  315. #endif
  316. static int
  317. dtls1_process_record(SSL *s)
  318. {
  319. int i,al;
  320. int clear=0;
  321. int enc_err;
  322. SSL_SESSION *sess;
  323. SSL3_RECORD *rr;
  324. unsigned int mac_size;
  325. unsigned char md[EVP_MAX_MD_SIZE];
  326. rr= &(s->s3->rrec);
  327. sess = s->session;
  328. /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
  329. * and we have that many bytes in s->packet
  330. */
  331. rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]);
  332. /* ok, we can now read from 's->packet' data into 'rr'
  333. * rr->input points at rr->length bytes, which
  334. * need to be copied into rr->data by either
  335. * the decryption or by the decompression
  336. * When the data is 'copied' into the rr->data buffer,
  337. * rr->input will be pointed at the new buffer */
  338. /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
  339. * rr->length bytes of encrypted compressed stuff. */
  340. /* check is not needed I believe */
  341. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
  342. {
  343. al=SSL_AD_RECORD_OVERFLOW;
  344. SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  345. goto f_err;
  346. }
  347. /* decrypt in place in 'rr->input' */
  348. rr->data=rr->input;
  349. enc_err = s->method->ssl3_enc->enc(s,0);
  350. if (enc_err <= 0)
  351. {
  352. if (enc_err == 0)
  353. /* SSLerr() and ssl3_send_alert() have been called */
  354. goto err;
  355. /* otherwise enc_err == -1 */
  356. al=SSL_AD_BAD_RECORD_MAC;
  357. goto f_err;
  358. }
  359. #ifdef TLS_DEBUG
  360. printf("dec %d\n",rr->length);
  361. { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
  362. printf("\n");
  363. #endif
  364. /* r->length is now the compressed data plus mac */
  365. if ( (sess == NULL) ||
  366. (s->enc_read_ctx == NULL) ||
  367. (s->read_hash == NULL))
  368. clear=1;
  369. if (!clear)
  370. {
  371. /* !clear => s->read_hash != NULL => mac_size != -1 */
  372. int t;
  373. t=EVP_MD_CTX_size(s->read_hash);
  374. OPENSSL_assert(t >= 0);
  375. mac_size=t;
  376. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size)
  377. {
  378. #if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */
  379. al=SSL_AD_RECORD_OVERFLOW;
  380. SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);
  381. goto f_err;
  382. #else
  383. goto err;
  384. #endif
  385. }
  386. /* check the MAC for rr->input (it's in mac_size bytes at the tail) */
  387. if (rr->length < mac_size)
  388. {
  389. #if 0 /* OK only for stream ciphers */
  390. al=SSL_AD_DECODE_ERROR;
  391. SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT);
  392. goto f_err;
  393. #else
  394. goto err;
  395. #endif
  396. }
  397. rr->length-=mac_size;
  398. i=s->method->ssl3_enc->mac(s,md,0);
  399. if (i < 0 || memcmp(md,&(rr->data[rr->length]),mac_size) != 0)
  400. {
  401. goto err;
  402. }
  403. }
  404. /* r->length is now just compressed */
  405. if (s->expand != NULL)
  406. {
  407. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH)
  408. {
  409. al=SSL_AD_RECORD_OVERFLOW;
  410. SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
  411. goto f_err;
  412. }
  413. if (!ssl3_do_uncompress(s))
  414. {
  415. al=SSL_AD_DECOMPRESSION_FAILURE;
  416. SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION);
  417. goto f_err;
  418. }
  419. }
  420. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH)
  421. {
  422. al=SSL_AD_RECORD_OVERFLOW;
  423. SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
  424. goto f_err;
  425. }
  426. rr->off=0;
  427. /* So at this point the following is true
  428. * ssl->s3->rrec.type is the type of record
  429. * ssl->s3->rrec.length == number of bytes in record
  430. * ssl->s3->rrec.off == offset to first valid byte
  431. * ssl->s3->rrec.data == where to take bytes from, increment
  432. * after use :-).
  433. */
  434. /* we have pulled in a full packet so zero things */
  435. s->packet_length=0;
  436. dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */
  437. return(1);
  438. f_err:
  439. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  440. err:
  441. return(0);
  442. }
  443. /* Call this to get a new input record.
  444. * It will return <= 0 if more data is needed, normally due to an error
  445. * or non-blocking IO.
  446. * When it finishes, one packet has been decoded and can be found in
  447. * ssl->s3->rrec.type - is the type of record
  448. * ssl->s3->rrec.data, - data
  449. * ssl->s3->rrec.length, - number of bytes
  450. */
  451. /* used only by dtls1_read_bytes */
  452. int dtls1_get_record(SSL *s)
  453. {
  454. int ssl_major,ssl_minor;
  455. int i,n;
  456. SSL3_RECORD *rr;
  457. unsigned char *p = NULL;
  458. unsigned short version;
  459. DTLS1_BITMAP *bitmap;
  460. unsigned int is_next_epoch;
  461. rr= &(s->s3->rrec);
  462. /* The epoch may have changed. If so, process all the
  463. * pending records. This is a non-blocking operation. */
  464. dtls1_process_buffered_records(s);
  465. /* if we're renegotiating, then there may be buffered records */
  466. if (dtls1_get_processed_record(s))
  467. return 1;
  468. /* get something from the wire */
  469. again:
  470. /* check if we have the header */
  471. if ( (s->rstate != SSL_ST_READ_BODY) ||
  472. (s->packet_length < DTLS1_RT_HEADER_LENGTH))
  473. {
  474. n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  475. /* read timeout is handled by dtls1_read_bytes */
  476. if (n <= 0) return(n); /* error or non-blocking */
  477. /* this packet contained a partial record, dump it */
  478. if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
  479. {
  480. s->packet_length = 0;
  481. goto again;
  482. }
  483. s->rstate=SSL_ST_READ_BODY;
  484. p=s->packet;
  485. /* Pull apart the header into the DTLS1_RECORD */
  486. rr->type= *(p++);
  487. ssl_major= *(p++);
  488. ssl_minor= *(p++);
  489. version=(ssl_major<<8)|ssl_minor;
  490. /* sequence number is 64 bits, with top 2 bytes = epoch */
  491. n2s(p,rr->epoch);
  492. memcpy(&(s->s3->read_sequence[2]), p, 6);
  493. p+=6;
  494. n2s(p,rr->length);
  495. /* Lets check version */
  496. if (!s->first_packet)
  497. {
  498. if (version != s->version)
  499. {
  500. /* unexpected version, silently discard */
  501. rr->length = 0;
  502. s->packet_length = 0;
  503. goto again;
  504. }
  505. }
  506. if ((version & 0xff00) != (s->version & 0xff00))
  507. {
  508. /* wrong version, silently discard record */
  509. rr->length = 0;
  510. s->packet_length = 0;
  511. goto again;
  512. }
  513. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
  514. {
  515. /* record too long, silently discard it */
  516. rr->length = 0;
  517. s->packet_length = 0;
  518. goto again;
  519. }
  520. /* now s->rstate == SSL_ST_READ_BODY */
  521. }
  522. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  523. if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
  524. {
  525. /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
  526. i=rr->length;
  527. n=ssl3_read_n(s,i,i,1);
  528. if (n <= 0) return(n); /* error or non-blocking io */
  529. /* this packet contained a partial record, dump it */
  530. if ( n != i)
  531. {
  532. rr->length = 0;
  533. s->packet_length = 0;
  534. goto again;
  535. }
  536. /* now n == rr->length,
  537. * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
  538. }
  539. s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
  540. /* match epochs. NULL means the packet is dropped on the floor */
  541. bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
  542. if ( bitmap == NULL)
  543. {
  544. rr->length = 0;
  545. s->packet_length = 0; /* dump this record */
  546. goto again; /* get another record */
  547. }
  548. /* Check whether this is a repeat, or aged record.
  549. * Don't check if we're listening and this message is
  550. * a ClientHello. They can look as if they're replayed,
  551. * since they arrive from different connections and
  552. * would be dropped unnecessarily.
  553. */
  554. if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
  555. *p == SSL3_MT_CLIENT_HELLO) &&
  556. !dtls1_record_replay_check(s, bitmap))
  557. {
  558. rr->length = 0;
  559. s->packet_length=0; /* dump this record */
  560. goto again; /* get another record */
  561. }
  562. /* just read a 0 length packet */
  563. if (rr->length == 0) goto again;
  564. /* If this record is from the next epoch (either HM or ALERT),
  565. * and a handshake is currently in progress, buffer it since it
  566. * cannot be processed at this time. */
  567. if (is_next_epoch)
  568. {
  569. if (SSL_in_init(s) || s->in_handshake)
  570. {
  571. dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
  572. }
  573. rr->length = 0;
  574. s->packet_length = 0;
  575. goto again;
  576. }
  577. if (!dtls1_process_record(s))
  578. {
  579. rr->length = 0;
  580. s->packet_length = 0; /* dump this record */
  581. goto again; /* get another record */
  582. }
  583. dtls1_clear_timeouts(s); /* done waiting */
  584. return(1);
  585. }
  586. /* Return up to 'len' payload bytes received in 'type' records.
  587. * 'type' is one of the following:
  588. *
  589. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  590. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  591. * - 0 (during a shutdown, no data has to be returned)
  592. *
  593. * If we don't have stored data to work from, read a SSL/TLS record first
  594. * (possibly multiple records if we still don't have anything to return).
  595. *
  596. * This function must handle any surprises the peer may have for us, such as
  597. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  598. * a surprise, but handled as if it were), or renegotiation requests.
  599. * Also if record payloads contain fragments too small to process, we store
  600. * them until there is enough for the respective protocol (the record protocol
  601. * may use arbitrary fragmentation and even interleaving):
  602. * Change cipher spec protocol
  603. * just 1 byte needed, no need for keeping anything stored
  604. * Alert protocol
  605. * 2 bytes needed (AlertLevel, AlertDescription)
  606. * Handshake protocol
  607. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  608. * to detect unexpected Client Hello and Hello Request messages
  609. * here, anything else is handled by higher layers
  610. * Application data protocol
  611. * none of our business
  612. */
  613. int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  614. {
  615. int al,i,j,ret;
  616. unsigned int n;
  617. SSL3_RECORD *rr;
  618. void (*cb)(const SSL *ssl,int type2,int val)=NULL;
  619. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  620. if (!ssl3_setup_buffers(s))
  621. return(-1);
  622. /* XXX: check what the second '&& type' is about */
  623. if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
  624. (type != SSL3_RT_HANDSHAKE) && type) ||
  625. (peek && (type != SSL3_RT_APPLICATION_DATA)))
  626. {
  627. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  628. return -1;
  629. }
  630. /* check whether there's a handshake message (client hello?) waiting */
  631. if ( (ret = have_handshake_fragment(s, type, buf, len, peek)))
  632. return ret;
  633. /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  634. if (!s->in_handshake && SSL_in_init(s))
  635. {
  636. /* type == SSL3_RT_APPLICATION_DATA */
  637. i=s->handshake_func(s);
  638. if (i < 0) return(i);
  639. if (i == 0)
  640. {
  641. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
  642. return(-1);
  643. }
  644. }
  645. start:
  646. s->rwstate=SSL_NOTHING;
  647. /* s->s3->rrec.type - is the type of record
  648. * s->s3->rrec.data, - data
  649. * s->s3->rrec.off, - offset into 'data' for next read
  650. * s->s3->rrec.length, - number of bytes. */
  651. rr = &(s->s3->rrec);
  652. /* We are not handshaking and have no data yet,
  653. * so process data buffered during the last handshake
  654. * in advance, if any.
  655. */
  656. if (s->state == SSL_ST_OK && rr->length == 0)
  657. {
  658. pitem *item;
  659. item = pqueue_pop(s->d1->buffered_app_data.q);
  660. if (item)
  661. {
  662. dtls1_copy_record(s, item);
  663. OPENSSL_free(item->data);
  664. pitem_free(item);
  665. }
  666. }
  667. /* Check for timeout */
  668. if (dtls1_handle_timeout(s) > 0)
  669. goto start;
  670. /* get new packet if necessary */
  671. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
  672. {
  673. ret=dtls1_get_record(s);
  674. if (ret <= 0)
  675. {
  676. ret = dtls1_read_failed(s, ret);
  677. /* anything other than a timeout is an error */
  678. if (ret <= 0)
  679. return(ret);
  680. else
  681. goto start;
  682. }
  683. }
  684. /* we now have a packet which can be read and processed */
  685. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  686. * reset by ssl3_get_finished */
  687. && (rr->type != SSL3_RT_HANDSHAKE))
  688. {
  689. /* We now have application data between CCS and Finished.
  690. * Most likely the packets were reordered on their way, so
  691. * buffer the application data for later processing rather
  692. * than dropping the connection.
  693. */
  694. dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num);
  695. rr->length = 0;
  696. goto start;
  697. }
  698. /* If the other end has shut down, throw anything we read away
  699. * (even in 'peek' mode) */
  700. if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
  701. {
  702. rr->length=0;
  703. s->rwstate=SSL_NOTHING;
  704. return(0);
  705. }
  706. if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  707. {
  708. /* make sure that we are not getting application data when we
  709. * are doing a handshake for the first time */
  710. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  711. (s->enc_read_ctx == NULL))
  712. {
  713. al=SSL_AD_UNEXPECTED_MESSAGE;
  714. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
  715. goto f_err;
  716. }
  717. if (len <= 0) return(len);
  718. if ((unsigned int)len > rr->length)
  719. n = rr->length;
  720. else
  721. n = (unsigned int)len;
  722. memcpy(buf,&(rr->data[rr->off]),n);
  723. if (!peek)
  724. {
  725. rr->length-=n;
  726. rr->off+=n;
  727. if (rr->length == 0)
  728. {
  729. s->rstate=SSL_ST_READ_HEADER;
  730. rr->off=0;
  731. }
  732. }
  733. return(n);
  734. }
  735. /* If we get here, then type != rr->type; if we have a handshake
  736. * message, then it was unexpected (Hello Request or Client Hello). */
  737. /* In case of record types for which we have 'fragment' storage,
  738. * fill that so that we can process the data at a fixed place.
  739. */
  740. {
  741. unsigned int k, dest_maxlen = 0;
  742. unsigned char *dest = NULL;
  743. unsigned int *dest_len = NULL;
  744. if (rr->type == SSL3_RT_HANDSHAKE)
  745. {
  746. dest_maxlen = sizeof s->d1->handshake_fragment;
  747. dest = s->d1->handshake_fragment;
  748. dest_len = &s->d1->handshake_fragment_len;
  749. }
  750. else if (rr->type == SSL3_RT_ALERT)
  751. {
  752. dest_maxlen = sizeof(s->d1->alert_fragment);
  753. dest = s->d1->alert_fragment;
  754. dest_len = &s->d1->alert_fragment_len;
  755. }
  756. /* else it's a CCS message, or application data or wrong */
  757. else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC)
  758. {
  759. /* Application data while renegotiating
  760. * is allowed. Try again reading.
  761. */
  762. if (rr->type == SSL3_RT_APPLICATION_DATA)
  763. {
  764. BIO *bio;
  765. s->s3->in_read_app_data=2;
  766. bio=SSL_get_rbio(s);
  767. s->rwstate=SSL_READING;
  768. BIO_clear_retry_flags(bio);
  769. BIO_set_retry_read(bio);
  770. return(-1);
  771. }
  772. /* Not certain if this is the right error handling */
  773. al=SSL_AD_UNEXPECTED_MESSAGE;
  774. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
  775. goto f_err;
  776. }
  777. if (dest_maxlen > 0)
  778. {
  779. /* XDTLS: In a pathalogical case, the Client Hello
  780. * may be fragmented--don't always expect dest_maxlen bytes */
  781. if ( rr->length < dest_maxlen)
  782. {
  783. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  784. /*
  785. * for normal alerts rr->length is 2, while
  786. * dest_maxlen is 7 if we were to handle this
  787. * non-existing alert...
  788. */
  789. FIX ME
  790. #endif
  791. s->rstate=SSL_ST_READ_HEADER;
  792. rr->length = 0;
  793. goto start;
  794. }
  795. /* now move 'n' bytes: */
  796. for ( k = 0; k < dest_maxlen; k++)
  797. {
  798. dest[k] = rr->data[rr->off++];
  799. rr->length--;
  800. }
  801. *dest_len = dest_maxlen;
  802. }
  803. }
  804. /* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
  805. * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
  806. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
  807. /* If we are a client, check for an incoming 'Hello Request': */
  808. if ((!s->server) &&
  809. (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  810. (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  811. (s->session != NULL) && (s->session->cipher != NULL))
  812. {
  813. s->d1->handshake_fragment_len = 0;
  814. if ((s->d1->handshake_fragment[1] != 0) ||
  815. (s->d1->handshake_fragment[2] != 0) ||
  816. (s->d1->handshake_fragment[3] != 0))
  817. {
  818. al=SSL_AD_DECODE_ERROR;
  819. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
  820. goto err;
  821. }
  822. /* no need to check sequence number on HELLO REQUEST messages */
  823. if (s->msg_callback)
  824. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  825. s->d1->handshake_fragment, 4, s, s->msg_callback_arg);
  826. if (SSL_is_init_finished(s) &&
  827. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  828. !s->s3->renegotiate)
  829. {
  830. s->new_session = 1;
  831. ssl3_renegotiate(s);
  832. if (ssl3_renegotiate_check(s))
  833. {
  834. i=s->handshake_func(s);
  835. if (i < 0) return(i);
  836. if (i == 0)
  837. {
  838. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
  839. return(-1);
  840. }
  841. if (!(s->mode & SSL_MODE_AUTO_RETRY))
  842. {
  843. if (s->s3->rbuf.left == 0) /* no read-ahead left? */
  844. {
  845. BIO *bio;
  846. /* In the case where we try to read application data,
  847. * but we trigger an SSL handshake, we return -1 with
  848. * the retry option set. Otherwise renegotiation may
  849. * cause nasty problems in the blocking world */
  850. s->rwstate=SSL_READING;
  851. bio=SSL_get_rbio(s);
  852. BIO_clear_retry_flags(bio);
  853. BIO_set_retry_read(bio);
  854. return(-1);
  855. }
  856. }
  857. }
  858. }
  859. /* we either finished a handshake or ignored the request,
  860. * now try again to obtain the (application) data we were asked for */
  861. goto start;
  862. }
  863. if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH)
  864. {
  865. int alert_level = s->d1->alert_fragment[0];
  866. int alert_descr = s->d1->alert_fragment[1];
  867. s->d1->alert_fragment_len = 0;
  868. if (s->msg_callback)
  869. s->msg_callback(0, s->version, SSL3_RT_ALERT,
  870. s->d1->alert_fragment, 2, s, s->msg_callback_arg);
  871. if (s->info_callback != NULL)
  872. cb=s->info_callback;
  873. else if (s->ctx->info_callback != NULL)
  874. cb=s->ctx->info_callback;
  875. if (cb != NULL)
  876. {
  877. j = (alert_level << 8) | alert_descr;
  878. cb(s, SSL_CB_READ_ALERT, j);
  879. }
  880. if (alert_level == 1) /* warning */
  881. {
  882. s->s3->warn_alert = alert_descr;
  883. if (alert_descr == SSL_AD_CLOSE_NOTIFY)
  884. {
  885. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  886. return(0);
  887. }
  888. #if 0
  889. /* XXX: this is a possible improvement in the future */
  890. /* now check if it's a missing record */
  891. if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
  892. {
  893. unsigned short seq;
  894. unsigned int frag_off;
  895. unsigned char *p = &(s->d1->alert_fragment[2]);
  896. n2s(p, seq);
  897. n2l3(p, frag_off);
  898. dtls1_retransmit_message(s,
  899. dtls1_get_queue_priority(frag->msg_header.seq, 0),
  900. frag_off, &found);
  901. if ( ! found && SSL_in_init(s))
  902. {
  903. /* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */
  904. /* requested a message not yet sent,
  905. send an alert ourselves */
  906. ssl3_send_alert(s,SSL3_AL_WARNING,
  907. DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  908. }
  909. }
  910. #endif
  911. }
  912. else if (alert_level == 2) /* fatal */
  913. {
  914. char tmp[16];
  915. s->rwstate=SSL_NOTHING;
  916. s->s3->fatal_alert = alert_descr;
  917. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
  918. BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
  919. ERR_add_error_data(2,"SSL alert number ",tmp);
  920. s->shutdown|=SSL_RECEIVED_SHUTDOWN;
  921. SSL_CTX_remove_session(s->ctx,s->session);
  922. return(0);
  923. }
  924. else
  925. {
  926. al=SSL_AD_ILLEGAL_PARAMETER;
  927. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
  928. goto f_err;
  929. }
  930. goto start;
  931. }
  932. if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
  933. {
  934. s->rwstate=SSL_NOTHING;
  935. rr->length=0;
  936. return(0);
  937. }
  938. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  939. {
  940. struct ccs_header_st ccs_hdr;
  941. unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
  942. dtls1_get_ccs_header(rr->data, &ccs_hdr);
  943. if (s->version == DTLS1_BAD_VER)
  944. ccs_hdr_len = 3;
  945. /* 'Change Cipher Spec' is just a single byte, so we know
  946. * exactly what the record payload has to look like */
  947. /* XDTLS: check that epoch is consistent */
  948. if ( (rr->length != ccs_hdr_len) ||
  949. (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS))
  950. {
  951. i=SSL_AD_ILLEGAL_PARAMETER;
  952. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
  953. goto err;
  954. }
  955. rr->length=0;
  956. if (s->msg_callback)
  957. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  958. rr->data, 1, s, s->msg_callback_arg);
  959. /* We can't process a CCS now, because previous handshake
  960. * messages are still missing, so just drop it.
  961. */
  962. if (!s->d1->change_cipher_spec_ok)
  963. {
  964. goto start;
  965. }
  966. s->d1->change_cipher_spec_ok = 0;
  967. s->s3->change_cipher_spec=1;
  968. if (!ssl3_do_change_cipher_spec(s))
  969. goto err;
  970. /* do this whenever CCS is processed */
  971. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  972. if (s->version == DTLS1_BAD_VER)
  973. s->d1->handshake_read_seq++;
  974. goto start;
  975. }
  976. /* Unexpected handshake message (Client Hello, or protocol violation) */
  977. if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  978. !s->in_handshake)
  979. {
  980. struct hm_header_st msg_hdr;
  981. /* this may just be a stale retransmit */
  982. dtls1_get_message_header(rr->data, &msg_hdr);
  983. if( rr->epoch != s->d1->r_epoch)
  984. {
  985. rr->length = 0;
  986. goto start;
  987. }
  988. /* If we are server, we may have a repeated FINISHED of the
  989. * client here, then retransmit our CCS and FINISHED.
  990. */
  991. if (msg_hdr.type == SSL3_MT_FINISHED)
  992. {
  993. dtls1_retransmit_buffered_messages(s);
  994. rr->length = 0;
  995. goto start;
  996. }
  997. if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
  998. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
  999. {
  1000. #if 0 /* worked only because C operator preferences are not as expected (and
  1001. * because this is not really needed for clients except for detecting
  1002. * protocol violations): */
  1003. s->state=SSL_ST_BEFORE|(s->server)
  1004. ?SSL_ST_ACCEPT
  1005. :SSL_ST_CONNECT;
  1006. #else
  1007. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  1008. #endif
  1009. s->renegotiate=1;
  1010. s->new_session=1;
  1011. }
  1012. i=s->handshake_func(s);
  1013. if (i < 0) return(i);
  1014. if (i == 0)
  1015. {
  1016. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
  1017. return(-1);
  1018. }
  1019. if (!(s->mode & SSL_MODE_AUTO_RETRY))
  1020. {
  1021. if (s->s3->rbuf.left == 0) /* no read-ahead left? */
  1022. {
  1023. BIO *bio;
  1024. /* In the case where we try to read application data,
  1025. * but we trigger an SSL handshake, we return -1 with
  1026. * the retry option set. Otherwise renegotiation may
  1027. * cause nasty problems in the blocking world */
  1028. s->rwstate=SSL_READING;
  1029. bio=SSL_get_rbio(s);
  1030. BIO_clear_retry_flags(bio);
  1031. BIO_set_retry_read(bio);
  1032. return(-1);
  1033. }
  1034. }
  1035. goto start;
  1036. }
  1037. switch (rr->type)
  1038. {
  1039. default:
  1040. #ifndef OPENSSL_NO_TLS
  1041. /* TLS just ignores unknown message types */
  1042. if (s->version == TLS1_VERSION)
  1043. {
  1044. rr->length = 0;
  1045. goto start;
  1046. }
  1047. #endif
  1048. al=SSL_AD_UNEXPECTED_MESSAGE;
  1049. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
  1050. goto f_err;
  1051. case SSL3_RT_CHANGE_CIPHER_SPEC:
  1052. case SSL3_RT_ALERT:
  1053. case SSL3_RT_HANDSHAKE:
  1054. /* we already handled all of these, with the possible exception
  1055. * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
  1056. * should not happen when type != rr->type */
  1057. al=SSL_AD_UNEXPECTED_MESSAGE;
  1058. SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR);
  1059. goto f_err;
  1060. case SSL3_RT_APPLICATION_DATA:
  1061. /* At this point, we were expecting handshake data,
  1062. * but have application data. If the library was
  1063. * running inside ssl3_read() (i.e. in_read_app_data
  1064. * is set) and it makes sense to read application data
  1065. * at this point (session renegotiation not yet started),
  1066. * we will indulge it.
  1067. */
  1068. if (s->s3->in_read_app_data &&
  1069. (s->s3->total_renegotiations != 0) &&
  1070. ((
  1071. (s->state & SSL_ST_CONNECT) &&
  1072. (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
  1073. (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
  1074. ) || (
  1075. (s->state & SSL_ST_ACCEPT) &&
  1076. (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
  1077. (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
  1078. )
  1079. ))
  1080. {
  1081. s->s3->in_read_app_data=2;
  1082. return(-1);
  1083. }
  1084. else
  1085. {
  1086. al=SSL_AD_UNEXPECTED_MESSAGE;
  1087. SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
  1088. goto f_err;
  1089. }
  1090. }
  1091. /* not reached */
  1092. f_err:
  1093. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  1094. err:
  1095. return(-1);
  1096. }
  1097. int
  1098. dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
  1099. {
  1100. int i;
  1101. if (SSL_in_init(s) && !s->in_handshake)
  1102. {
  1103. i=s->handshake_func(s);
  1104. if (i < 0) return(i);
  1105. if (i == 0)
  1106. {
  1107. SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
  1108. return -1;
  1109. }
  1110. }
  1111. if (len > SSL3_RT_MAX_PLAIN_LENGTH)
  1112. {
  1113. SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_DTLS_MESSAGE_TOO_BIG);
  1114. return -1;
  1115. }
  1116. i = dtls1_write_bytes(s, type, buf_, len);
  1117. return i;
  1118. }
  1119. /* this only happens when a client hello is received and a handshake
  1120. * is started. */
  1121. static int
  1122. have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  1123. int len, int peek)
  1124. {
  1125. if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
  1126. /* (partially) satisfy request from storage */
  1127. {
  1128. unsigned char *src = s->d1->handshake_fragment;
  1129. unsigned char *dst = buf;
  1130. unsigned int k,n;
  1131. /* peek == 0 */
  1132. n = 0;
  1133. while ((len > 0) && (s->d1->handshake_fragment_len > 0))
  1134. {
  1135. *dst++ = *src++;
  1136. len--; s->d1->handshake_fragment_len--;
  1137. n++;
  1138. }
  1139. /* move any remaining fragment bytes: */
  1140. for (k = 0; k < s->d1->handshake_fragment_len; k++)
  1141. s->d1->handshake_fragment[k] = *src++;
  1142. return n;
  1143. }
  1144. return 0;
  1145. }
  1146. /* Call this to write data in records of type 'type'
  1147. * It will return <= 0 if not all data has been sent or non-blocking IO.
  1148. */
  1149. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
  1150. {
  1151. int i;
  1152. OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  1153. s->rwstate=SSL_NOTHING;
  1154. i=do_dtls1_write(s, type, buf, len, 0);
  1155. return i;
  1156. }
  1157. int do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len, int create_empty_fragment)
  1158. {
  1159. unsigned char *p,*pseq;
  1160. int i,mac_size,clear=0;
  1161. int prefix_len = 0;
  1162. SSL3_RECORD *wr;
  1163. SSL3_BUFFER *wb;
  1164. SSL_SESSION *sess;
  1165. int bs;
  1166. /* first check if there is a SSL3_BUFFER still being written
  1167. * out. This will happen with non blocking IO */
  1168. if (s->s3->wbuf.left != 0)
  1169. {
  1170. OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */
  1171. return(ssl3_write_pending(s,type,buf,len));
  1172. }
  1173. /* If we have an alert to send, lets send it */
  1174. if (s->s3->alert_dispatch)
  1175. {
  1176. i=s->method->ssl_dispatch_alert(s);
  1177. if (i <= 0)
  1178. return(i);
  1179. /* if it went, fall through and send more stuff */
  1180. }
  1181. if (len == 0 && !create_empty_fragment)
  1182. return 0;
  1183. wr= &(s->s3->wrec);
  1184. wb= &(s->s3->wbuf);
  1185. sess=s->session;
  1186. if ( (sess == NULL) ||
  1187. (s->enc_write_ctx == NULL) ||
  1188. (EVP_MD_CTX_md(s->write_hash) == NULL))
  1189. clear=1;
  1190. if (clear)
  1191. mac_size=0;
  1192. else
  1193. {
  1194. mac_size=EVP_MD_CTX_size(s->write_hash);
  1195. if (mac_size < 0)
  1196. goto err;
  1197. }
  1198. /* DTLS implements explicit IV, so no need for empty fragments */
  1199. #if 0
  1200. /* 'create_empty_fragment' is true only when this function calls itself */
  1201. if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
  1202. && SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
  1203. {
  1204. /* countermeasure against known-IV weakness in CBC ciphersuites
  1205. * (see http://www.openssl.org/~bodo/tls-cbc.txt)
  1206. */
  1207. if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
  1208. {
  1209. /* recursive function call with 'create_empty_fragment' set;
  1210. * this prepares and buffers the data for an empty fragment
  1211. * (these 'prefix_len' bytes are sent out later
  1212. * together with the actual payload) */
  1213. prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
  1214. if (prefix_len <= 0)
  1215. goto err;
  1216. if (s->s3->wbuf.len < (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE)
  1217. {
  1218. /* insufficient space */
  1219. SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
  1220. goto err;
  1221. }
  1222. }
  1223. s->s3->empty_fragment_done = 1;
  1224. }
  1225. #endif
  1226. p = wb->buf + prefix_len;
  1227. /* write the header */
  1228. *(p++)=type&0xff;
  1229. wr->type=type;
  1230. *(p++)=(s->version>>8);
  1231. *(p++)=s->version&0xff;
  1232. /* field where we are to write out packet epoch, seq num and len */
  1233. pseq=p;
  1234. p+=10;
  1235. /* lets setup the record stuff. */
  1236. /* Make space for the explicit IV in case of CBC.
  1237. * (this is a bit of a boundary violation, but what the heck).
  1238. */
  1239. if ( s->enc_write_ctx &&
  1240. (EVP_CIPHER_mode( s->enc_write_ctx->cipher ) & EVP_CIPH_CBC_MODE))
  1241. bs = EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
  1242. else
  1243. bs = 0;
  1244. wr->data=p + bs; /* make room for IV in case of CBC */
  1245. wr->length=(int)len;
  1246. wr->input=(unsigned char *)buf;
  1247. /* we now 'read' from wr->input, wr->length bytes into
  1248. * wr->data */
  1249. /* first we compress */
  1250. if (s->compress != NULL)
  1251. {
  1252. if (!ssl3_do_compress(s))
  1253. {
  1254. SSLerr(SSL_F_DO_DTLS1_WRITE,SSL_R_COMPRESSION_FAILURE);
  1255. goto err;
  1256. }
  1257. }
  1258. else
  1259. {
  1260. memcpy(wr->data,wr->input,wr->length);
  1261. wr->input=wr->data;
  1262. }
  1263. /* we should still have the output to wr->data and the input
  1264. * from wr->input. Length should be wr->length.
  1265. * wr->data still points in the wb->buf */
  1266. if (mac_size != 0)
  1267. {
  1268. if(s->method->ssl3_enc->mac(s,&(p[wr->length + bs]),1) < 0)
  1269. goto err;
  1270. wr->length+=mac_size;
  1271. }
  1272. /* this is true regardless of mac size */
  1273. wr->input=p;
  1274. wr->data=p;
  1275. /* ssl3_enc can only have an error on read */
  1276. if (bs) /* bs != 0 in case of CBC */
  1277. {
  1278. RAND_pseudo_bytes(p,bs);
  1279. /* master IV and last CBC residue stand for
  1280. * the rest of randomness */
  1281. wr->length += bs;
  1282. }
  1283. s->method->ssl3_enc->enc(s,1);
  1284. /* record length after mac and block padding */
  1285. /* if (type == SSL3_RT_APPLICATION_DATA ||
  1286. (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
  1287. /* there's only one epoch between handshake and app data */
  1288. s2n(s->d1->w_epoch, pseq);
  1289. /* XDTLS: ?? */
  1290. /* else
  1291. s2n(s->d1->handshake_epoch, pseq); */
  1292. memcpy(pseq, &(s->s3->write_sequence[2]), 6);
  1293. pseq+=6;
  1294. s2n(wr->length,pseq);
  1295. /* we should now have
  1296. * wr->data pointing to the encrypted data, which is
  1297. * wr->length long */
  1298. wr->type=type; /* not needed but helps for debugging */
  1299. wr->length+=DTLS1_RT_HEADER_LENGTH;
  1300. #if 0 /* this is now done at the message layer */
  1301. /* buffer the record, making it easy to handle retransmits */
  1302. if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1303. dtls1_buffer_record(s, wr->data, wr->length,
  1304. *((PQ_64BIT *)&(s->s3->write_sequence[0])));
  1305. #endif
  1306. ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
  1307. if (create_empty_fragment)
  1308. {
  1309. /* we are in a recursive call;
  1310. * just return the length, don't write out anything here
  1311. */
  1312. return wr->length;
  1313. }
  1314. /* now let's set up wb */
  1315. wb->left = prefix_len + wr->length;
  1316. wb->offset = 0;
  1317. /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
  1318. s->s3->wpend_tot=len;
  1319. s->s3->wpend_buf=buf;
  1320. s->s3->wpend_type=type;
  1321. s->s3->wpend_ret=len;
  1322. /* we now just need to write the buffer */
  1323. return ssl3_write_pending(s,type,buf,len);
  1324. err:
  1325. return -1;
  1326. }
  1327. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
  1328. {
  1329. int cmp;
  1330. unsigned int shift;
  1331. const unsigned char *seq = s->s3->read_sequence;
  1332. cmp = satsub64be(seq,bitmap->max_seq_num);
  1333. if (cmp > 0)
  1334. {
  1335. memcpy (s->s3->rrec.seq_num,seq,8);
  1336. return 1; /* this record in new */
  1337. }
  1338. shift = -cmp;
  1339. if (shift >= sizeof(bitmap->map)*8)
  1340. return 0; /* stale, outside the window */
  1341. else if (bitmap->map & (1UL<<shift))
  1342. return 0; /* record previously received */
  1343. memcpy (s->s3->rrec.seq_num,seq,8);
  1344. return 1;
  1345. }
  1346. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
  1347. {
  1348. int cmp;
  1349. unsigned int shift;
  1350. const unsigned char *seq = s->s3->read_sequence;
  1351. cmp = satsub64be(seq,bitmap->max_seq_num);
  1352. if (cmp > 0)
  1353. {
  1354. shift = cmp;
  1355. if (shift < sizeof(bitmap->map)*8)
  1356. bitmap->map <<= shift, bitmap->map |= 1UL;
  1357. else
  1358. bitmap->map = 1UL;
  1359. memcpy(bitmap->max_seq_num,seq,8);
  1360. }
  1361. else {
  1362. shift = -cmp;
  1363. if (shift < sizeof(bitmap->map)*8)
  1364. bitmap->map |= 1UL<<shift;
  1365. }
  1366. }
  1367. int dtls1_dispatch_alert(SSL *s)
  1368. {
  1369. int i,j;
  1370. void (*cb)(const SSL *ssl,int type,int val)=NULL;
  1371. unsigned char buf[DTLS1_AL_HEADER_LENGTH];
  1372. unsigned char *ptr = &buf[0];
  1373. s->s3->alert_dispatch=0;
  1374. memset(buf, 0x00, sizeof(buf));
  1375. *ptr++ = s->s3->send_alert[0];
  1376. *ptr++ = s->s3->send_alert[1];
  1377. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1378. if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
  1379. {
  1380. s2n(s->d1->handshake_read_seq, ptr);
  1381. #if 0
  1382. if ( s->d1->r_msg_hdr.frag_off == 0) /* waiting for a new msg */
  1383. else
  1384. s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
  1385. #endif
  1386. #if 0
  1387. fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq);
  1388. #endif
  1389. l2n3(s->d1->r_msg_hdr.frag_off, ptr);
  1390. }
  1391. #endif
  1392. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
  1393. if (i <= 0)
  1394. {
  1395. s->s3->alert_dispatch=1;
  1396. /* fprintf( stderr, "not done with alert\n" ); */
  1397. }
  1398. else
  1399. {
  1400. if (s->s3->send_alert[0] == SSL3_AL_FATAL
  1401. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1402. || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  1403. #endif
  1404. )
  1405. (void)BIO_flush(s->wbio);
  1406. if (s->msg_callback)
  1407. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
  1408. 2, s, s->msg_callback_arg);
  1409. if (s->info_callback != NULL)
  1410. cb=s->info_callback;
  1411. else if (s->ctx->info_callback != NULL)
  1412. cb=s->ctx->info_callback;
  1413. if (cb != NULL)
  1414. {
  1415. j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
  1416. cb(s,SSL_CB_WRITE_ALERT,j);
  1417. }
  1418. }
  1419. return(i);
  1420. }
  1421. static DTLS1_BITMAP *
  1422. dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
  1423. {
  1424. *is_next_epoch = 0;
  1425. /* In current epoch, accept HM, CCS, DATA, & ALERT */
  1426. if (rr->epoch == s->d1->r_epoch)
  1427. return &s->d1->bitmap;
  1428. /* Only HM and ALERT messages can be from the next epoch */
  1429. else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
  1430. (rr->type == SSL3_RT_HANDSHAKE ||
  1431. rr->type == SSL3_RT_ALERT))
  1432. {
  1433. *is_next_epoch = 1;
  1434. return &s->d1->next_bitmap;
  1435. }
  1436. return NULL;
  1437. }
  1438. #if 0
  1439. static int
  1440. dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority,
  1441. unsigned long *offset)
  1442. {
  1443. /* alerts are passed up immediately */
  1444. if ( rr->type == SSL3_RT_APPLICATION_DATA ||
  1445. rr->type == SSL3_RT_ALERT)
  1446. return 0;
  1447. /* Only need to buffer if a handshake is underway.
  1448. * (this implies that Hello Request and Client Hello are passed up
  1449. * immediately) */
  1450. if ( SSL_in_init(s))
  1451. {
  1452. unsigned char *data = rr->data;
  1453. /* need to extract the HM/CCS sequence number here */
  1454. if ( rr->type == SSL3_RT_HANDSHAKE ||
  1455. rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1456. {
  1457. unsigned short seq_num;
  1458. struct hm_header_st msg_hdr;
  1459. struct ccs_header_st ccs_hdr;
  1460. if ( rr->type == SSL3_RT_HANDSHAKE)
  1461. {
  1462. dtls1_get_message_header(data, &msg_hdr);
  1463. seq_num = msg_hdr.seq;
  1464. *offset = msg_hdr.frag_off;
  1465. }
  1466. else
  1467. {
  1468. dtls1_get_ccs_header(data, &ccs_hdr);
  1469. seq_num = ccs_hdr.seq;
  1470. *offset = 0;
  1471. }
  1472. /* this is either a record we're waiting for, or a
  1473. * retransmit of something we happened to previously
  1474. * receive (higher layers will drop the repeat silently */
  1475. if ( seq_num < s->d1->handshake_read_seq)
  1476. return 0;
  1477. if (rr->type == SSL3_RT_HANDSHAKE &&
  1478. seq_num == s->d1->handshake_read_seq &&
  1479. msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
  1480. return 0;
  1481. else if ( seq_num == s->d1->handshake_read_seq &&
  1482. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
  1483. msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
  1484. return 0;
  1485. else
  1486. {
  1487. *priority = seq_num;
  1488. return 1;
  1489. }
  1490. }
  1491. else /* unknown record type */
  1492. return 0;
  1493. }
  1494. return 0;
  1495. }
  1496. #endif
  1497. void
  1498. dtls1_reset_seq_numbers(SSL *s, int rw)
  1499. {
  1500. unsigned char *seq;
  1501. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  1502. if ( rw & SSL3_CC_READ)
  1503. {
  1504. seq = s->s3->read_sequence;
  1505. s->d1->r_epoch++;
  1506. memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
  1507. memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
  1508. }
  1509. else
  1510. {
  1511. seq = s->s3->write_sequence;
  1512. memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
  1513. s->d1->w_epoch++;
  1514. }
  1515. memset(seq, 0x00, seq_bytes);
  1516. }
  1517. static void
  1518. dtls1_clear_timeouts(SSL *s)
  1519. {
  1520. memset(&(s->d1->timeout), 0x00, sizeof(struct dtls1_timeout_st));
  1521. }