25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1134 lines
34 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 dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
  174. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
  175. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  176. unsigned int *is_next_epoch);
  177. static int dtls1_buffer_record(SSL *s, record_pqueue *q,
  178. uint8_t *priority);
  179. static int dtls1_process_record(SSL *s);
  180. static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
  181. unsigned int len);
  182. /* copy buffered record into SSL structure */
  183. static int dtls1_copy_record(SSL *s, pitem *item) {
  184. DTLS1_RECORD_DATA *rdata;
  185. rdata = (DTLS1_RECORD_DATA *)item->data;
  186. if (s->s3->rbuf.buf != NULL) {
  187. OPENSSL_free(s->s3->rbuf.buf);
  188. }
  189. s->packet = rdata->packet;
  190. s->packet_length = rdata->packet_length;
  191. memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
  192. memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
  193. /* Set proper sequence number for mac calculation */
  194. memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
  195. return 1;
  196. }
  197. static int dtls1_buffer_record(SSL *s, record_pqueue *queue,
  198. uint8_t *priority) {
  199. DTLS1_RECORD_DATA *rdata;
  200. pitem *item;
  201. /* Limit the size of the queue to prevent DOS attacks */
  202. if (pqueue_size(queue->q) >= 100) {
  203. return 0;
  204. }
  205. rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
  206. item = pitem_new(priority, rdata);
  207. if (rdata == NULL || item == NULL) {
  208. if (rdata != NULL) {
  209. OPENSSL_free(rdata);
  210. }
  211. if (item != NULL) {
  212. pitem_free(item);
  213. }
  214. OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
  215. return -1;
  216. }
  217. rdata->packet = s->packet;
  218. rdata->packet_length = s->packet_length;
  219. memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
  220. memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
  221. item->data = rdata;
  222. s->packet = NULL;
  223. s->packet_length = 0;
  224. memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
  225. memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
  226. if (!ssl3_setup_buffers(s)) {
  227. goto internal_error;
  228. }
  229. /* insert should not fail, since duplicates are dropped */
  230. if (pqueue_insert(queue->q, item) == NULL) {
  231. goto internal_error;
  232. }
  233. return 1;
  234. internal_error:
  235. OPENSSL_PUT_ERROR(SSL, dtls1_buffer_record, ERR_R_INTERNAL_ERROR);
  236. if (rdata->rbuf.buf != NULL) {
  237. OPENSSL_free(rdata->rbuf.buf);
  238. }
  239. OPENSSL_free(rdata);
  240. pitem_free(item);
  241. return -1;
  242. }
  243. static int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue) {
  244. pitem *item;
  245. item = pqueue_pop(queue->q);
  246. if (item) {
  247. dtls1_copy_record(s, item);
  248. OPENSSL_free(item->data);
  249. pitem_free(item);
  250. return 1;
  251. }
  252. return 0;
  253. }
  254. /* retrieve a buffered record that belongs to the new epoch, i.e., not
  255. * processed yet */
  256. #define dtls1_get_unprocessed_record(s) \
  257. dtls1_retrieve_buffered_record((s), &((s)->d1->unprocessed_rcds))
  258. /* retrieve a buffered record that belongs to the current epoch, i.e.,
  259. * processed */
  260. #define dtls1_get_processed_record(s) \
  261. dtls1_retrieve_buffered_record((s), &((s)->d1->processed_rcds))
  262. static int dtls1_process_buffered_records(SSL *s) {
  263. pitem *item;
  264. item = pqueue_peek(s->d1->unprocessed_rcds.q);
  265. if (item) {
  266. /* Check if epoch is current. */
  267. if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch) {
  268. return 1; /* Nothing to do. */
  269. }
  270. /* Process all the records. */
  271. while (pqueue_peek(s->d1->unprocessed_rcds.q)) {
  272. dtls1_get_unprocessed_record(s);
  273. if (!dtls1_process_record(s)) {
  274. return 0;
  275. }
  276. if (dtls1_buffer_record(s, &(s->d1->processed_rcds),
  277. s->s3->rrec.seq_num) < 0) {
  278. return -1;
  279. }
  280. }
  281. }
  282. /* sync epoch numbers once all the unprocessed records have been processed */
  283. s->d1->processed_rcds.epoch = s->d1->r_epoch;
  284. s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
  285. return 1;
  286. }
  287. static int dtls1_process_record(SSL *s) {
  288. int al;
  289. SSL3_RECORD *rr;
  290. rr = &(s->s3->rrec);
  291. /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length, and
  292. * we have that many bytes in s->packet. */
  293. rr->input = &(s->packet[DTLS1_RT_HEADER_LENGTH]);
  294. /* ok, we can now read from 's->packet' data into 'rr' rr->input points at
  295. * rr->length bytes, which need to be copied into rr->data by either the
  296. * decryption or by the decompression When the data is 'copied' into the
  297. * rr->data buffer, rr->input will be pointed at the new buffer */
  298. /* We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length bytes
  299. * of encrypted compressed stuff. */
  300. /* check is not needed I believe */
  301. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  302. al = SSL_AD_RECORD_OVERFLOW;
  303. OPENSSL_PUT_ERROR(SSL, dtls1_process_record,
  304. SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
  305. goto f_err;
  306. }
  307. /* decrypt in place in 'rr->input' */
  308. rr->data = rr->input;
  309. if (!s->enc_method->enc(s, 0)) {
  310. /* Bad packets are silently dropped in DTLS. Clear the error queue of any
  311. * errors decryption may have added. */
  312. ERR_clear_error();
  313. rr->length = 0;
  314. s->packet_length = 0;
  315. goto err;
  316. }
  317. if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
  318. al = SSL_AD_RECORD_OVERFLOW;
  319. OPENSSL_PUT_ERROR(SSL, dtls1_process_record, SSL_R_DATA_LENGTH_TOO_LONG);
  320. goto f_err;
  321. }
  322. rr->off = 0;
  323. /* So at this point the following is true
  324. * ssl->s3->rrec.type is the type of record
  325. * ssl->s3->rrec.length == number of bytes in record
  326. * ssl->s3->rrec.off == offset to first valid byte
  327. * ssl->s3->rrec.data == where to take bytes from, increment
  328. * after use :-). */
  329. /* we have pulled in a full packet so zero things */
  330. s->packet_length = 0;
  331. return 1;
  332. f_err:
  333. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  334. err:
  335. return 0;
  336. }
  337. /* Call this to get a new input record.
  338. * It will return <= 0 if more data is needed, normally due to an error
  339. * or non-blocking IO.
  340. * When it finishes, one packet has been decoded and can be found in
  341. * ssl->s3->rrec.type - is the type of record
  342. * ssl->s3->rrec.data, - data
  343. * ssl->s3->rrec.length, - number of bytes
  344. *
  345. * used only by dtls1_read_bytes */
  346. int dtls1_get_record(SSL *s) {
  347. int ssl_major, ssl_minor;
  348. int i, n;
  349. SSL3_RECORD *rr;
  350. unsigned char *p = NULL;
  351. unsigned short version;
  352. DTLS1_BITMAP *bitmap;
  353. unsigned int is_next_epoch;
  354. rr = &(s->s3->rrec);
  355. /* The epoch may have changed. If so, process all the pending records. This
  356. * is a non-blocking operation. */
  357. if (dtls1_process_buffered_records(s) < 0) {
  358. return -1;
  359. }
  360. /* If we're renegotiating, then there may be buffered records. */
  361. if (dtls1_get_processed_record(s)) {
  362. return 1;
  363. }
  364. /* get something from the wire */
  365. again:
  366. /* check if we have the header */
  367. if ((s->rstate != SSL_ST_READ_BODY) ||
  368. (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
  369. n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
  370. /* read timeout is handled by dtls1_read_bytes */
  371. if (n <= 0) {
  372. return n; /* error or non-blocking */
  373. }
  374. /* this packet contained a partial record, dump it */
  375. if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {
  376. s->packet_length = 0;
  377. goto again;
  378. }
  379. s->rstate = SSL_ST_READ_BODY;
  380. p = s->packet;
  381. if (s->msg_callback) {
  382. s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH, s,
  383. s->msg_callback_arg);
  384. }
  385. /* Pull apart the header into the DTLS1_RECORD */
  386. rr->type = *(p++);
  387. ssl_major = *(p++);
  388. ssl_minor = *(p++);
  389. version = (ssl_major << 8) | ssl_minor;
  390. /* sequence number is 64 bits, with top 2 bytes = epoch */
  391. n2s(p, rr->epoch);
  392. memcpy(&(s->s3->read_sequence[2]), p, 6);
  393. p += 6;
  394. n2s(p, rr->length);
  395. /* Lets check version */
  396. if (s->s3->have_version) {
  397. if (version != s->version) {
  398. /* The record's version doesn't match, so silently drop it.
  399. *
  400. * TODO(davidben): This doesn't work. The DTLS record layer is not
  401. * packet-based, so the remainder of the packet isn't dropped and we
  402. * get a framing error. It's also unclear what it means to silently
  403. * drop a record in a packet containing two records. */
  404. rr->length = 0;
  405. s->packet_length = 0;
  406. goto again;
  407. }
  408. }
  409. if ((version & 0xff00) != (s->version & 0xff00)) {
  410. /* wrong version, silently discard record */
  411. rr->length = 0;
  412. s->packet_length = 0;
  413. goto again;
  414. }
  415. if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
  416. /* record too long, silently discard it */
  417. rr->length = 0;
  418. s->packet_length = 0;
  419. goto again;
  420. }
  421. /* now s->rstate == SSL_ST_READ_BODY */
  422. }
  423. /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
  424. if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
  425. /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
  426. i = rr->length;
  427. n = ssl3_read_n(s, i, i, 1);
  428. if (n <= 0) {
  429. return n; /* error or non-blocking io */
  430. }
  431. /* this packet contained a partial record, dump it */
  432. if (n != i) {
  433. rr->length = 0;
  434. s->packet_length = 0;
  435. goto again;
  436. }
  437. /* now n == rr->length,
  438. * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
  439. }
  440. s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
  441. /* match epochs. NULL means the packet is dropped on the floor */
  442. bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
  443. if (bitmap == NULL) {
  444. rr->length = 0;
  445. s->packet_length = 0; /* dump this record */
  446. goto again; /* get another record */
  447. }
  448. /* Check whether this is a repeat, or aged record. */
  449. if (!dtls1_record_replay_check(s, bitmap)) {
  450. rr->length = 0;
  451. s->packet_length = 0; /* dump this record */
  452. goto again; /* get another record */
  453. }
  454. /* just read a 0 length packet */
  455. if (rr->length == 0) {
  456. goto again;
  457. }
  458. /* If this record is from the next epoch (either HM or ALERT),
  459. * and a handshake is currently in progress, buffer it since it
  460. * cannot be processed at this time.
  461. */
  462. if (is_next_epoch) {
  463. if (SSL_in_init(s) || s->in_handshake) {
  464. if (dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0) {
  465. return -1;
  466. }
  467. dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
  468. }
  469. rr->length = 0;
  470. s->packet_length = 0;
  471. goto again;
  472. }
  473. if (!dtls1_process_record(s)) {
  474. rr->length = 0;
  475. s->packet_length = 0; /* dump this record */
  476. goto again; /* get another record */
  477. }
  478. dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
  479. return 1;
  480. }
  481. /* Return up to 'len' payload bytes received in 'type' records.
  482. * 'type' is one of the following:
  483. *
  484. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  485. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  486. * - 0 (during a shutdown, no data has to be returned)
  487. *
  488. * If we don't have stored data to work from, read a SSL/TLS record first
  489. * (possibly multiple records if we still don't have anything to return).
  490. *
  491. * This function must handle any surprises the peer may have for us, such as
  492. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  493. * a surprise, but handled as if it were), or renegotiation requests.
  494. * Also if record payloads contain fragments too small to process, we store
  495. * them until there is enough for the respective protocol (the record protocol
  496. * may use arbitrary fragmentation and even interleaving):
  497. * Change cipher spec protocol
  498. * just 1 byte needed, no need for keeping anything stored
  499. * Alert protocol
  500. * 2 bytes needed (AlertLevel, AlertDescription)
  501. * Handshake protocol
  502. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  503. * to detect unexpected Client Hello and Hello Request messages
  504. * here, anything else is handled by higher layers
  505. * Application data protocol
  506. * none of our business
  507. */
  508. int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek) {
  509. int al, i, ret;
  510. unsigned int n;
  511. SSL3_RECORD *rr;
  512. void (*cb)(const SSL *ssl, int type2, int val) = NULL;
  513. /* XXX: check what the second '&& type' is about */
  514. if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
  515. (type != SSL3_RT_HANDSHAKE) && type) ||
  516. (peek && (type != SSL3_RT_APPLICATION_DATA))) {
  517. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
  518. return -1;
  519. }
  520. if (!s->in_handshake && SSL_in_init(s)) {
  521. /* type == SSL3_RT_APPLICATION_DATA */
  522. i = s->handshake_func(s);
  523. if (i < 0) {
  524. return i;
  525. }
  526. if (i == 0) {
  527. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
  528. return -1;
  529. }
  530. }
  531. if (s->s3->rbuf.buf == NULL && !ssl3_setup_buffers(s)) {
  532. /* TODO(davidben): Is this redundant with the calls in the handshake? */
  533. return -1;
  534. }
  535. start:
  536. s->rwstate = SSL_NOTHING;
  537. /* s->s3->rrec.type - is the type of record
  538. * s->s3->rrec.data - data
  539. * s->s3->rrec.off - offset into 'data' for next read
  540. * s->s3->rrec.length - number of bytes. */
  541. rr = &s->s3->rrec;
  542. /* We are not handshaking and have no data yet,
  543. * so process data buffered during the last handshake
  544. * in advance, if any.
  545. */
  546. if (s->state == SSL_ST_OK && rr->length == 0) {
  547. pitem *item;
  548. item = pqueue_pop(s->d1->buffered_app_data.q);
  549. if (item) {
  550. dtls1_copy_record(s, item);
  551. OPENSSL_free(item->data);
  552. pitem_free(item);
  553. }
  554. }
  555. /* Check for timeout */
  556. if (dtls1_handle_timeout(s) > 0) {
  557. goto start;
  558. }
  559. /* get new packet if necessary */
  560. if (rr->length == 0 || s->rstate == SSL_ST_READ_BODY) {
  561. ret = dtls1_get_record(s);
  562. if (ret <= 0) {
  563. ret = dtls1_read_failed(s, ret);
  564. /* anything other than a timeout is an error */
  565. if (ret <= 0) {
  566. return ret;
  567. } else {
  568. goto start;
  569. }
  570. }
  571. }
  572. /* we now have a packet which can be read and processed */
  573. /* |change_cipher_spec is set when we receive a ChangeCipherSpec and reset by
  574. * ssl3_get_finished. */
  575. if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE) {
  576. /* We now have application data between CCS and Finished. Most likely the
  577. * packets were reordered on their way, so buffer the application data for
  578. * later processing rather than dropping the connection. */
  579. if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) < 0) {
  580. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, ERR_R_INTERNAL_ERROR);
  581. return -1;
  582. }
  583. rr->length = 0;
  584. goto start;
  585. }
  586. /* If the other end has shut down, throw anything we read away (even in
  587. * 'peek' mode) */
  588. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  589. rr->length = 0;
  590. s->rwstate = SSL_NOTHING;
  591. return 0;
  592. }
  593. if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  594. /* make sure that we are not getting application data when we
  595. * are doing a handshake for the first time */
  596. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  597. (s->aead_read_ctx == NULL)) {
  598. /* TODO(davidben): Is this check redundant with the handshake_func
  599. * check? */
  600. al = SSL_AD_UNEXPECTED_MESSAGE;
  601. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  602. goto f_err;
  603. }
  604. if (len <= 0) {
  605. return len;
  606. }
  607. if ((unsigned int)len > rr->length) {
  608. n = rr->length;
  609. } else {
  610. n = (unsigned int)len;
  611. }
  612. memcpy(buf, &(rr->data[rr->off]), n);
  613. if (!peek) {
  614. rr->length -= n;
  615. rr->off += n;
  616. if (rr->length == 0) {
  617. s->rstate = SSL_ST_READ_HEADER;
  618. rr->off = 0;
  619. }
  620. }
  621. return n;
  622. }
  623. /* If we get here, then type != rr->type. */
  624. /* If an alert record, process one alert out of the record. Note that we allow
  625. * a single record to contain multiple alerts. */
  626. if (rr->type == SSL3_RT_ALERT) {
  627. /* Alerts may not be fragmented. */
  628. if (rr->length < 2) {
  629. al = SSL_AD_DECODE_ERROR;
  630. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_ALERT);
  631. goto f_err;
  632. }
  633. if (s->msg_callback) {
  634. s->msg_callback(0, s->version, SSL3_RT_ALERT, &rr->data[rr->off], 2, s,
  635. s->msg_callback_arg);
  636. }
  637. const uint8_t alert_level = rr->data[rr->off++];
  638. const uint8_t alert_descr = rr->data[rr->off++];
  639. rr->length -= 2;
  640. if (s->info_callback != NULL) {
  641. cb = s->info_callback;
  642. } else if (s->ctx->info_callback != NULL) {
  643. cb = s->ctx->info_callback;
  644. }
  645. if (cb != NULL) {
  646. uint16_t alert = (alert_level << 8) | alert_descr;
  647. cb(s, SSL_CB_READ_ALERT, alert);
  648. }
  649. if (alert_level == SSL3_AL_WARNING) {
  650. s->s3->warn_alert = alert_descr;
  651. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  652. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  653. return 0;
  654. }
  655. } else if (alert_level == SSL3_AL_FATAL) {
  656. char tmp[16];
  657. s->rwstate = SSL_NOTHING;
  658. s->s3->fatal_alert = alert_descr;
  659. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes,
  660. SSL_AD_REASON_OFFSET + alert_descr);
  661. BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
  662. ERR_add_error_data(2, "SSL alert number ", tmp);
  663. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  664. SSL_CTX_remove_session(s->ctx, s->session);
  665. return 0;
  666. } else {
  667. al = SSL_AD_ILLEGAL_PARAMETER;
  668. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  669. goto f_err;
  670. }
  671. goto start;
  672. }
  673. if (s->shutdown & SSL_SENT_SHUTDOWN) {
  674. /* but we have not received a shutdown */
  675. s->rwstate = SSL_NOTHING;
  676. rr->length = 0;
  677. return 0;
  678. }
  679. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  680. /* 'Change Cipher Spec' is just a single byte, so we know exactly what the
  681. * record payload has to look like */
  682. if (rr->length != 1 || rr->off != 0 || rr->data[0] != SSL3_MT_CCS) {
  683. al = SSL_AD_ILLEGAL_PARAMETER;
  684. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  685. goto f_err;
  686. }
  687. rr->length = 0;
  688. if (s->msg_callback) {
  689. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
  690. s->msg_callback_arg);
  691. }
  692. /* We can't process a CCS now, because previous handshake
  693. * messages are still missing, so just drop it.
  694. */
  695. if (!s->d1->change_cipher_spec_ok) {
  696. goto start;
  697. }
  698. s->d1->change_cipher_spec_ok = 0;
  699. s->s3->change_cipher_spec = 1;
  700. if (!ssl3_do_change_cipher_spec(s)) {
  701. goto err;
  702. }
  703. /* do this whenever CCS is processed */
  704. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  705. goto start;
  706. }
  707. /* Unexpected handshake message. It may be a retransmitted Finished (the only
  708. * post-CCS message). Otherwise, it's a pre-CCS handshake message from an
  709. * unsupported renegotiation attempt. */
  710. if (rr->type == SSL3_RT_HANDSHAKE && !s->in_handshake) {
  711. if (rr->length < DTLS1_HM_HEADER_LENGTH) {
  712. al = SSL_AD_DECODE_ERROR;
  713. OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_HANDSHAKE_RECORD);
  714. goto f_err;
  715. }
  716. struct hm_header_st msg_hdr;
  717. dtls1_get_message_header(&rr->data[rr->off], &msg_hdr);
  718. /* Ignore a stray Finished from the previous handshake. */
  719. if (msg_hdr.type == SSL3_MT_FINISHED) {
  720. if (msg_hdr.frag_off == 0) {
  721. /* Retransmit our last flight of messages. If the peer sends the second
  722. * Finished, they may not have received ours. Only do this for the
  723. * first fragment, in case the Finished was fragmented. */
  724. if (dtls1_check_timeout_num(s) < 0) {
  725. return -1;
  726. }
  727. dtls1_retransmit_buffered_messages(s);
  728. }
  729. rr->length = 0;
  730. goto start;
  731. }
  732. }
  733. /* We already handled these. */
  734. assert(rr->type != SSL3_RT_CHANGE_CIPHER_SPEC && rr->type != SSL3_RT_ALERT);
  735. al = SSL_AD_UNEXPECTED_MESSAGE;
  736. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
  737. f_err:
  738. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  739. err:
  740. return -1;
  741. }
  742. int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len) {
  743. int i;
  744. if (SSL_in_init(s) && !s->in_handshake) {
  745. i = s->handshake_func(s);
  746. if (i < 0) {
  747. return i;
  748. }
  749. if (i == 0) {
  750. OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes,
  751. SSL_R_SSL_HANDSHAKE_FAILURE);
  752. return -1;
  753. }
  754. }
  755. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  756. OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes,
  757. SSL_R_DTLS_MESSAGE_TOO_BIG);
  758. return -1;
  759. }
  760. i = dtls1_write_bytes(s, type, buf_, len);
  761. return i;
  762. }
  763. /* Call this to write data in records of type 'type' It will return <= 0 if not
  764. * all data has been sent or non-blocking IO. */
  765. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len) {
  766. int i;
  767. assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  768. s->rwstate = SSL_NOTHING;
  769. i = do_dtls1_write(s, type, buf, len);
  770. return i;
  771. }
  772. static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
  773. unsigned int len) {
  774. uint8_t *p, *pseq;
  775. int i;
  776. int prefix_len = 0;
  777. int eivlen = 0;
  778. SSL3_RECORD *wr;
  779. SSL3_BUFFER *wb;
  780. /* first check if there is a SSL3_BUFFER still being written
  781. * out. This will happen with non blocking IO */
  782. if (s->s3->wbuf.left != 0) {
  783. assert(0); /* XDTLS: want to see if we ever get here */
  784. return ssl3_write_pending(s, type, buf, len);
  785. }
  786. /* If we have an alert to send, lets send it */
  787. if (s->s3->alert_dispatch) {
  788. i = s->method->ssl_dispatch_alert(s);
  789. if (i <= 0) {
  790. return i;
  791. }
  792. /* if it went, fall through and send more stuff */
  793. }
  794. if (len == 0) {
  795. return 0;
  796. }
  797. wr = &(s->s3->wrec);
  798. wb = &(s->s3->wbuf);
  799. p = wb->buf + prefix_len;
  800. /* write the header */
  801. *(p++) = type & 0xff;
  802. wr->type = type;
  803. /* Special case: for hello verify request, client version 1.0 and
  804. * we haven't decided which version to use yet send back using
  805. * version 1.0 header: otherwise some clients will ignore it.
  806. */
  807. if (!s->s3->have_version) {
  808. *(p++) = DTLS1_VERSION >> 8;
  809. *(p++) = DTLS1_VERSION & 0xff;
  810. } else {
  811. *(p++) = s->version >> 8;
  812. *(p++) = s->version & 0xff;
  813. }
  814. /* field where we are to write out packet epoch, seq num and len */
  815. pseq = p;
  816. p += 10;
  817. /* Leave room for the variable nonce for AEADs which specify it explicitly. */
  818. if (s->aead_write_ctx != NULL &&
  819. s->aead_write_ctx->variable_nonce_included_in_record) {
  820. eivlen = s->aead_write_ctx->variable_nonce_len;
  821. }
  822. /* lets setup the record stuff. */
  823. wr->data = p + eivlen; /* make room for IV in case of CBC */
  824. wr->length = (int)len;
  825. wr->input = (unsigned char *)buf;
  826. /* we now 'read' from wr->input, wr->length bytes into wr->data */
  827. memcpy(wr->data, wr->input, wr->length);
  828. wr->input = wr->data;
  829. /* this is true regardless of mac size */
  830. wr->input = p;
  831. wr->data = p;
  832. wr->length += eivlen;
  833. if (!s->enc_method->enc(s, 1)) {
  834. goto err;
  835. }
  836. /* there's only one epoch between handshake and app data */
  837. s2n(s->d1->w_epoch, pseq);
  838. memcpy(pseq, &(s->s3->write_sequence[2]), 6);
  839. pseq += 6;
  840. s2n(wr->length, pseq);
  841. if (s->msg_callback) {
  842. s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
  843. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  844. }
  845. /* we should now have wr->data pointing to the encrypted data, which is
  846. * wr->length long */
  847. wr->type = type; /* not needed but helps for debugging */
  848. wr->length += DTLS1_RT_HEADER_LENGTH;
  849. ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
  850. /* now let's set up wb */
  851. wb->left = prefix_len + wr->length;
  852. wb->offset = 0;
  853. /* memorize arguments so that ssl3_write_pending can detect bad write retries
  854. * later */
  855. s->s3->wpend_tot = len;
  856. s->s3->wpend_buf = buf;
  857. s->s3->wpend_type = type;
  858. s->s3->wpend_ret = len;
  859. /* we now just need to write the buffer */
  860. return ssl3_write_pending(s, type, buf, len);
  861. err:
  862. return -1;
  863. }
  864. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap) {
  865. int cmp;
  866. unsigned int shift;
  867. const uint8_t *seq = s->s3->read_sequence;
  868. cmp = satsub64be(seq, bitmap->max_seq_num);
  869. if (cmp > 0) {
  870. memcpy(s->s3->rrec.seq_num, seq, 8);
  871. return 1; /* this record in new */
  872. }
  873. shift = -cmp;
  874. if (shift >= sizeof(bitmap->map) * 8) {
  875. return 0; /* stale, outside the window */
  876. } else if (bitmap->map & (((uint64_t)1) << shift)) {
  877. return 0; /* record previously received */
  878. }
  879. memcpy(s->s3->rrec.seq_num, seq, 8);
  880. return 1;
  881. }
  882. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap) {
  883. int cmp;
  884. unsigned int shift;
  885. const uint8_t *seq = s->s3->read_sequence;
  886. cmp = satsub64be(seq, bitmap->max_seq_num);
  887. if (cmp > 0) {
  888. shift = cmp;
  889. if (shift < sizeof(bitmap->map) * 8) {
  890. bitmap->map <<= shift, bitmap->map |= 1UL;
  891. } else {
  892. bitmap->map = 1UL;
  893. }
  894. memcpy(bitmap->max_seq_num, seq, 8);
  895. } else {
  896. shift = -cmp;
  897. if (shift < sizeof(bitmap->map) * 8) {
  898. bitmap->map |= ((uint64_t)1) << shift;
  899. }
  900. }
  901. }
  902. int dtls1_dispatch_alert(SSL *s) {
  903. int i, j;
  904. void (*cb)(const SSL *ssl, int type, int val) = NULL;
  905. uint8_t buf[DTLS1_AL_HEADER_LENGTH];
  906. uint8_t *ptr = &buf[0];
  907. s->s3->alert_dispatch = 0;
  908. memset(buf, 0x00, sizeof(buf));
  909. *ptr++ = s->s3->send_alert[0];
  910. *ptr++ = s->s3->send_alert[1];
  911. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf));
  912. if (i <= 0) {
  913. s->s3->alert_dispatch = 1;
  914. } else {
  915. if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
  916. (void)BIO_flush(s->wbio);
  917. }
  918. if (s->msg_callback) {
  919. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
  920. s->msg_callback_arg);
  921. }
  922. if (s->info_callback != NULL) {
  923. cb = s->info_callback;
  924. } else if (s->ctx->info_callback != NULL) {
  925. cb = s->ctx->info_callback;
  926. }
  927. if (cb != NULL) {
  928. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  929. cb(s, SSL_CB_WRITE_ALERT, j);
  930. }
  931. }
  932. return i;
  933. }
  934. static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
  935. unsigned int *is_next_epoch) {
  936. *is_next_epoch = 0;
  937. /* In current epoch, accept HM, CCS, DATA, & ALERT */
  938. if (rr->epoch == s->d1->r_epoch) {
  939. return &s->d1->bitmap;
  940. } else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
  941. (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
  942. /* Only HM and ALERT messages can be from the next epoch */
  943. *is_next_epoch = 1;
  944. return &s->d1->next_bitmap;
  945. }
  946. return NULL;
  947. }
  948. void dtls1_reset_seq_numbers(SSL *s, int rw) {
  949. uint8_t *seq;
  950. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  951. if (rw & SSL3_CC_READ) {
  952. seq = s->s3->read_sequence;
  953. s->d1->r_epoch++;
  954. memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
  955. memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
  956. } else {
  957. seq = s->s3->write_sequence;
  958. memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
  959. s->d1->w_epoch++;
  960. }
  961. memset(seq, 0x00, seq_bytes);
  962. }