Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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