Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630
  1. /* DTLS implementation written by Nagendra Modadugu
  2. * (nagendra@cs.stanford.edu) for the OpenSSL project 2005. */
  3. /* ====================================================================
  4. * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright
  11. * notice, this list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright
  14. * notice, this list of conditions and the following disclaimer in
  15. * the documentation and/or other materials provided with the
  16. * distribution.
  17. *
  18. * 3. All advertising materials mentioning features or use of this
  19. * software must display the following acknowledgment:
  20. * "This product includes software developed by the OpenSSL Project
  21. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  22. *
  23. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  24. * endorse or promote products derived from this software without
  25. * prior written permission. For written permission, please contact
  26. * openssl-core@openssl.org.
  27. *
  28. * 5. Products derived from this software may not be called "OpenSSL"
  29. * nor may "OpenSSL" appear in their names without prior written
  30. * permission of the OpenSSL Project.
  31. *
  32. * 6. Redistributions of any form whatsoever must retain the following
  33. * acknowledgment:
  34. * "This product includes software developed by the OpenSSL Project
  35. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  36. *
  37. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  38. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  39. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  40. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  41. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  42. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  43. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  44. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  45. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  46. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  47. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  48. * OF THE POSSIBILITY OF SUCH DAMAGE.
  49. * ====================================================================
  50. *
  51. * This product includes cryptographic software written by Eric Young
  52. * (eay@cryptsoft.com). This product includes software written by Tim
  53. * Hudson (tjh@cryptsoft.com).
  54. *
  55. */
  56. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  57. * All rights reserved.
  58. *
  59. * This package is an SSL implementation written
  60. * by Eric Young (eay@cryptsoft.com).
  61. * The implementation was written so as to conform with Netscapes SSL.
  62. *
  63. * This library is free for commercial and non-commercial use as long as
  64. * the following conditions are aheared to. The following conditions
  65. * apply to all code found in this distribution, be it the RC4, RSA,
  66. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  67. * included with this distribution is covered by the same copyright terms
  68. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  69. *
  70. * Copyright remains Eric Young's, and as such any Copyright notices in
  71. * the code are not to be removed.
  72. * If this package is used in a product, Eric Young should be given attribution
  73. * as the author of the parts of the library used.
  74. * This can be in the form of a textual message at program startup or
  75. * in documentation (online or textual) provided with the package.
  76. *
  77. * Redistribution and use in source and binary forms, with or without
  78. * modification, are permitted provided that the following conditions
  79. * are met:
  80. * 1. Redistributions of source code must retain the copyright
  81. * notice, this list of conditions and the following disclaimer.
  82. * 2. Redistributions in binary form must reproduce the above copyright
  83. * notice, this list of conditions and the following disclaimer in the
  84. * documentation and/or other materials provided with the distribution.
  85. * 3. All advertising materials mentioning features or use of this software
  86. * must display the following acknowledgement:
  87. * "This product includes cryptographic software written by
  88. * Eric Young (eay@cryptsoft.com)"
  89. * The word 'cryptographic' can be left out if the rouines from the library
  90. * being used are not cryptographic related :-).
  91. * 4. If you include any Windows specific code (or a derivative thereof) from
  92. * the apps directory (application code) you must include an acknowledgement:
  93. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  94. *
  95. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  96. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  97. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  98. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  99. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  100. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  101. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  102. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  103. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  104. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  105. * SUCH DAMAGE.
  106. *
  107. * The licence and distribution terms for any publically available version or
  108. * derivative of this code cannot be changed. i.e. this code cannot simply be
  109. * copied and put under another distribution licence
  110. * [including the GNU Public Licence.] */
  111. #include <stdio.h>
  112. #include <errno.h>
  113. #include <assert.h>
  114. #include <openssl/buf.h>
  115. #include <openssl/mem.h>
  116. #include <openssl/evp.h>
  117. #include <openssl/err.h>
  118. #include <openssl/rand.h>
  119. #include "ssl_locl.h"
  120. /* mod 128 saturating subtract of two 64-bit values in big-endian order */
  121. static int satsub64be(const unsigned char *v1,const unsigned char *v2)
  122. { int ret,sat,brw,i;
  123. if (sizeof(long) == 8) do
  124. { const union { long one; char little; } is_endian = {1};
  125. long l;
  126. if (is_endian.little) break;
  127. /* not reached on little-endians */
  128. /* following test is redundant, because input is
  129. * always aligned, but I take no chances... */
  130. if (((size_t)v1|(size_t)v2)&0x7) break;
  131. l = *((long *)v1);
  132. l -= *((long *)v2);
  133. if (l>128) return 128;
  134. else if (l<-128) return -128;
  135. else return (int)l;
  136. } while (0);
  137. ret = (int)v1[7]-(int)v2[7];
  138. sat = 0;
  139. brw = ret>>8; /* brw is either 0 or -1 */
  140. if (ret & 0x80)
  141. { for (i=6;i>=0;i--)
  142. { brw += (int)v1[i]-(int)v2[i];
  143. sat |= ~brw;
  144. brw >>= 8;
  145. }
  146. }
  147. else
  148. { for (i=6;i>=0;i--)
  149. { brw += (int)v1[i]-(int)v2[i];
  150. sat |= brw;
  151. brw >>= 8;
  152. }
  153. }
  154. brw <<= 8; /* brw is either 0 or -256 */
  155. if (sat&0xff) return brw | 0x80;
  156. else return brw + (ret&0xFF);
  157. }
  158. static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  159. int len, int peek);
  160. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
  161. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
  162. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  163. unsigned int *is_next_epoch);
  164. #if 0
  165. static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
  166. unsigned short *priority, unsigned long *offset);
  167. #endif
  168. static int dtls1_buffer_record(SSL *s, record_pqueue *q,
  169. unsigned char *priority);
  170. static int dtls1_process_record(SSL *s);
  171. static int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
  172. unsigned int len);
  173. /* copy buffered record into SSL structure */
  174. static int
  175. dtls1_copy_record(SSL *s, pitem *item)
  176. {
  177. DTLS1_RECORD_DATA *rdata;
  178. rdata = (DTLS1_RECORD_DATA *)item->data;
  179. if (s->s3->rbuf.buf != NULL)
  180. OPENSSL_free(s->s3->rbuf.buf);
  181. s->packet = rdata->packet;
  182. s->packet_length = rdata->packet_length;
  183. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  184. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  185. /* Set proper sequence number for mac calculation */
  186. memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
  187. return(1);
  188. }
  189. static int
  190. dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
  191. {
  192. DTLS1_RECORD_DATA *rdata;
  193. pitem *item;
  194. /* Limit the size of the queue to prevent DOS attacks */
  195. if (pqueue_size(queue->q) >= 100)
  196. return 0;
  197. rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
  198. item = pitem_new(priority, rdata);
  199. if (rdata == NULL || item == NULL)
  200. {
  201. if (rdata != NULL) OPENSSL_free(rdata);
  202. if (item != NULL) pitem_free(item);
  203. OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
  204. return(0);
  205. }
  206. rdata->packet = s->packet;
  207. rdata->packet_length = s->packet_length;
  208. memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
  209. memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
  210. item->data = rdata;
  211. s->packet = NULL;
  212. s->packet_length = 0;
  213. memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
  214. memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
  215. if (!ssl3_setup_buffers(s))
  216. {
  217. OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
  218. OPENSSL_free(rdata);
  219. pitem_free(item);
  220. return(0);
  221. }
  222. /* insert should not fail, since duplicates are dropped */
  223. if (pqueue_insert(queue->q, item) == NULL)
  224. {
  225. OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
  226. OPENSSL_free(rdata);
  227. pitem_free(item);
  228. return(0);
  229. }
  230. return(1);
  231. }
  232. static int
  233. dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
  234. {
  235. pitem *item;
  236. item = pqueue_pop(queue->q);
  237. if (item)
  238. {
  239. dtls1_copy_record(s, item);
  240. OPENSSL_free(item->data);
  241. pitem_free(item);
  242. return(1);
  243. }
  244. return(0);
  245. }
  246. /* retrieve a buffered record that belongs to the new epoch, i.e., not processed
  247. * yet */
  248. #define dtls1_get_unprocessed_record(s) \
  249. dtls1_retrieve_buffered_record((s), \
  250. &((s)->d1->unprocessed_rcds))
  251. /* retrieve a buffered record that belongs to the current epoch, ie, processed */
  252. #define dtls1_get_processed_record(s) \
  253. dtls1_retrieve_buffered_record((s), \
  254. &((s)->d1->processed_rcds))
  255. static int
  256. dtls1_process_buffered_records(SSL *s)
  257. {
  258. pitem *item;
  259. item = pqueue_peek(s->d1->unprocessed_rcds.q);
  260. if (item)
  261. {
  262. /* Check if epoch is current. */
  263. if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
  264. return(1); /* Nothing to do. */
  265. /* Process all the records. */
  266. while (pqueue_peek(s->d1->unprocessed_rcds.q))
  267. {
  268. dtls1_get_unprocessed_record(s);
  269. if ( ! dtls1_process_record(s))
  270. return(0);
  271. dtls1_buffer_record(s, &(s->d1->processed_rcds),
  272. s->s3->rrec.seq_num);
  273. }
  274. }
  275. /* sync epoch numbers once all the unprocessed records
  276. * have been processed */
  277. s->d1->processed_rcds.epoch = s->d1->r_epoch;
  278. s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
  279. return(1);
  280. }
  281. #if 0
  282. static int
  283. dtls1_get_buffered_record(SSL *s)
  284. {
  285. pitem *item;
  286. PQ_64BIT priority =
  287. (((PQ_64BIT)s->d1->handshake_read_seq) << 32) |
  288. ((PQ_64BIT)s->d1->r_msg_hdr.frag_off);
  289. if ( ! SSL_in_init(s)) /* if we're not (re)negotiating,
  290. nothing buffered */
  291. return 0;
  292. item = pqueue_peek(s->d1->rcvd_records);
  293. if (item && item->priority == priority)
  294. {
  295. /* Check if we've received the record of interest. It must be
  296. * a handshake record, since data records as passed up without
  297. * buffering */
  298. DTLS1_RECORD_DATA *rdata;
  299. item = pqueue_pop(s->d1->rcvd_records);
  300. rdata = (DTLS1_RECORD_DATA *)item->data;
  301. if (s->s3->rbuf.buf != NULL)
  302. OPENSSL_free(s->s3->rbuf.buf);
  303. s->packet = rdata->packet;
  304. s->packet_length = rdata->packet_length;
  305. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  306. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  307. OPENSSL_free(item->data);
  308. pitem_free(item);
  309. /* s->d1->next_expected_seq_num++; */
  310. return(1);
  311. }
  312. return 0;
  313. }
  314. #endif
  315. static int
  316. dtls1_process_record(SSL *s)
  317. {
  318. int i,al;
  319. int enc_err;
  320. SSL_SESSION *sess;
  321. SSL3_RECORD *rr;
  322. unsigned int mac_size, orig_len;
  323. unsigned char md[EVP_MAX_MD_SIZE];
  324. rr= &(s->s3->rrec);
  325. sess = s->session;
  326. /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
  327. * and we have that many bytes in s->packet
  328. */
  329. rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]);
  330. /* ok, we can now read from 's->packet' data into 'rr'
  331. * rr->input points at rr->length bytes, which
  332. * need to be copied into rr->data by either
  333. * the decryption or by the decompression
  334. * When the data is 'copied' into the rr->data buffer,
  335. * rr->input will be pointed at the new buffer */
  336. /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
  337. * rr->length bytes of encrypted compressed stuff. */
  338. /* check is not needed I believe */
  339. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
  340. {
  341. al=SSL_AD_RECORD_OVERFLOW;
  342. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  343. goto f_err;
  344. }
  345. /* decrypt in place in 'rr->input' */
  346. rr->data=rr->input;
  347. enc_err = s->method->ssl3_enc->enc(s,0);
  348. /* enc_err is:
  349. * 0: (in non-constant time) if the record is publically invalid.
  350. * 1: if the padding is valid
  351. * -1: if the padding is invalid */
  352. if (enc_err == 0)
  353. {
  354. /* For DTLS we simply ignore bad packets. */
  355. rr->length = 0;
  356. s->packet_length = 0;
  357. goto err;
  358. }
  359. #ifdef TLS_DEBUG
  360. printf("dec %d\n",rr->length);
  361. { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
  362. printf("\n");
  363. #endif
  364. /* r->length is now the compressed data plus mac */
  365. if ((sess != NULL) &&
  366. (s->enc_read_ctx != NULL) &&
  367. (EVP_MD_CTX_md(s->read_hash) != NULL))
  368. {
  369. /* s->read_hash != NULL => mac_size != -1 */
  370. unsigned char *mac = NULL;
  371. unsigned char mac_tmp[EVP_MAX_MD_SIZE];
  372. mac_size=EVP_MD_CTX_size(s->read_hash);
  373. assert(mac_size <= EVP_MAX_MD_SIZE);
  374. /* kludge: *_cbc_remove_padding passes padding length in rr->type */
  375. orig_len = rr->length+((unsigned int)rr->type>>8);
  376. /* orig_len is the length of the record before any padding was
  377. * removed. This is public information, as is the MAC in use,
  378. * therefore we can safely process the record in a different
  379. * amount of time if it's too short to possibly contain a MAC.
  380. */
  381. if (orig_len < mac_size ||
  382. /* CBC records must have a padding length byte too. */
  383. (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  384. orig_len < mac_size+1))
  385. {
  386. al=SSL_AD_DECODE_ERROR;
  387. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_LENGTH_TOO_SHORT);
  388. goto f_err;
  389. }
  390. if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
  391. {
  392. /* We update the length so that the TLS header bytes
  393. * can be constructed correctly but we need to extract
  394. * the MAC in constant time from within the record,
  395. * without leaking the contents of the padding bytes.
  396. * */
  397. mac = mac_tmp;
  398. ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
  399. rr->length -= mac_size;
  400. }
  401. else
  402. {
  403. /* In this case there's no padding, so |orig_len|
  404. * equals |rec->length| and we checked that there's
  405. * enough bytes for |mac_size| above. */
  406. rr->length -= mac_size;
  407. mac = &rr->data[rr->length];
  408. }
  409. i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
  410. if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
  411. enc_err = -1;
  412. if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size)
  413. enc_err = -1;
  414. }
  415. if (enc_err < 0)
  416. {
  417. /* decryption failed, silently discard message */
  418. rr->length = 0;
  419. s->packet_length = 0;
  420. goto err;
  421. }
  422. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH)
  423. {
  424. al=SSL_AD_RECORD_OVERFLOW;
  425. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_DATA_LENGTH_TOO_LONG);
  426. goto f_err;
  427. }
  428. rr->off=0;
  429. /* So at this point the following is true
  430. * ssl->s3->rrec.type is the type of record
  431. * ssl->s3->rrec.length == number of bytes in record
  432. * ssl->s3->rrec.off == offset to first valid byte
  433. * ssl->s3->rrec.data == where to take bytes from, increment
  434. * after use :-).
  435. */
  436. /* we have pulled in a full packet so zero things */
  437. s->packet_length=0;
  438. dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */
  439. return(1);
  440. f_err:
  441. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  442. err:
  443. return(0);
  444. }
  445. /* Call this to get a new input record.
  446. * It will return <= 0 if more data is needed, normally due to an error
  447. * or non-blocking IO.
  448. * When it finishes, one packet has been decoded and can be found in
  449. * ssl->s3->rrec.type - is the type of record
  450. * ssl->s3->rrec.data, - data
  451. * ssl->s3->rrec.length, - number of bytes
  452. */
  453. /* used only by dtls1_read_bytes */
  454. int dtls1_get_record(SSL *s)
  455. {
  456. int ssl_major,ssl_minor;
  457. int i,n;
  458. SSL3_RECORD *rr;
  459. unsigned char *p = NULL;
  460. unsigned short version;
  461. DTLS1_BITMAP *bitmap;
  462. unsigned int is_next_epoch;
  463. rr= &(s->s3->rrec);
  464. /* The epoch may have changed. If so, process all the
  465. * pending records. This is a non-blocking operation. */
  466. dtls1_process_buffered_records(s);
  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. /* this packet contained a partial record, dump it */
  480. if (s->packet_length != DTLS1_RT_HEADER_LENGTH)
  481. {
  482. s->packet_length = 0;
  483. goto again;
  484. }
  485. s->rstate=SSL_ST_READ_BODY;
  486. p=s->packet;
  487. if (s->msg_callback)
  488. s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  489. /* Pull apart the header into the DTLS1_RECORD */
  490. rr->type= *(p++);
  491. ssl_major= *(p++);
  492. ssl_minor= *(p++);
  493. version=(ssl_major<<8)|ssl_minor;
  494. /* sequence number is 64 bits, with top 2 bytes = epoch */
  495. n2s(p,rr->epoch);
  496. memcpy(&(s->s3->read_sequence[2]), p, 6);
  497. p+=6;
  498. n2s(p,rr->length);
  499. /* Lets check version */
  500. if (!s->first_packet)
  501. {
  502. if (version != s->version)
  503. {
  504. /* unexpected version, silently discard */
  505. rr->length = 0;
  506. s->packet_length = 0;
  507. goto again;
  508. }
  509. }
  510. if ((version & 0xff00) != (s->version & 0xff00))
  511. {
  512. /* wrong version, silently discard record */
  513. rr->length = 0;
  514. s->packet_length = 0;
  515. goto again;
  516. }
  517. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
  518. {
  519. /* record too long, silently discard it */
  520. rr->length = 0;
  521. s->packet_length = 0;
  522. goto again;
  523. }
  524. /* now s->rstate == SSL_ST_READ_BODY */
  525. }
  526. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  527. if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
  528. {
  529. /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
  530. i=rr->length;
  531. n=ssl3_read_n(s,i,i,1);
  532. if (n <= 0) return(n); /* error or non-blocking io */
  533. /* this packet contained a partial record, dump it */
  534. if ( n != i)
  535. {
  536. rr->length = 0;
  537. s->packet_length = 0;
  538. goto again;
  539. }
  540. /* now n == rr->length,
  541. * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
  542. }
  543. s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
  544. /* match epochs. NULL means the packet is dropped on the floor */
  545. bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
  546. if ( bitmap == NULL)
  547. {
  548. rr->length = 0;
  549. s->packet_length = 0; /* dump this record */
  550. goto again; /* get another record */
  551. }
  552. /* Check whether this is a repeat, or aged record. */
  553. if (!dtls1_record_replay_check(s, bitmap))
  554. {
  555. rr->length = 0;
  556. s->packet_length=0; /* dump this record */
  557. goto again; /* get another record */
  558. }
  559. /* just read a 0 length packet */
  560. if (rr->length == 0) goto again;
  561. /* If this record is from the next epoch (either HM or ALERT),
  562. * and a handshake is currently in progress, buffer it since it
  563. * cannot be processed at this time.
  564. */
  565. if (is_next_epoch)
  566. {
  567. if (SSL_in_init(s) || s->in_handshake)
  568. {
  569. dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
  570. }
  571. rr->length = 0;
  572. s->packet_length = 0;
  573. goto again;
  574. }
  575. if (!dtls1_process_record(s))
  576. {
  577. rr->length = 0;
  578. s->packet_length = 0; /* dump this record */
  579. goto again; /* get another record */
  580. }
  581. return(1);
  582. }
  583. /* Return up to 'len' payload bytes received in 'type' records.
  584. * 'type' is one of the following:
  585. *
  586. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  587. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  588. * - 0 (during a shutdown, no data has to be returned)
  589. *
  590. * If we don't have stored data to work from, read a SSL/TLS record first
  591. * (possibly multiple records if we still don't have anything to return).
  592. *
  593. * This function must handle any surprises the peer may have for us, such as
  594. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  595. * a surprise, but handled as if it were), or renegotiation requests.
  596. * Also if record payloads contain fragments too small to process, we store
  597. * them until there is enough for the respective protocol (the record protocol
  598. * may use arbitrary fragmentation and even interleaving):
  599. * Change cipher spec protocol
  600. * just 1 byte needed, no need for keeping anything stored
  601. * Alert protocol
  602. * 2 bytes needed (AlertLevel, AlertDescription)
  603. * Handshake protocol
  604. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  605. * to detect unexpected Client Hello and Hello Request messages
  606. * here, anything else is handled by higher layers
  607. * Application data protocol
  608. * none of our business
  609. */
  610. int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
  611. {
  612. int al,i,j,ret;
  613. unsigned int n;
  614. SSL3_RECORD *rr;
  615. void (*cb)(const SSL *ssl,int type2,int val)=NULL;
  616. if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
  617. if (!ssl3_setup_buffers(s))
  618. return(-1);
  619. /* XXX: check what the second '&& type' is about */
  620. if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
  621. (type != SSL3_RT_HANDSHAKE) && type) ||
  622. (peek && (type != SSL3_RT_APPLICATION_DATA)))
  623. {
  624. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
  625. return -1;
  626. }
  627. /* check whether there's a handshake message (client hello?) waiting */
  628. if ( (ret = have_handshake_fragment(s, type, buf, len, peek)))
  629. return ret;
  630. /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  631. if (!s->in_handshake && SSL_in_init(s))
  632. {
  633. /* type == SSL3_RT_APPLICATION_DATA */
  634. i=s->handshake_func(s);
  635. if (i < 0) return(i);
  636. if (i == 0)
  637. {
  638. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  639. return(-1);
  640. }
  641. }
  642. start:
  643. s->rwstate=SSL_NOTHING;
  644. /* s->s3->rrec.type - is the type of record
  645. * s->s3->rrec.data, - data
  646. * s->s3->rrec.off, - offset into 'data' for next read
  647. * s->s3->rrec.length, - number of bytes. */
  648. rr = &(s->s3->rrec);
  649. /* We are not handshaking and have no data yet,
  650. * so process data buffered during the last handshake
  651. * in advance, if any.
  652. */
  653. if (s->state == SSL_ST_OK && rr->length == 0)
  654. {
  655. pitem *item;
  656. item = pqueue_pop(s->d1->buffered_app_data.q);
  657. if (item)
  658. {
  659. dtls1_copy_record(s, item);
  660. OPENSSL_free(item->data);
  661. pitem_free(item);
  662. }
  663. }
  664. /* Check for timeout */
  665. if (dtls1_handle_timeout(s) > 0)
  666. goto start;
  667. /* get new packet if necessary */
  668. if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
  669. {
  670. ret=dtls1_get_record(s);
  671. if (ret <= 0)
  672. {
  673. ret = dtls1_read_failed(s, ret);
  674. /* anything other than a timeout is an error */
  675. if (ret <= 0)
  676. return(ret);
  677. else
  678. goto start;
  679. }
  680. }
  681. /* we now have a packet which can be read and processed */
  682. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  683. * reset by ssl3_get_finished */
  684. && (rr->type != SSL3_RT_HANDSHAKE))
  685. {
  686. /* We now have application data between CCS and Finished.
  687. * Most likely the packets were reordered on their way, so
  688. * buffer the application data for later processing rather
  689. * than dropping the connection.
  690. */
  691. dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num);
  692. rr->length = 0;
  693. goto start;
  694. }
  695. /* If the other end has shut down, throw anything we read away
  696. * (even in 'peek' mode) */
  697. if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
  698. {
  699. rr->length=0;
  700. s->rwstate=SSL_NOTHING;
  701. return(0);
  702. }
  703. if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  704. {
  705. /* make sure that we are not getting application data when we
  706. * are doing a handshake for the first time */
  707. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  708. (s->enc_read_ctx == NULL))
  709. {
  710. al=SSL_AD_UNEXPECTED_MESSAGE;
  711. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  712. goto f_err;
  713. }
  714. if (len <= 0) return(len);
  715. if ((unsigned int)len > rr->length)
  716. n = rr->length;
  717. else
  718. n = (unsigned int)len;
  719. memcpy(buf,&(rr->data[rr->off]),n);
  720. if (!peek)
  721. {
  722. rr->length-=n;
  723. rr->off+=n;
  724. if (rr->length == 0)
  725. {
  726. s->rstate=SSL_ST_READ_HEADER;
  727. rr->off=0;
  728. }
  729. }
  730. return(n);
  731. }
  732. /* If we get here, then type != rr->type; if we have a handshake
  733. * message, then it was unexpected (Hello Request or Client Hello). */
  734. /* In case of record types for which we have 'fragment' storage,
  735. * fill that so that we can process the data at a fixed place.
  736. */
  737. {
  738. unsigned int k, dest_maxlen = 0;
  739. unsigned char *dest = NULL;
  740. unsigned int *dest_len = NULL;
  741. if (rr->type == SSL3_RT_HANDSHAKE)
  742. {
  743. dest_maxlen = sizeof s->d1->handshake_fragment;
  744. dest = s->d1->handshake_fragment;
  745. dest_len = &s->d1->handshake_fragment_len;
  746. }
  747. else if (rr->type == SSL3_RT_ALERT)
  748. {
  749. dest_maxlen = sizeof(s->d1->alert_fragment);
  750. dest = s->d1->alert_fragment;
  751. dest_len = &s->d1->alert_fragment_len;
  752. }
  753. /* else it's a CCS message, or application data or wrong */
  754. else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC)
  755. {
  756. /* Application data while renegotiating
  757. * is allowed. Try again reading.
  758. */
  759. if (rr->type == SSL3_RT_APPLICATION_DATA)
  760. {
  761. BIO *bio;
  762. s->s3->in_read_app_data=2;
  763. bio=SSL_get_rbio(s);
  764. s->rwstate=SSL_READING;
  765. BIO_clear_retry_flags(bio);
  766. BIO_set_retry_read(bio);
  767. return(-1);
  768. }
  769. /* Not certain if this is the right error handling */
  770. al=SSL_AD_UNEXPECTED_MESSAGE;
  771. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
  772. goto f_err;
  773. }
  774. if (dest_maxlen > 0)
  775. {
  776. /* XDTLS: In a pathalogical case, the Client Hello
  777. * may be fragmented--don't always expect dest_maxlen bytes */
  778. if ( rr->length < dest_maxlen)
  779. {
  780. s->rstate=SSL_ST_READ_HEADER;
  781. rr->length = 0;
  782. goto start;
  783. }
  784. /* now move 'n' bytes: */
  785. for ( k = 0; k < dest_maxlen; k++)
  786. {
  787. dest[k] = rr->data[rr->off++];
  788. rr->length--;
  789. }
  790. *dest_len = dest_maxlen;
  791. }
  792. }
  793. /* s->d1->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
  794. * s->d1->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
  795. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
  796. /* If we are a client, check for an incoming 'Hello Request': */
  797. if ((!s->server) &&
  798. (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  799. (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  800. (s->session != NULL) && (s->session->cipher != NULL))
  801. {
  802. s->d1->handshake_fragment_len = 0;
  803. if ((s->d1->handshake_fragment[1] != 0) ||
  804. (s->d1->handshake_fragment[2] != 0) ||
  805. (s->d1->handshake_fragment[3] != 0))
  806. {
  807. al=SSL_AD_DECODE_ERROR;
  808. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_HELLO_REQUEST);
  809. goto f_err;
  810. }
  811. /* no need to check sequence number on HELLO REQUEST messages */
  812. if (s->msg_callback)
  813. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  814. s->d1->handshake_fragment, 4, s, s->msg_callback_arg);
  815. if (SSL_is_init_finished(s) &&
  816. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  817. !s->s3->renegotiate)
  818. {
  819. s->d1->handshake_read_seq++;
  820. s->new_session = 1;
  821. ssl3_renegotiate(s);
  822. if (ssl3_renegotiate_check(s))
  823. {
  824. i=s->handshake_func(s);
  825. if (i < 0) return(i);
  826. if (i == 0)
  827. {
  828. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  829. return(-1);
  830. }
  831. }
  832. }
  833. /* we either finished a handshake or ignored the request,
  834. * now try again to obtain the (application) data we were asked for */
  835. goto start;
  836. }
  837. if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH)
  838. {
  839. int alert_level = s->d1->alert_fragment[0];
  840. int alert_descr = s->d1->alert_fragment[1];
  841. s->d1->alert_fragment_len = 0;
  842. if (s->msg_callback)
  843. s->msg_callback(0, s->version, SSL3_RT_ALERT,
  844. s->d1->alert_fragment, 2, s, s->msg_callback_arg);
  845. if (s->info_callback != NULL)
  846. cb=s->info_callback;
  847. else if (s->ctx->info_callback != NULL)
  848. cb=s->ctx->info_callback;
  849. if (cb != NULL)
  850. {
  851. j = (alert_level << 8) | alert_descr;
  852. cb(s, SSL_CB_READ_ALERT, j);
  853. }
  854. if (alert_level == 1) /* warning */
  855. {
  856. s->s3->warn_alert = alert_descr;
  857. if (alert_descr == SSL_AD_CLOSE_NOTIFY)
  858. {
  859. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  860. return(0);
  861. }
  862. }
  863. else if (alert_level == 2) /* fatal */
  864. {
  865. char tmp[16];
  866. s->rwstate=SSL_NOTHING;
  867. s->s3->fatal_alert = alert_descr;
  868. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_AD_REASON_OFFSET + alert_descr);
  869. BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
  870. ERR_add_error_data(2,"SSL alert number ",tmp);
  871. s->shutdown|=SSL_RECEIVED_SHUTDOWN;
  872. SSL_CTX_remove_session(s->ctx,s->session);
  873. return(0);
  874. }
  875. else
  876. {
  877. al=SSL_AD_ILLEGAL_PARAMETER;
  878. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  879. goto f_err;
  880. }
  881. goto start;
  882. }
  883. if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
  884. {
  885. s->rwstate=SSL_NOTHING;
  886. rr->length=0;
  887. return(0);
  888. }
  889. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  890. {
  891. struct ccs_header_st ccs_hdr;
  892. unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
  893. dtls1_get_ccs_header(rr->data, &ccs_hdr);
  894. /* 'Change Cipher Spec' is just a single byte, so we know
  895. * exactly what the record payload has to look like */
  896. /* XDTLS: check that epoch is consistent */
  897. if ( (rr->length != ccs_hdr_len) ||
  898. (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS))
  899. {
  900. al=SSL_AD_ILLEGAL_PARAMETER;
  901. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  902. goto f_err;
  903. }
  904. rr->length=0;
  905. if (s->msg_callback)
  906. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
  907. rr->data, 1, s, s->msg_callback_arg);
  908. /* We can't process a CCS now, because previous handshake
  909. * messages are still missing, so just drop it.
  910. */
  911. if (!s->d1->change_cipher_spec_ok)
  912. {
  913. goto start;
  914. }
  915. s->d1->change_cipher_spec_ok = 0;
  916. s->s3->change_cipher_spec=1;
  917. if (!ssl3_do_change_cipher_spec(s))
  918. goto err;
  919. /* do this whenever CCS is processed */
  920. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  921. goto start;
  922. }
  923. /* Unexpected handshake message (Client Hello, or protocol violation) */
  924. if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  925. !s->in_handshake)
  926. {
  927. struct hm_header_st msg_hdr;
  928. /* this may just be a stale retransmit */
  929. dtls1_get_message_header(rr->data, &msg_hdr);
  930. if( rr->epoch != s->d1->r_epoch)
  931. {
  932. rr->length = 0;
  933. goto start;
  934. }
  935. /* If we are server, we may have a repeated FINISHED of the
  936. * client here, then retransmit our CCS and FINISHED.
  937. */
  938. if (msg_hdr.type == SSL3_MT_FINISHED)
  939. {
  940. if (dtls1_check_timeout_num(s) < 0)
  941. return -1;
  942. dtls1_retransmit_buffered_messages(s);
  943. rr->length = 0;
  944. goto start;
  945. }
  946. if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
  947. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
  948. {
  949. s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
  950. s->renegotiate=1;
  951. s->new_session=1;
  952. }
  953. i=s->handshake_func(s);
  954. if (i < 0) return(i);
  955. if (i == 0)
  956. {
  957. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  958. return(-1);
  959. }
  960. goto start;
  961. }
  962. switch (rr->type)
  963. {
  964. default:
  965. /* TLS just ignores unknown message types */
  966. if (s->version == TLS1_VERSION)
  967. {
  968. rr->length = 0;
  969. goto start;
  970. }
  971. al=SSL_AD_UNEXPECTED_MESSAGE;
  972. OPENSSL_PUT_ERROR(SSL, 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. OPENSSL_PUT_ERROR(SSL, 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. OPENSSL_PUT_ERROR(SSL, 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. int i;
  1024. if (SSL_in_init(s) && !s->in_handshake)
  1025. {
  1026. i=s->handshake_func(s);
  1027. if (i < 0) return(i);
  1028. if (i == 0)
  1029. {
  1030. OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  1031. return -1;
  1032. }
  1033. }
  1034. if (len > SSL3_RT_MAX_PLAIN_LENGTH)
  1035. {
  1036. OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes, SSL_R_DTLS_MESSAGE_TOO_BIG);
  1037. return -1;
  1038. }
  1039. i = dtls1_write_bytes(s, type, buf_, len);
  1040. return i;
  1041. }
  1042. /* this only happens when a client hello is received and a handshake
  1043. * is started. */
  1044. static int
  1045. have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  1046. int len, int peek)
  1047. {
  1048. if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
  1049. /* (partially) satisfy request from storage */
  1050. {
  1051. unsigned char *src = s->d1->handshake_fragment;
  1052. unsigned char *dst = buf;
  1053. unsigned int k,n;
  1054. /* peek == 0 */
  1055. n = 0;
  1056. while ((len > 0) && (s->d1->handshake_fragment_len > 0))
  1057. {
  1058. *dst++ = *src++;
  1059. len--; s->d1->handshake_fragment_len--;
  1060. n++;
  1061. }
  1062. /* move any remaining fragment bytes: */
  1063. for (k = 0; k < s->d1->handshake_fragment_len; k++)
  1064. s->d1->handshake_fragment[k] = *src++;
  1065. return n;
  1066. }
  1067. return 0;
  1068. }
  1069. /* Call this to write data in records of type 'type'
  1070. * It will return <= 0 if not all data has been sent or non-blocking IO.
  1071. */
  1072. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
  1073. {
  1074. int i;
  1075. assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  1076. s->rwstate=SSL_NOTHING;
  1077. i=do_dtls1_write(s, type, buf, len);
  1078. return i;
  1079. }
  1080. static int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
  1081. unsigned int len)
  1082. {
  1083. unsigned char *p,*pseq;
  1084. int i,mac_size,clear=0;
  1085. int prefix_len = 0;
  1086. int eivlen;
  1087. SSL3_RECORD *wr;
  1088. SSL3_BUFFER *wb;
  1089. SSL_SESSION *sess;
  1090. /* first check if there is a SSL3_BUFFER still being written
  1091. * out. This will happen with non blocking IO */
  1092. if (s->s3->wbuf.left != 0)
  1093. {
  1094. assert(0); /* XDTLS: want to see if we ever get here */
  1095. return(ssl3_write_pending(s,type,buf,len));
  1096. }
  1097. /* If we have an alert to send, lets send it */
  1098. if (s->s3->alert_dispatch)
  1099. {
  1100. i=s->method->ssl_dispatch_alert(s);
  1101. if (i <= 0)
  1102. return(i);
  1103. /* if it went, fall through and send more stuff */
  1104. }
  1105. if (len == 0)
  1106. return 0;
  1107. wr= &(s->s3->wrec);
  1108. wb= &(s->s3->wbuf);
  1109. sess=s->session;
  1110. if ( (sess == NULL) ||
  1111. (s->enc_write_ctx == NULL) ||
  1112. (EVP_MD_CTX_md(s->write_hash) == NULL))
  1113. clear=1;
  1114. if (clear)
  1115. mac_size=0;
  1116. else
  1117. {
  1118. mac_size=EVP_MD_CTX_size(s->write_hash);
  1119. if (mac_size < 0)
  1120. goto err;
  1121. }
  1122. p = wb->buf + prefix_len;
  1123. /* write the header */
  1124. *(p++)=type&0xff;
  1125. wr->type=type;
  1126. /* Special case: for hello verify request, client version 1.0 and
  1127. * we haven't decided which version to use yet send back using
  1128. * version 1.0 header: otherwise some clients will ignore it.
  1129. */
  1130. if (s->method->version == DTLS_ANY_VERSION)
  1131. {
  1132. *(p++)=DTLS1_VERSION>>8;
  1133. *(p++)=DTLS1_VERSION&0xff;
  1134. }
  1135. else
  1136. {
  1137. *(p++)=s->version>>8;
  1138. *(p++)=s->version&0xff;
  1139. }
  1140. /* field where we are to write out packet epoch, seq num and len */
  1141. pseq=p;
  1142. p+=10;
  1143. /* Explicit IV length, block ciphers appropriate version flag */
  1144. if (s->enc_write_ctx)
  1145. {
  1146. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  1147. if (mode == EVP_CIPH_CBC_MODE)
  1148. {
  1149. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  1150. if (eivlen <= 1)
  1151. eivlen = 0;
  1152. }
  1153. /* Need explicit part of IV for GCM mode */
  1154. else if (mode == EVP_CIPH_GCM_MODE)
  1155. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  1156. else
  1157. eivlen = 0;
  1158. }
  1159. else
  1160. eivlen = 0;
  1161. /* lets setup the record stuff. */
  1162. wr->data=p + eivlen; /* make room for IV in case of CBC */
  1163. wr->length=(int)len;
  1164. wr->input=(unsigned char *)buf;
  1165. /* we now 'read' from wr->input, wr->length bytes into
  1166. * wr->data */
  1167. memcpy(wr->data,wr->input,wr->length);
  1168. wr->input=wr->data;
  1169. /* we should still have the output to wr->data and the input
  1170. * from wr->input. Length should be wr->length.
  1171. * wr->data still points in the wb->buf */
  1172. if (mac_size != 0)
  1173. {
  1174. if(s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
  1175. goto err;
  1176. wr->length+=mac_size;
  1177. }
  1178. /* this is true regardless of mac size */
  1179. wr->input=p;
  1180. wr->data=p;
  1181. if (eivlen)
  1182. wr->length += eivlen;
  1183. s->method->ssl3_enc->enc(s,1);
  1184. /* record length after mac and block padding */
  1185. /* if (type == SSL3_RT_APPLICATION_DATA ||
  1186. (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
  1187. /* there's only one epoch between handshake and app data */
  1188. s2n(s->d1->w_epoch, pseq);
  1189. /* XDTLS: ?? */
  1190. /* else
  1191. s2n(s->d1->handshake_epoch, pseq); */
  1192. memcpy(pseq, &(s->s3->write_sequence[2]), 6);
  1193. pseq+=6;
  1194. s2n(wr->length,pseq);
  1195. if (s->msg_callback)
  1196. s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH, DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  1197. /* we should now have
  1198. * wr->data pointing to the encrypted data, which is
  1199. * wr->length long */
  1200. wr->type=type; /* not needed but helps for debugging */
  1201. wr->length+=DTLS1_RT_HEADER_LENGTH;
  1202. #if 0 /* this is now done at the message layer */
  1203. /* buffer the record, making it easy to handle retransmits */
  1204. if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1205. dtls1_buffer_record(s, wr->data, wr->length,
  1206. *((PQ_64BIT *)&(s->s3->write_sequence[0])));
  1207. #endif
  1208. ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
  1209. /* now let's set up wb */
  1210. wb->left = prefix_len + wr->length;
  1211. wb->offset = 0;
  1212. /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
  1213. s->s3->wpend_tot=len;
  1214. s->s3->wpend_buf=buf;
  1215. s->s3->wpend_type=type;
  1216. s->s3->wpend_ret=len;
  1217. /* we now just need to write the buffer */
  1218. return ssl3_write_pending(s,type,buf,len);
  1219. err:
  1220. return -1;
  1221. }
  1222. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
  1223. {
  1224. int cmp;
  1225. unsigned int shift;
  1226. const unsigned char *seq = s->s3->read_sequence;
  1227. cmp = satsub64be(seq,bitmap->max_seq_num);
  1228. if (cmp > 0)
  1229. {
  1230. memcpy (s->s3->rrec.seq_num,seq,8);
  1231. return 1; /* this record in new */
  1232. }
  1233. shift = -cmp;
  1234. if (shift >= sizeof(bitmap->map)*8)
  1235. return 0; /* stale, outside the window */
  1236. else if (bitmap->map & (((uint64_t) 1) << shift))
  1237. return 0; /* record previously received */
  1238. memcpy (s->s3->rrec.seq_num,seq,8);
  1239. return 1;
  1240. }
  1241. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
  1242. {
  1243. int cmp;
  1244. unsigned int shift;
  1245. const unsigned char *seq = s->s3->read_sequence;
  1246. cmp = satsub64be(seq,bitmap->max_seq_num);
  1247. if (cmp > 0)
  1248. {
  1249. shift = cmp;
  1250. if (shift < sizeof(bitmap->map)*8)
  1251. bitmap->map <<= shift, bitmap->map |= 1UL;
  1252. else
  1253. bitmap->map = 1UL;
  1254. memcpy(bitmap->max_seq_num,seq,8);
  1255. }
  1256. else {
  1257. shift = -cmp;
  1258. if (shift < sizeof(bitmap->map)*8)
  1259. bitmap->map |= ((uint64_t) 1) << shift;
  1260. }
  1261. }
  1262. int dtls1_dispatch_alert(SSL *s)
  1263. {
  1264. int i,j;
  1265. void (*cb)(const SSL *ssl,int type,int val)=NULL;
  1266. unsigned char buf[DTLS1_AL_HEADER_LENGTH];
  1267. unsigned char *ptr = &buf[0];
  1268. s->s3->alert_dispatch=0;
  1269. memset(buf, 0x00, sizeof(buf));
  1270. *ptr++ = s->s3->send_alert[0];
  1271. *ptr++ = s->s3->send_alert[1];
  1272. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf));
  1273. if (i <= 0)
  1274. {
  1275. s->s3->alert_dispatch=1;
  1276. /* fprintf( stderr, "not done with alert\n" ); */
  1277. }
  1278. else
  1279. {
  1280. if (s->s3->send_alert[0] == SSL3_AL_FATAL)
  1281. (void)BIO_flush(s->wbio);
  1282. if (s->msg_callback)
  1283. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
  1284. 2, s, s->msg_callback_arg);
  1285. if (s->info_callback != NULL)
  1286. cb=s->info_callback;
  1287. else if (s->ctx->info_callback != NULL)
  1288. cb=s->ctx->info_callback;
  1289. if (cb != NULL)
  1290. {
  1291. j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
  1292. cb(s,SSL_CB_WRITE_ALERT,j);
  1293. }
  1294. }
  1295. return(i);
  1296. }
  1297. static DTLS1_BITMAP *
  1298. dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
  1299. {
  1300. *is_next_epoch = 0;
  1301. /* In current epoch, accept HM, CCS, DATA, & ALERT */
  1302. if (rr->epoch == s->d1->r_epoch)
  1303. return &s->d1->bitmap;
  1304. /* Only HM and ALERT messages can be from the next epoch */
  1305. else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
  1306. (rr->type == SSL3_RT_HANDSHAKE ||
  1307. rr->type == SSL3_RT_ALERT))
  1308. {
  1309. *is_next_epoch = 1;
  1310. return &s->d1->next_bitmap;
  1311. }
  1312. return NULL;
  1313. }
  1314. #if 0
  1315. static int
  1316. dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority,
  1317. unsigned long *offset)
  1318. {
  1319. /* alerts are passed up immediately */
  1320. if ( rr->type == SSL3_RT_APPLICATION_DATA ||
  1321. rr->type == SSL3_RT_ALERT)
  1322. return 0;
  1323. /* Only need to buffer if a handshake is underway.
  1324. * (this implies that Hello Request and Client Hello are passed up
  1325. * immediately) */
  1326. if ( SSL_in_init(s))
  1327. {
  1328. unsigned char *data = rr->data;
  1329. /* need to extract the HM/CCS sequence number here */
  1330. if ( rr->type == SSL3_RT_HANDSHAKE ||
  1331. rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
  1332. {
  1333. unsigned short seq_num;
  1334. struct hm_header_st msg_hdr;
  1335. struct ccs_header_st ccs_hdr;
  1336. if ( rr->type == SSL3_RT_HANDSHAKE)
  1337. {
  1338. dtls1_get_message_header(data, &msg_hdr);
  1339. seq_num = msg_hdr.seq;
  1340. *offset = msg_hdr.frag_off;
  1341. }
  1342. else
  1343. {
  1344. dtls1_get_ccs_header(data, &ccs_hdr);
  1345. seq_num = ccs_hdr.seq;
  1346. *offset = 0;
  1347. }
  1348. /* this is either a record we're waiting for, or a
  1349. * retransmit of something we happened to previously
  1350. * receive (higher layers will drop the repeat silently */
  1351. if ( seq_num < s->d1->handshake_read_seq)
  1352. return 0;
  1353. if (rr->type == SSL3_RT_HANDSHAKE &&
  1354. seq_num == s->d1->handshake_read_seq &&
  1355. msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
  1356. return 0;
  1357. else if ( seq_num == s->d1->handshake_read_seq &&
  1358. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
  1359. msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
  1360. return 0;
  1361. else
  1362. {
  1363. *priority = seq_num;
  1364. return 1;
  1365. }
  1366. }
  1367. else /* unknown record type */
  1368. return 0;
  1369. }
  1370. return 0;
  1371. }
  1372. #endif
  1373. void
  1374. dtls1_reset_seq_numbers(SSL *s, int rw)
  1375. {
  1376. unsigned char *seq;
  1377. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  1378. if ( rw & SSL3_CC_READ)
  1379. {
  1380. seq = s->s3->read_sequence;
  1381. s->d1->r_epoch++;
  1382. memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
  1383. memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
  1384. }
  1385. else
  1386. {
  1387. seq = s->s3->write_sequence;
  1388. memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
  1389. s->d1->w_epoch++;
  1390. }
  1391. memset(seq, 0x00, seq_bytes);
  1392. }