Você não pode selecionar mais de 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.
 
 
 
 
 
 

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