2
0

d1_pkt.c 46 KB

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