d1_pkt.c 47 KB

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