rec_layer_d1.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265
  1. /* ssl/record/rec_layer_d1.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. #include "record_locl.h"
  124. int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl)
  125. {
  126. DTLS_RECORD_LAYER *d;
  127. if ((d = OPENSSL_malloc(sizeof(*d))) == NULL)
  128. return (0);
  129. rl->d = d;
  130. d->unprocessed_rcds.q = pqueue_new();
  131. d->processed_rcds.q = pqueue_new();
  132. d->buffered_app_data.q = pqueue_new();
  133. if (d->unprocessed_rcds.q == NULL || d->processed_rcds.q == NULL
  134. || d->buffered_app_data.q == NULL) {
  135. pqueue_free(d->unprocessed_rcds.q);
  136. pqueue_free(d->processed_rcds.q);
  137. pqueue_free(d->buffered_app_data.q);
  138. OPENSSL_free(d);
  139. rl->d = NULL;
  140. return (0);
  141. }
  142. return 1;
  143. }
  144. void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl)
  145. {
  146. DTLS_RECORD_LAYER_clear(rl);
  147. pqueue_free(rl->d->unprocessed_rcds.q);
  148. pqueue_free(rl->d->processed_rcds.q);
  149. pqueue_free(rl->d->buffered_app_data.q);
  150. OPENSSL_free(rl->d);
  151. rl->d = NULL;
  152. }
  153. void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl)
  154. {
  155. DTLS_RECORD_LAYER *d;
  156. pitem *item = NULL;
  157. DTLS1_RECORD_DATA *rdata;
  158. pqueue unprocessed_rcds;
  159. pqueue processed_rcds;
  160. pqueue buffered_app_data;
  161. d = rl->d;
  162. while ((item = pqueue_pop(d->unprocessed_rcds.q)) != NULL) {
  163. rdata = (DTLS1_RECORD_DATA *)item->data;
  164. OPENSSL_free(rdata->rbuf.buf);
  165. OPENSSL_free(item->data);
  166. pitem_free(item);
  167. }
  168. while ((item = pqueue_pop(d->processed_rcds.q)) != NULL) {
  169. rdata = (DTLS1_RECORD_DATA *)item->data;
  170. OPENSSL_free(rdata->rbuf.buf);
  171. OPENSSL_free(item->data);
  172. pitem_free(item);
  173. }
  174. while ((item = pqueue_pop(d->buffered_app_data.q)) != NULL) {
  175. rdata = (DTLS1_RECORD_DATA *)item->data;
  176. OPENSSL_free(rdata->rbuf.buf);
  177. OPENSSL_free(item->data);
  178. pitem_free(item);
  179. }
  180. unprocessed_rcds = d->unprocessed_rcds.q;
  181. processed_rcds = d->processed_rcds.q;
  182. buffered_app_data = d->buffered_app_data.q;
  183. memset(d, 0, sizeof(*d));
  184. d->unprocessed_rcds.q = unprocessed_rcds;
  185. d->processed_rcds.q = processed_rcds;
  186. d->buffered_app_data.q = buffered_app_data;
  187. }
  188. void DTLS_RECORD_LAYER_set_saved_w_epoch(RECORD_LAYER *rl, unsigned short e)
  189. {
  190. if (e == rl->d->w_epoch - 1) {
  191. memcpy(rl->d->curr_write_sequence,
  192. rl->write_sequence,
  193. sizeof(rl->write_sequence));
  194. memcpy(rl->write_sequence,
  195. rl->d->last_write_sequence,
  196. sizeof(rl->write_sequence));
  197. } else if (e == rl->d->w_epoch + 1) {
  198. memcpy(rl->d->last_write_sequence,
  199. rl->write_sequence,
  200. sizeof(unsigned char[8]));
  201. memcpy(rl->write_sequence,
  202. rl->d->curr_write_sequence,
  203. sizeof(rl->write_sequence));
  204. }
  205. rl->d->w_epoch = e;
  206. }
  207. void DTLS_RECORD_LAYER_resync_write(RECORD_LAYER *rl)
  208. {
  209. memcpy(rl->write_sequence, rl->read_sequence, sizeof(rl->write_sequence));
  210. }
  211. void DTLS_RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, unsigned char *seq)
  212. {
  213. memcpy(rl->write_sequence, seq, SEQ_NUM_SIZE);
  214. }
  215. static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  216. int len, int peek);
  217. /* copy buffered record into SSL structure */
  218. static int dtls1_copy_record(SSL *s, pitem *item)
  219. {
  220. DTLS1_RECORD_DATA *rdata;
  221. rdata = (DTLS1_RECORD_DATA *)item->data;
  222. SSL3_BUFFER_release(&s->rlayer.rbuf);
  223. s->rlayer.packet = rdata->packet;
  224. s->rlayer.packet_length = rdata->packet_length;
  225. memcpy(&s->rlayer.rbuf, &(rdata->rbuf), sizeof(SSL3_BUFFER));
  226. memcpy(&s->rlayer.rrec, &(rdata->rrec), sizeof(SSL3_RECORD));
  227. /* Set proper sequence number for mac calculation */
  228. memcpy(&(s->rlayer.read_sequence[2]), &(rdata->packet[5]), 6);
  229. return (1);
  230. }
  231. int dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
  232. {
  233. DTLS1_RECORD_DATA *rdata;
  234. pitem *item;
  235. /* Limit the size of the queue to prevent DOS attacks */
  236. if (pqueue_size(queue->q) >= 100)
  237. return 0;
  238. rdata = OPENSSL_malloc(sizeof(*rdata));
  239. item = pitem_new(priority, rdata);
  240. if (rdata == NULL || item == NULL) {
  241. OPENSSL_free(rdata);
  242. pitem_free(item);
  243. SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
  244. return -1;
  245. }
  246. rdata->packet = s->rlayer.packet;
  247. rdata->packet_length = s->rlayer.packet_length;
  248. memcpy(&(rdata->rbuf), &s->rlayer.rbuf, sizeof(SSL3_BUFFER));
  249. memcpy(&(rdata->rrec), &s->rlayer.rrec, sizeof(SSL3_RECORD));
  250. item->data = rdata;
  251. #ifndef OPENSSL_NO_SCTP
  252. /* Store bio_dgram_sctp_rcvinfo struct */
  253. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  254. (SSL_get_state(s) == TLS_ST_SR_FINISHED
  255. || SSL_get_state(s) == TLS_ST_CR_FINISHED)) {
  256. BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
  257. sizeof(rdata->recordinfo), &rdata->recordinfo);
  258. }
  259. #endif
  260. s->rlayer.packet = NULL;
  261. s->rlayer.packet_length = 0;
  262. memset(&s->rlayer.rbuf, 0, sizeof(s->rlayer.rbuf));
  263. memset(&s->rlayer.rrec, 0, sizeof(s->rlayer.rrec));
  264. if (!ssl3_setup_buffers(s)) {
  265. SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
  266. OPENSSL_free(rdata->rbuf.buf);
  267. OPENSSL_free(rdata);
  268. pitem_free(item);
  269. return (-1);
  270. }
  271. /* insert should not fail, since duplicates are dropped */
  272. if (pqueue_insert(queue->q, item) == NULL) {
  273. SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
  274. OPENSSL_free(rdata->rbuf.buf);
  275. OPENSSL_free(rdata);
  276. pitem_free(item);
  277. return (-1);
  278. }
  279. return (1);
  280. }
  281. int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
  282. {
  283. pitem *item;
  284. item = pqueue_pop(queue->q);
  285. if (item) {
  286. dtls1_copy_record(s, item);
  287. OPENSSL_free(item->data);
  288. pitem_free(item);
  289. return (1);
  290. }
  291. return (0);
  292. }
  293. /*
  294. * retrieve a buffered record that belongs to the new epoch, i.e., not
  295. * processed yet
  296. */
  297. #define dtls1_get_unprocessed_record(s) \
  298. dtls1_retrieve_buffered_record((s), \
  299. &((s)->rlayer.d->unprocessed_rcds))
  300. int dtls1_process_buffered_records(SSL *s)
  301. {
  302. pitem *item;
  303. item = pqueue_peek(s->rlayer.d->unprocessed_rcds.q);
  304. if (item) {
  305. /* Check if epoch is current. */
  306. if (s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch)
  307. return (1); /* Nothing to do. */
  308. /* Process all the records. */
  309. while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
  310. dtls1_get_unprocessed_record(s);
  311. if (!dtls1_process_record(s))
  312. return (0);
  313. if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
  314. SSL3_RECORD_get_seq_num(&s->rlayer.rrec)) < 0)
  315. return -1;
  316. }
  317. }
  318. /*
  319. * sync epoch numbers once all the unprocessed records have been
  320. * processed
  321. */
  322. s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch;
  323. s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1;
  324. return (1);
  325. }
  326. /*-
  327. * Return up to 'len' payload bytes received in 'type' records.
  328. * 'type' is one of the following:
  329. *
  330. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  331. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  332. * - 0 (during a shutdown, no data has to be returned)
  333. *
  334. * If we don't have stored data to work from, read a SSL/TLS record first
  335. * (possibly multiple records if we still don't have anything to return).
  336. *
  337. * This function must handle any surprises the peer may have for us, such as
  338. * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
  339. * messages are treated as if they were handshake messages *if* the |recd_type|
  340. * argument is non NULL.
  341. * Also if record payloads contain fragments too small to process, we store
  342. * them until there is enough for the respective protocol (the record protocol
  343. * may use arbitrary fragmentation and even interleaving):
  344. * Change cipher spec protocol
  345. * just 1 byte needed, no need for keeping anything stored
  346. * Alert protocol
  347. * 2 bytes needed (AlertLevel, AlertDescription)
  348. * Handshake protocol
  349. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  350. * to detect unexpected Client Hello and Hello Request messages
  351. * here, anything else is handled by higher layers
  352. * Application data protocol
  353. * none of our business
  354. */
  355. int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
  356. int len, int peek)
  357. {
  358. int al, i, j, ret;
  359. unsigned int n;
  360. SSL3_RECORD *rr;
  361. void (*cb) (const SSL *ssl, int type2, int val) = NULL;
  362. if (!SSL3_BUFFER_is_initialised(&s->rlayer.rbuf)) {
  363. /* Not initialized yet */
  364. if (!ssl3_setup_buffers(s))
  365. return (-1);
  366. }
  367. if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
  368. (type != SSL3_RT_HANDSHAKE)) ||
  369. (peek && (type != SSL3_RT_APPLICATION_DATA))) {
  370. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  371. return -1;
  372. }
  373. /*
  374. * check whether there's a handshake message (client hello?) waiting
  375. */
  376. if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
  377. return ret;
  378. /*
  379. * Now s->rlayer.d->handshake_fragment_len == 0 if
  380. * type == SSL3_RT_HANDSHAKE.
  381. */
  382. #ifndef OPENSSL_NO_SCTP
  383. /*
  384. * Continue handshake if it had to be interrupted to read app data with
  385. * SCTP.
  386. */
  387. if ((!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) ||
  388. (BIO_dgram_is_sctp(SSL_get_rbio(s))
  389. && ossl_statem_in_sctp_read_sock(s)
  390. && s->s3->in_read_app_data != 2))
  391. #else
  392. if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s))
  393. #endif
  394. {
  395. /* type == SSL3_RT_APPLICATION_DATA */
  396. i = s->handshake_func(s);
  397. if (i < 0)
  398. return (i);
  399. if (i == 0) {
  400. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  401. return (-1);
  402. }
  403. }
  404. start:
  405. s->rwstate = SSL_NOTHING;
  406. /*-
  407. * s->s3->rrec.type - is the type of record
  408. * s->s3->rrec.data, - data
  409. * s->s3->rrec.off, - offset into 'data' for next read
  410. * s->s3->rrec.length, - number of bytes.
  411. */
  412. rr = &s->rlayer.rrec;
  413. /*
  414. * We are not handshaking and have no data yet, so process data buffered
  415. * during the last handshake in advance, if any.
  416. */
  417. if (SSL_is_init_finished(s) && SSL3_RECORD_get_length(rr) == 0) {
  418. pitem *item;
  419. item = pqueue_pop(s->rlayer.d->buffered_app_data.q);
  420. if (item) {
  421. #ifndef OPENSSL_NO_SCTP
  422. /* Restore bio_dgram_sctp_rcvinfo struct */
  423. if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
  424. DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
  425. BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
  426. sizeof(rdata->recordinfo), &rdata->recordinfo);
  427. }
  428. #endif
  429. dtls1_copy_record(s, item);
  430. OPENSSL_free(item->data);
  431. pitem_free(item);
  432. }
  433. }
  434. /* Check for timeout */
  435. if (dtls1_handle_timeout(s) > 0)
  436. goto start;
  437. /* get new packet if necessary */
  438. if ((SSL3_RECORD_get_length(rr) == 0)
  439. || (s->rlayer.rstate == SSL_ST_READ_BODY)) {
  440. ret = dtls1_get_record(s);
  441. if (ret <= 0) {
  442. ret = dtls1_read_failed(s, ret);
  443. /* anything other than a timeout is an error */
  444. if (ret <= 0)
  445. return (ret);
  446. else
  447. goto start;
  448. }
  449. }
  450. /* we now have a packet which can be read and processed */
  451. if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
  452. * reset by ssl3_get_finished */
  453. && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
  454. /*
  455. * We now have application data between CCS and Finished. Most likely
  456. * the packets were reordered on their way, so buffer the application
  457. * data for later processing rather than dropping the connection.
  458. */
  459. if (dtls1_buffer_record(s, &(s->rlayer.d->buffered_app_data),
  460. SSL3_RECORD_get_seq_num(rr)) < 0) {
  461. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  462. return -1;
  463. }
  464. SSL3_RECORD_set_length(rr, 0);
  465. goto start;
  466. }
  467. /*
  468. * If the other end has shut down, throw anything we read away (even in
  469. * 'peek' mode)
  470. */
  471. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  472. SSL3_RECORD_set_length(rr, 0);
  473. s->rwstate = SSL_NOTHING;
  474. return (0);
  475. }
  476. if (type == SSL3_RECORD_get_type(rr)
  477. || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
  478. && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
  479. /*
  480. * SSL3_RT_APPLICATION_DATA or
  481. * SSL3_RT_HANDSHAKE or
  482. * SSL3_RT_CHANGE_CIPHER_SPEC
  483. */
  484. /*
  485. * make sure that we are not getting application data when we are
  486. * doing a handshake for the first time
  487. */
  488. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  489. (s->enc_read_ctx == NULL)) {
  490. al = SSL_AD_UNEXPECTED_MESSAGE;
  491. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
  492. goto f_err;
  493. }
  494. if (recvd_type != NULL)
  495. *recvd_type = SSL3_RECORD_get_type(rr);
  496. if (len <= 0)
  497. return (len);
  498. if ((unsigned int)len > SSL3_RECORD_get_length(rr))
  499. n = SSL3_RECORD_get_length(rr);
  500. else
  501. n = (unsigned int)len;
  502. memcpy(buf, &(SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]), n);
  503. if (!peek) {
  504. SSL3_RECORD_add_length(rr, -n);
  505. SSL3_RECORD_add_off(rr, n);
  506. if (SSL3_RECORD_get_length(rr) == 0) {
  507. s->rlayer.rstate = SSL_ST_READ_HEADER;
  508. SSL3_RECORD_set_off(rr, 0);
  509. }
  510. }
  511. #ifndef OPENSSL_NO_SCTP
  512. /*
  513. * We were about to renegotiate but had to read belated application
  514. * data first, so retry.
  515. */
  516. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  517. SSL3_RECORD_get_type(rr) == SSL3_RT_APPLICATION_DATA &&
  518. ossl_statem_in_sctp_read_sock(s)) {
  519. s->rwstate = SSL_READING;
  520. BIO_clear_retry_flags(SSL_get_rbio(s));
  521. BIO_set_retry_read(SSL_get_rbio(s));
  522. }
  523. /*
  524. * We might had to delay a close_notify alert because of reordered
  525. * app data. If there was an alert and there is no message to read
  526. * anymore, finally set shutdown.
  527. */
  528. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  529. s->d1->shutdown_received
  530. && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
  531. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  532. return (0);
  533. }
  534. #endif
  535. return (n);
  536. }
  537. /*
  538. * If we get here, then type != rr->type; if we have a handshake message,
  539. * then it was unexpected (Hello Request or Client Hello).
  540. */
  541. /*
  542. * In case of record types for which we have 'fragment' storage, fill
  543. * that so that we can process the data at a fixed place.
  544. */
  545. {
  546. unsigned int k, dest_maxlen = 0;
  547. unsigned char *dest = NULL;
  548. unsigned int *dest_len = NULL;
  549. if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
  550. dest_maxlen = sizeof s->rlayer.d->handshake_fragment;
  551. dest = s->rlayer.d->handshake_fragment;
  552. dest_len = &s->rlayer.d->handshake_fragment_len;
  553. } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
  554. dest_maxlen = sizeof(s->rlayer.d->alert_fragment);
  555. dest = s->rlayer.d->alert_fragment;
  556. dest_len = &s->rlayer.d->alert_fragment_len;
  557. }
  558. #ifndef OPENSSL_NO_HEARTBEATS
  559. else if (SSL3_RECORD_get_type(rr) == TLS1_RT_HEARTBEAT) {
  560. /* We allow a 0 return */
  561. if (dtls1_process_heartbeat(s, SSL3_RECORD_get_data(rr),
  562. SSL3_RECORD_get_length(rr)) < 0) {
  563. return -1;
  564. }
  565. /* Exit and notify application to read again */
  566. SSL3_RECORD_set_length(rr, 0);
  567. s->rwstate = SSL_READING;
  568. BIO_clear_retry_flags(SSL_get_rbio(s));
  569. BIO_set_retry_read(SSL_get_rbio(s));
  570. return (-1);
  571. }
  572. #endif
  573. /* else it's a CCS message, or application data or wrong */
  574. else if (SSL3_RECORD_get_type(rr) != SSL3_RT_CHANGE_CIPHER_SPEC) {
  575. /*
  576. * Application data while renegotiating is allowed. Try again
  577. * reading.
  578. */
  579. if (SSL3_RECORD_get_type(rr) == SSL3_RT_APPLICATION_DATA) {
  580. BIO *bio;
  581. s->s3->in_read_app_data = 2;
  582. bio = SSL_get_rbio(s);
  583. s->rwstate = SSL_READING;
  584. BIO_clear_retry_flags(bio);
  585. BIO_set_retry_read(bio);
  586. return (-1);
  587. }
  588. /* Not certain if this is the right error handling */
  589. al = SSL_AD_UNEXPECTED_MESSAGE;
  590. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  591. goto f_err;
  592. }
  593. if (dest_maxlen > 0) {
  594. /*
  595. * XDTLS: In a pathalogical case, the Client Hello may be
  596. * fragmented--don't always expect dest_maxlen bytes
  597. */
  598. if (SSL3_RECORD_get_length(rr) < dest_maxlen) {
  599. #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
  600. /*
  601. * for normal alerts rr->length is 2, while
  602. * dest_maxlen is 7 if we were to handle this
  603. * non-existing alert...
  604. */
  605. FIX ME
  606. #endif
  607. s->rlayer.rstate = SSL_ST_READ_HEADER;
  608. SSL3_RECORD_set_length(rr, 0);
  609. goto start;
  610. }
  611. /* now move 'n' bytes: */
  612. for (k = 0; k < dest_maxlen; k++) {
  613. dest[k] = SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
  614. SSL3_RECORD_add_off(rr, 1);
  615. SSL3_RECORD_add_length(rr, -1);
  616. }
  617. *dest_len = dest_maxlen;
  618. }
  619. }
  620. /*-
  621. * s->rlayer.d->handshake_fragment_len == 12 iff rr->type == SSL3_RT_HANDSHAKE;
  622. * s->rlayer.d->alert_fragment_len == 7 iff rr->type == SSL3_RT_ALERT.
  623. * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
  624. */
  625. /* If we are a client, check for an incoming 'Hello Request': */
  626. if ((!s->server) &&
  627. (s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  628. (s->rlayer.d->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
  629. (s->session != NULL) && (s->session->cipher != NULL)) {
  630. s->rlayer.d->handshake_fragment_len = 0;
  631. if ((s->rlayer.d->handshake_fragment[1] != 0) ||
  632. (s->rlayer.d->handshake_fragment[2] != 0) ||
  633. (s->rlayer.d->handshake_fragment[3] != 0)) {
  634. al = SSL_AD_DECODE_ERROR;
  635. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
  636. goto f_err;
  637. }
  638. /*
  639. * no need to check sequence number on HELLO REQUEST messages
  640. */
  641. if (s->msg_callback)
  642. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  643. s->rlayer.d->handshake_fragment, 4, s,
  644. s->msg_callback_arg);
  645. if (SSL_is_init_finished(s) &&
  646. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
  647. !s->s3->renegotiate) {
  648. s->d1->handshake_read_seq++;
  649. s->new_session = 1;
  650. ssl3_renegotiate(s);
  651. if (ssl3_renegotiate_check(s)) {
  652. i = s->handshake_func(s);
  653. if (i < 0)
  654. return (i);
  655. if (i == 0) {
  656. SSLerr(SSL_F_DTLS1_READ_BYTES,
  657. SSL_R_SSL_HANDSHAKE_FAILURE);
  658. return (-1);
  659. }
  660. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  661. if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
  662. /* no read-ahead left? */
  663. BIO *bio;
  664. /*
  665. * In the case where we try to read application data,
  666. * but we trigger an SSL handshake, we return -1 with
  667. * the retry option set. Otherwise renegotiation may
  668. * cause nasty problems in the blocking world
  669. */
  670. s->rwstate = SSL_READING;
  671. bio = SSL_get_rbio(s);
  672. BIO_clear_retry_flags(bio);
  673. BIO_set_retry_read(bio);
  674. return (-1);
  675. }
  676. }
  677. }
  678. }
  679. /*
  680. * we either finished a handshake or ignored the request, now try
  681. * again to obtain the (application) data we were asked for
  682. */
  683. goto start;
  684. }
  685. if (s->rlayer.d->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
  686. int alert_level = s->rlayer.d->alert_fragment[0];
  687. int alert_descr = s->rlayer.d->alert_fragment[1];
  688. s->rlayer.d->alert_fragment_len = 0;
  689. if (s->msg_callback)
  690. s->msg_callback(0, s->version, SSL3_RT_ALERT,
  691. s->rlayer.d->alert_fragment, 2, s,
  692. s->msg_callback_arg);
  693. if (s->info_callback != NULL)
  694. cb = s->info_callback;
  695. else if (s->ctx->info_callback != NULL)
  696. cb = s->ctx->info_callback;
  697. if (cb != NULL) {
  698. j = (alert_level << 8) | alert_descr;
  699. cb(s, SSL_CB_READ_ALERT, j);
  700. }
  701. if (alert_level == SSL3_AL_WARNING) {
  702. s->s3->warn_alert = alert_descr;
  703. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  704. #ifndef OPENSSL_NO_SCTP
  705. /*
  706. * With SCTP and streams the socket may deliver app data
  707. * after a close_notify alert. We have to check this first so
  708. * that nothing gets discarded.
  709. */
  710. if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
  711. BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
  712. s->d1->shutdown_received = 1;
  713. s->rwstate = SSL_READING;
  714. BIO_clear_retry_flags(SSL_get_rbio(s));
  715. BIO_set_retry_read(SSL_get_rbio(s));
  716. return -1;
  717. }
  718. #endif
  719. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  720. return (0);
  721. }
  722. #if 0
  723. /* XXX: this is a possible improvement in the future */
  724. /* now check if it's a missing record */
  725. if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
  726. unsigned short seq;
  727. unsigned int frag_off;
  728. unsigned char *p = &(s->rlayer.d->alert_fragment[2]);
  729. n2s(p, seq);
  730. n2l3(p, frag_off);
  731. dtls1_retransmit_message(s,
  732. dtls1_get_queue_priority
  733. (frag->msg_header.seq, 0), frag_off,
  734. &found);
  735. if (!found && SSL_in_init(s)) {
  736. /*
  737. * fprintf( stderr,"in init = %d\n", SSL_in_init(s));
  738. */
  739. /*
  740. * requested a message not yet sent, send an alert
  741. * ourselves
  742. */
  743. ssl3_send_alert(s, SSL3_AL_WARNING,
  744. DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  745. }
  746. }
  747. #endif
  748. } else if (alert_level == SSL3_AL_FATAL) {
  749. char tmp[16];
  750. s->rwstate = SSL_NOTHING;
  751. s->s3->fatal_alert = alert_descr;
  752. SSLerr(SSL_F_DTLS1_READ_BYTES,
  753. SSL_AD_REASON_OFFSET + alert_descr);
  754. BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
  755. ERR_add_error_data(2, "SSL alert number ", tmp);
  756. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  757. SSL_CTX_remove_session(s->ctx, s->session);
  758. return (0);
  759. } else {
  760. al = SSL_AD_ILLEGAL_PARAMETER;
  761. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
  762. goto f_err;
  763. }
  764. goto start;
  765. }
  766. if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
  767. * shutdown */
  768. s->rwstate = SSL_NOTHING;
  769. SSL3_RECORD_set_length(rr, 0);
  770. return (0);
  771. }
  772. if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
  773. /*
  774. * We can't process a CCS now, because previous handshake messages
  775. * are still missing, so just drop it.
  776. */
  777. SSL3_RECORD_set_length(rr, 0);
  778. goto start;
  779. }
  780. /*
  781. * Unexpected handshake message (Client Hello, or protocol violation)
  782. */
  783. if ((s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
  784. !ossl_statem_get_in_handshake(s)) {
  785. struct hm_header_st msg_hdr;
  786. /* this may just be a stale retransmit */
  787. dtls1_get_message_header(rr->data, &msg_hdr);
  788. if (SSL3_RECORD_get_epoch(rr) != s->rlayer.d->r_epoch) {
  789. SSL3_RECORD_set_length(rr, 0);
  790. goto start;
  791. }
  792. /*
  793. * If we are server, we may have a repeated FINISHED of the client
  794. * here, then retransmit our CCS and FINISHED.
  795. */
  796. if (msg_hdr.type == SSL3_MT_FINISHED) {
  797. if (dtls1_check_timeout_num(s) < 0)
  798. return -1;
  799. dtls1_retransmit_buffered_messages(s);
  800. SSL3_RECORD_set_length(rr, 0);
  801. goto start;
  802. }
  803. if (SSL_is_init_finished(s) &&
  804. !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
  805. ossl_statem_set_in_init(s, 1);
  806. s->renegotiate = 1;
  807. s->new_session = 1;
  808. }
  809. i = s->handshake_func(s);
  810. if (i < 0)
  811. return (i);
  812. if (i == 0) {
  813. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
  814. return (-1);
  815. }
  816. if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
  817. if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
  818. /* no read-ahead left? */
  819. BIO *bio;
  820. /*
  821. * In the case where we try to read application data, but we
  822. * trigger an SSL handshake, we return -1 with the retry
  823. * option set. Otherwise renegotiation may cause nasty
  824. * problems in the blocking world
  825. */
  826. s->rwstate = SSL_READING;
  827. bio = SSL_get_rbio(s);
  828. BIO_clear_retry_flags(bio);
  829. BIO_set_retry_read(bio);
  830. return (-1);
  831. }
  832. }
  833. goto start;
  834. }
  835. switch (SSL3_RECORD_get_type(rr)) {
  836. default:
  837. /* TLS just ignores unknown message types */
  838. if (s->version == TLS1_VERSION) {
  839. SSL3_RECORD_set_length(rr, 0);
  840. goto start;
  841. }
  842. al = SSL_AD_UNEXPECTED_MESSAGE;
  843. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  844. goto f_err;
  845. case SSL3_RT_CHANGE_CIPHER_SPEC:
  846. case SSL3_RT_ALERT:
  847. case SSL3_RT_HANDSHAKE:
  848. /*
  849. * we already handled all of these, with the possible exception of
  850. * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
  851. * that should not happen when type != rr->type
  852. */
  853. al = SSL_AD_UNEXPECTED_MESSAGE;
  854. SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
  855. goto f_err;
  856. case SSL3_RT_APPLICATION_DATA:
  857. /*
  858. * At this point, we were expecting handshake data, but have
  859. * application data. If the library was running inside ssl3_read()
  860. * (i.e. in_read_app_data is set) and it makes sense to read
  861. * application data at this point (session renegotiation not yet
  862. * started), we will indulge it.
  863. */
  864. if (s->s3->in_read_app_data &&
  865. (s->s3->total_renegotiations != 0) &&
  866. ossl_statem_app_data_allowed(s)) {
  867. s->s3->in_read_app_data = 2;
  868. return (-1);
  869. } else {
  870. al = SSL_AD_UNEXPECTED_MESSAGE;
  871. SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
  872. goto f_err;
  873. }
  874. }
  875. /* not reached */
  876. f_err:
  877. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  878. return (-1);
  879. }
  880. /*
  881. * this only happens when a client hello is received and a handshake
  882. * is started.
  883. */
  884. static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
  885. int len, int peek)
  886. {
  887. if ((type == SSL3_RT_HANDSHAKE)
  888. && (s->rlayer.d->handshake_fragment_len > 0))
  889. /* (partially) satisfy request from storage */
  890. {
  891. unsigned char *src = s->rlayer.d->handshake_fragment;
  892. unsigned char *dst = buf;
  893. unsigned int k, n;
  894. /* peek == 0 */
  895. n = 0;
  896. while ((len > 0) && (s->rlayer.d->handshake_fragment_len > 0)) {
  897. *dst++ = *src++;
  898. len--;
  899. s->rlayer.d->handshake_fragment_len--;
  900. n++;
  901. }
  902. /* move any remaining fragment bytes: */
  903. for (k = 0; k < s->rlayer.d->handshake_fragment_len; k++)
  904. s->rlayer.d->handshake_fragment[k] = *src++;
  905. return n;
  906. }
  907. return 0;
  908. }
  909. /*
  910. * Call this to write data in records of type 'type' It will return <= 0 if
  911. * not all data has been sent or non-blocking IO.
  912. */
  913. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
  914. {
  915. int i;
  916. OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  917. s->rwstate = SSL_NOTHING;
  918. i = do_dtls1_write(s, type, buf, len, 0);
  919. return i;
  920. }
  921. int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
  922. unsigned int len, int create_empty_fragment)
  923. {
  924. unsigned char *p, *pseq;
  925. int i, mac_size, clear = 0;
  926. int prefix_len = 0;
  927. int eivlen;
  928. SSL3_RECORD *wr;
  929. SSL3_BUFFER *wb;
  930. SSL_SESSION *sess;
  931. wb = &s->rlayer.wbuf;
  932. /*
  933. * first check if there is a SSL3_BUFFER still being written out. This
  934. * will happen with non blocking IO
  935. */
  936. if (SSL3_BUFFER_get_left(wb) != 0) {
  937. OPENSSL_assert(0); /* XDTLS: want to see if we ever get here */
  938. return (ssl3_write_pending(s, type, buf, len));
  939. }
  940. /* If we have an alert to send, lets send it */
  941. if (s->s3->alert_dispatch) {
  942. i = s->method->ssl_dispatch_alert(s);
  943. if (i <= 0)
  944. return (i);
  945. /* if it went, fall through and send more stuff */
  946. }
  947. if (len == 0 && !create_empty_fragment)
  948. return 0;
  949. wr = &s->rlayer.wrec;
  950. sess = s->session;
  951. if ((sess == NULL) ||
  952. (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
  953. clear = 1;
  954. if (clear)
  955. mac_size = 0;
  956. else {
  957. mac_size = EVP_MD_CTX_size(s->write_hash);
  958. if (mac_size < 0)
  959. goto err;
  960. }
  961. p = SSL3_BUFFER_get_buf(wb) + prefix_len;
  962. /* write the header */
  963. *(p++) = type & 0xff;
  964. SSL3_RECORD_set_type(wr, type);
  965. /*
  966. * Special case: for hello verify request, client version 1.0 and we
  967. * haven't decided which version to use yet send back using version 1.0
  968. * header: otherwise some clients will ignore it.
  969. */
  970. if (s->method->version == DTLS_ANY_VERSION) {
  971. *(p++) = DTLS1_VERSION >> 8;
  972. *(p++) = DTLS1_VERSION & 0xff;
  973. } else {
  974. *(p++) = s->version >> 8;
  975. *(p++) = s->version & 0xff;
  976. }
  977. /* field where we are to write out packet epoch, seq num and len */
  978. pseq = p;
  979. p += 10;
  980. /* Explicit IV length, block ciphers appropriate version flag */
  981. if (s->enc_write_ctx) {
  982. int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
  983. if (mode == EVP_CIPH_CBC_MODE) {
  984. eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
  985. if (eivlen <= 1)
  986. eivlen = 0;
  987. }
  988. /* Need explicit part of IV for GCM mode */
  989. else if (mode == EVP_CIPH_GCM_MODE)
  990. eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
  991. else if (mode == EVP_CIPH_CCM_MODE)
  992. eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
  993. else
  994. eivlen = 0;
  995. } else
  996. eivlen = 0;
  997. /* lets setup the record stuff. */
  998. SSL3_RECORD_set_data(wr, p + eivlen); /* make room for IV in case of CBC */
  999. SSL3_RECORD_set_length(wr, (int)len);
  1000. SSL3_RECORD_set_input(wr, (unsigned char *)buf);
  1001. /*
  1002. * we now 'read' from wr->input, wr->length bytes into wr->data
  1003. */
  1004. /* first we compress */
  1005. if (s->compress != NULL) {
  1006. if (!ssl3_do_compress(s)) {
  1007. SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
  1008. goto err;
  1009. }
  1010. } else {
  1011. memcpy(SSL3_RECORD_get_data(wr), SSL3_RECORD_get_input(wr),
  1012. SSL3_RECORD_get_length(wr));
  1013. SSL3_RECORD_reset_input(wr);
  1014. }
  1015. /*
  1016. * we should still have the output to wr->data and the input from
  1017. * wr->input. Length should be wr->length. wr->data still points in the
  1018. * wb->buf
  1019. */
  1020. if (mac_size != 0) {
  1021. if (s->method->ssl3_enc->mac(s,
  1022. &(p[SSL3_RECORD_get_length(wr) + eivlen]), 1) < 0)
  1023. goto err;
  1024. SSL3_RECORD_add_length(wr, mac_size);
  1025. }
  1026. /* this is true regardless of mac size */
  1027. SSL3_RECORD_set_data(wr, p);
  1028. SSL3_RECORD_reset_input(wr);
  1029. if (eivlen)
  1030. SSL3_RECORD_add_length(wr, eivlen);
  1031. if (s->method->ssl3_enc->enc(s, 1) < 1)
  1032. goto err;
  1033. /* record length after mac and block padding */
  1034. /*
  1035. * if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
  1036. * SSL_in_init(s)))
  1037. */
  1038. /* there's only one epoch between handshake and app data */
  1039. s2n(s->rlayer.d->w_epoch, pseq);
  1040. /* XDTLS: ?? */
  1041. /*
  1042. * else s2n(s->d1->handshake_epoch, pseq);
  1043. */
  1044. memcpy(pseq, &(s->rlayer.write_sequence[2]), 6);
  1045. pseq += 6;
  1046. s2n(SSL3_RECORD_get_length(wr), pseq);
  1047. if (s->msg_callback)
  1048. s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
  1049. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  1050. /*
  1051. * we should now have wr->data pointing to the encrypted data, which is
  1052. * wr->length long
  1053. */
  1054. SSL3_RECORD_set_type(wr, type); /* not needed but helps for debugging */
  1055. SSL3_RECORD_add_length(wr, DTLS1_RT_HEADER_LENGTH);
  1056. ssl3_record_sequence_update(&(s->rlayer.write_sequence[0]));
  1057. if (create_empty_fragment) {
  1058. /*
  1059. * we are in a recursive call; just return the length, don't write
  1060. * out anything here
  1061. */
  1062. return wr->length;
  1063. }
  1064. /* now let's set up wb */
  1065. SSL3_BUFFER_set_left(wb, prefix_len + SSL3_RECORD_get_length(wr));
  1066. SSL3_BUFFER_set_offset(wb, 0);
  1067. /*
  1068. * memorize arguments so that ssl3_write_pending can detect bad write
  1069. * retries later
  1070. */
  1071. s->rlayer.wpend_tot = len;
  1072. s->rlayer.wpend_buf = buf;
  1073. s->rlayer.wpend_type = type;
  1074. s->rlayer.wpend_ret = len;
  1075. /* we now just need to write the buffer */
  1076. return ssl3_write_pending(s, type, buf, len);
  1077. err:
  1078. return -1;
  1079. }
  1080. DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  1081. unsigned int *is_next_epoch)
  1082. {
  1083. *is_next_epoch = 0;
  1084. /* In current epoch, accept HM, CCS, DATA, & ALERT */
  1085. if (rr->epoch == s->rlayer.d->r_epoch)
  1086. return &s->rlayer.d->bitmap;
  1087. /* Only HM and ALERT messages can be from the next epoch */
  1088. else if (rr->epoch == (unsigned long)(s->rlayer.d->r_epoch + 1) &&
  1089. (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
  1090. *is_next_epoch = 1;
  1091. return &s->rlayer.d->next_bitmap;
  1092. }
  1093. return NULL;
  1094. }
  1095. void dtls1_reset_seq_numbers(SSL *s, int rw)
  1096. {
  1097. unsigned char *seq;
  1098. unsigned int seq_bytes = sizeof(s->rlayer.read_sequence);
  1099. if (rw & SSL3_CC_READ) {
  1100. seq = s->rlayer.read_sequence;
  1101. s->rlayer.d->r_epoch++;
  1102. memcpy(&s->rlayer.d->bitmap, &s->rlayer.d->next_bitmap,
  1103. sizeof(s->rlayer.d->bitmap));
  1104. memset(&s->rlayer.d->next_bitmap, 0,
  1105. sizeof(s->rlayer.d->next_bitmap));
  1106. } else {
  1107. seq = s->rlayer.write_sequence;
  1108. memcpy(s->rlayer.d->last_write_sequence, seq,
  1109. sizeof(s->rlayer.write_sequence));
  1110. s->rlayer.d->w_epoch++;
  1111. }
  1112. memset(seq, 0, seq_bytes);
  1113. }