Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

926 lignes
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, s->s3->rbuf.len, 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, 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. if (s->s3->rbuf.buf == NULL && !ssl3_setup_buffers(s)) {
  398. /* TODO(davidben): Is this redundant with the calls in the handshake? */
  399. return -1;
  400. }
  401. start:
  402. s->rwstate = SSL_NOTHING;
  403. /* s->s3->rrec.type - is the type of record
  404. * s->s3->rrec.data - data
  405. * s->s3->rrec.off - offset into 'data' for next read
  406. * s->s3->rrec.length - number of bytes. */
  407. rr = &s->s3->rrec;
  408. /* Check for timeout */
  409. if (dtls1_handle_timeout(s) > 0) {
  410. goto start;
  411. }
  412. /* get new packet if necessary */
  413. if (rr->length == 0 || s->rstate == SSL_ST_READ_BODY) {
  414. ret = dtls1_get_record(s);
  415. if (ret <= 0) {
  416. ret = dtls1_read_failed(s, ret);
  417. /* anything other than a timeout is an error */
  418. if (ret <= 0) {
  419. return ret;
  420. } else {
  421. goto start;
  422. }
  423. }
  424. }
  425. /* we now have a packet which can be read and processed */
  426. /* |change_cipher_spec is set when we receive a ChangeCipherSpec and reset by
  427. * ssl3_get_finished. */
  428. if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE &&
  429. rr->type != SSL3_RT_ALERT) {
  430. /* We now have an unexpected record between CCS and Finished. Most likely
  431. * the packets were reordered on their way. DTLS is unreliable, so drop the
  432. * packet and expect the peer to retransmit. */
  433. rr->length = 0;
  434. goto start;
  435. }
  436. /* If the other end has shut down, throw anything we read away (even in
  437. * 'peek' mode) */
  438. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  439. rr->length = 0;
  440. s->rwstate = SSL_NOTHING;
  441. return 0;
  442. }
  443. if (type == rr->type) { /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  444. /* make sure that we are not getting application data when we
  445. * are doing a handshake for the first time */
  446. if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
  447. (s->aead_read_ctx == NULL)) {
  448. /* TODO(davidben): Is this check redundant with the handshake_func
  449. * check? */
  450. al = SSL_AD_UNEXPECTED_MESSAGE;
  451. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
  452. goto f_err;
  453. }
  454. if (len <= 0) {
  455. return len;
  456. }
  457. if ((unsigned int)len > rr->length) {
  458. n = rr->length;
  459. } else {
  460. n = (unsigned int)len;
  461. }
  462. memcpy(buf, &(rr->data[rr->off]), n);
  463. if (!peek) {
  464. rr->length -= n;
  465. rr->off += n;
  466. if (rr->length == 0) {
  467. s->rstate = SSL_ST_READ_HEADER;
  468. rr->off = 0;
  469. }
  470. }
  471. return n;
  472. }
  473. /* If we get here, then type != rr->type. */
  474. /* If an alert record, process one alert out of the record. Note that we allow
  475. * a single record to contain multiple alerts. */
  476. if (rr->type == SSL3_RT_ALERT) {
  477. /* Alerts may not be fragmented. */
  478. if (rr->length < 2) {
  479. al = SSL_AD_DECODE_ERROR;
  480. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_ALERT);
  481. goto f_err;
  482. }
  483. if (s->msg_callback) {
  484. s->msg_callback(0, s->version, SSL3_RT_ALERT, &rr->data[rr->off], 2, s,
  485. s->msg_callback_arg);
  486. }
  487. const uint8_t alert_level = rr->data[rr->off++];
  488. const uint8_t alert_descr = rr->data[rr->off++];
  489. rr->length -= 2;
  490. if (s->info_callback != NULL) {
  491. cb = s->info_callback;
  492. } else if (s->ctx->info_callback != NULL) {
  493. cb = s->ctx->info_callback;
  494. }
  495. if (cb != NULL) {
  496. uint16_t alert = (alert_level << 8) | alert_descr;
  497. cb(s, SSL_CB_READ_ALERT, alert);
  498. }
  499. if (alert_level == SSL3_AL_WARNING) {
  500. s->s3->warn_alert = alert_descr;
  501. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  502. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  503. return 0;
  504. }
  505. } else if (alert_level == SSL3_AL_FATAL) {
  506. char tmp[16];
  507. s->rwstate = SSL_NOTHING;
  508. s->s3->fatal_alert = alert_descr;
  509. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes,
  510. SSL_AD_REASON_OFFSET + alert_descr);
  511. BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
  512. ERR_add_error_data(2, "SSL alert number ", tmp);
  513. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  514. SSL_CTX_remove_session(s->ctx, s->session);
  515. return 0;
  516. } else {
  517. al = SSL_AD_ILLEGAL_PARAMETER;
  518. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
  519. goto f_err;
  520. }
  521. goto start;
  522. }
  523. if (s->shutdown & SSL_SENT_SHUTDOWN) {
  524. /* but we have not received a shutdown */
  525. s->rwstate = SSL_NOTHING;
  526. rr->length = 0;
  527. return 0;
  528. }
  529. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  530. /* 'Change Cipher Spec' is just a single byte, so we know exactly what the
  531. * record payload has to look like */
  532. if (rr->length != 1 || rr->off != 0 || rr->data[0] != SSL3_MT_CCS) {
  533. al = SSL_AD_ILLEGAL_PARAMETER;
  534. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  535. goto f_err;
  536. }
  537. rr->length = 0;
  538. if (s->msg_callback) {
  539. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
  540. s->msg_callback_arg);
  541. }
  542. /* We can't process a CCS now, because previous handshake
  543. * messages are still missing, so just drop it.
  544. */
  545. if (!s->d1->change_cipher_spec_ok) {
  546. goto start;
  547. }
  548. s->d1->change_cipher_spec_ok = 0;
  549. s->s3->change_cipher_spec = 1;
  550. if (!ssl3_do_change_cipher_spec(s)) {
  551. goto err;
  552. }
  553. /* do this whenever CCS is processed */
  554. dtls1_reset_seq_numbers(s, SSL3_CC_READ);
  555. goto start;
  556. }
  557. /* Unexpected handshake message. It may be a retransmitted Finished (the only
  558. * post-CCS message). Otherwise, it's a pre-CCS handshake message from an
  559. * unsupported renegotiation attempt. */
  560. if (rr->type == SSL3_RT_HANDSHAKE && !s->in_handshake) {
  561. if (rr->length < DTLS1_HM_HEADER_LENGTH) {
  562. al = SSL_AD_DECODE_ERROR;
  563. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_BAD_HANDSHAKE_RECORD);
  564. goto f_err;
  565. }
  566. struct hm_header_st msg_hdr;
  567. dtls1_get_message_header(&rr->data[rr->off], &msg_hdr);
  568. /* Ignore a stray Finished from the previous handshake. */
  569. if (msg_hdr.type == SSL3_MT_FINISHED) {
  570. if (msg_hdr.frag_off == 0) {
  571. /* Retransmit our last flight of messages. If the peer sends the second
  572. * Finished, they may not have received ours. Only do this for the
  573. * first fragment, in case the Finished was fragmented. */
  574. if (dtls1_check_timeout_num(s) < 0) {
  575. return -1;
  576. }
  577. dtls1_retransmit_buffered_messages(s);
  578. }
  579. rr->length = 0;
  580. goto start;
  581. }
  582. }
  583. /* We already handled these. */
  584. assert(rr->type != SSL3_RT_CHANGE_CIPHER_SPEC && rr->type != SSL3_RT_ALERT);
  585. al = SSL_AD_UNEXPECTED_MESSAGE;
  586. OPENSSL_PUT_ERROR(SSL, dtls1_read_bytes, SSL_R_UNEXPECTED_RECORD);
  587. f_err:
  588. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  589. err:
  590. return -1;
  591. }
  592. int dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len) {
  593. int i;
  594. if (SSL_in_init(s) && !s->in_handshake) {
  595. i = s->handshake_func(s);
  596. if (i < 0) {
  597. return i;
  598. }
  599. if (i == 0) {
  600. OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes,
  601. SSL_R_SSL_HANDSHAKE_FAILURE);
  602. return -1;
  603. }
  604. }
  605. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  606. OPENSSL_PUT_ERROR(SSL, dtls1_write_app_data_bytes,
  607. SSL_R_DTLS_MESSAGE_TOO_BIG);
  608. return -1;
  609. }
  610. i = dtls1_write_bytes(s, type, buf_, len);
  611. return i;
  612. }
  613. /* Call this to write data in records of type 'type' It will return <= 0 if not
  614. * all data has been sent or non-blocking IO. */
  615. int dtls1_write_bytes(SSL *s, int type, const void *buf, int len) {
  616. int i;
  617. assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  618. s->rwstate = SSL_NOTHING;
  619. i = do_dtls1_write(s, type, buf, len);
  620. return i;
  621. }
  622. static int do_dtls1_write(SSL *s, int type, const uint8_t *buf,
  623. unsigned int len) {
  624. uint8_t *p, *pseq;
  625. int i;
  626. int prefix_len = 0;
  627. int eivlen = 0;
  628. SSL3_RECORD *wr;
  629. SSL3_BUFFER *wb;
  630. /* ssl3_write_pending drops the write if |BIO_write| fails in DTLS, so there
  631. * is never pending data. */
  632. assert(s->s3->wbuf.left == 0);
  633. /* If we have an alert to send, lets send it */
  634. if (s->s3->alert_dispatch) {
  635. i = s->method->ssl_dispatch_alert(s);
  636. if (i <= 0) {
  637. return i;
  638. }
  639. /* if it went, fall through and send more stuff */
  640. }
  641. if (len == 0) {
  642. return 0;
  643. }
  644. wr = &(s->s3->wrec);
  645. wb = &(s->s3->wbuf);
  646. p = wb->buf + prefix_len;
  647. /* write the header */
  648. *(p++) = type & 0xff;
  649. wr->type = type;
  650. /* Special case: for hello verify request, client version 1.0 and
  651. * we haven't decided which version to use yet send back using
  652. * version 1.0 header: otherwise some clients will ignore it.
  653. */
  654. if (!s->s3->have_version) {
  655. *(p++) = DTLS1_VERSION >> 8;
  656. *(p++) = DTLS1_VERSION & 0xff;
  657. } else {
  658. *(p++) = s->version >> 8;
  659. *(p++) = s->version & 0xff;
  660. }
  661. /* field where we are to write out packet epoch, seq num and len */
  662. pseq = p;
  663. p += 10;
  664. /* Leave room for the variable nonce for AEADs which specify it explicitly. */
  665. if (s->aead_write_ctx != NULL &&
  666. s->aead_write_ctx->variable_nonce_included_in_record) {
  667. eivlen = s->aead_write_ctx->variable_nonce_len;
  668. }
  669. /* Assemble the input for |s->enc_method->enc|. The input is the plaintext
  670. * with |eivlen| bytes of space prepended for the explicit nonce. */
  671. wr->input = p;
  672. wr->length = eivlen + len;
  673. memcpy(p + eivlen, buf, len);
  674. /* Encrypt in-place, so the output also goes into |p|. */
  675. wr->data = p;
  676. if (!s->enc_method->enc(s, 1)) {
  677. goto err;
  678. }
  679. /* there's only one epoch between handshake and app data */
  680. s2n(s->d1->w_epoch, pseq);
  681. memcpy(pseq, &(s->s3->write_sequence[2]), 6);
  682. pseq += 6;
  683. s2n(wr->length, pseq);
  684. if (s->msg_callback) {
  685. s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
  686. DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
  687. }
  688. /* we should now have wr->data pointing to the encrypted data, which is
  689. * wr->length long */
  690. wr->type = type; /* not needed but helps for debugging */
  691. wr->length += DTLS1_RT_HEADER_LENGTH;
  692. if (!ssl3_record_sequence_update(&s->s3->write_sequence[2], 6)) {
  693. goto err;
  694. }
  695. /* now let's set up wb */
  696. wb->left = prefix_len + wr->length;
  697. wb->offset = 0;
  698. /* memorize arguments so that ssl3_write_pending can detect bad write retries
  699. * later */
  700. s->s3->wpend_tot = len;
  701. s->s3->wpend_buf = buf;
  702. s->s3->wpend_type = type;
  703. s->s3->wpend_ret = len;
  704. /* we now just need to write the buffer */
  705. return ssl3_write_pending(s, type, buf, len);
  706. err:
  707. return -1;
  708. }
  709. static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap) {
  710. int cmp;
  711. unsigned int shift;
  712. const uint8_t *seq = s->s3->read_sequence;
  713. cmp = satsub64be(seq, bitmap->max_seq_num);
  714. if (cmp > 0) {
  715. memcpy(s->s3->rrec.seq_num, seq, 8);
  716. return 1; /* this record in new */
  717. }
  718. shift = -cmp;
  719. if (shift >= sizeof(bitmap->map) * 8) {
  720. return 0; /* stale, outside the window */
  721. } else if (bitmap->map & (((uint64_t)1) << shift)) {
  722. return 0; /* record previously received */
  723. }
  724. memcpy(s->s3->rrec.seq_num, seq, 8);
  725. return 1;
  726. }
  727. static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap) {
  728. int cmp;
  729. unsigned int shift;
  730. const uint8_t *seq = s->s3->read_sequence;
  731. cmp = satsub64be(seq, bitmap->max_seq_num);
  732. if (cmp > 0) {
  733. shift = cmp;
  734. if (shift < sizeof(bitmap->map) * 8) {
  735. bitmap->map <<= shift, bitmap->map |= 1UL;
  736. } else {
  737. bitmap->map = 1UL;
  738. }
  739. memcpy(bitmap->max_seq_num, seq, 8);
  740. } else {
  741. shift = -cmp;
  742. if (shift < sizeof(bitmap->map) * 8) {
  743. bitmap->map |= ((uint64_t)1) << shift;
  744. }
  745. }
  746. }
  747. int dtls1_dispatch_alert(SSL *s) {
  748. int i, j;
  749. void (*cb)(const SSL *ssl, int type, int val) = NULL;
  750. uint8_t buf[DTLS1_AL_HEADER_LENGTH];
  751. uint8_t *ptr = &buf[0];
  752. s->s3->alert_dispatch = 0;
  753. memset(buf, 0x00, sizeof(buf));
  754. *ptr++ = s->s3->send_alert[0];
  755. *ptr++ = s->s3->send_alert[1];
  756. i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf));
  757. if (i <= 0) {
  758. s->s3->alert_dispatch = 1;
  759. } else {
  760. if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
  761. (void)BIO_flush(s->wbio);
  762. }
  763. if (s->msg_callback) {
  764. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
  765. s->msg_callback_arg);
  766. }
  767. if (s->info_callback != NULL) {
  768. cb = s->info_callback;
  769. } else if (s->ctx->info_callback != NULL) {
  770. cb = s->ctx->info_callback;
  771. }
  772. if (cb != NULL) {
  773. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  774. cb(s, SSL_CB_WRITE_ALERT, j);
  775. }
  776. }
  777. return i;
  778. }
  779. void dtls1_reset_seq_numbers(SSL *s, int rw) {
  780. uint8_t *seq;
  781. unsigned int seq_bytes = sizeof(s->s3->read_sequence);
  782. if (rw & SSL3_CC_READ) {
  783. seq = s->s3->read_sequence;
  784. s->d1->r_epoch++;
  785. memset(&s->d1->bitmap, 0, sizeof(DTLS1_BITMAP));
  786. } else {
  787. seq = s->s3->write_sequence;
  788. memcpy(s->d1->last_write_sequence, seq, sizeof(s->s3->write_sequence));
  789. s->d1->w_epoch++;
  790. }
  791. memset(seq, 0x00, seq_bytes);
  792. }