2
0

d1_pkt.c 47 KB

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