Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

1322 строки
40 KiB

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