d1_pkt.c 47 KB

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