Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

540 řádky
18 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 <openssl/ssl.h>
  112. #include <assert.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. static int do_dtls1_write(SSL *ssl, int type, const uint8_t *buf,
  121. unsigned int len, enum dtls1_use_epoch_t use_epoch);
  122. /* dtls1_get_record reads a new input record. On success, it places it in
  123. * |ssl->s3->rrec| and returns one. Otherwise it returns <= 0 on error or if
  124. * more data is needed. */
  125. static int dtls1_get_record(SSL *ssl) {
  126. again:
  127. /* Read a new packet if there is no unconsumed one. */
  128. if (ssl_read_buffer_len(ssl) == 0) {
  129. int ret = ssl_read_buffer_extend_to(ssl, 0 /* unused */);
  130. if (ret <= 0) {
  131. return ret;
  132. }
  133. }
  134. assert(ssl_read_buffer_len(ssl) > 0);
  135. /* Ensure the packet is large enough to decrypt in-place. */
  136. if (ssl_read_buffer_len(ssl) < ssl_record_prefix_len(ssl)) {
  137. ssl_read_buffer_clear(ssl);
  138. goto again;
  139. }
  140. uint8_t *out = ssl_read_buffer(ssl) + ssl_record_prefix_len(ssl);
  141. size_t max_out = ssl_read_buffer_len(ssl) - ssl_record_prefix_len(ssl);
  142. uint8_t type, alert;
  143. size_t len, consumed;
  144. switch (dtls_open_record(ssl, &type, out, &len, &consumed, &alert, max_out,
  145. ssl_read_buffer(ssl), ssl_read_buffer_len(ssl))) {
  146. case ssl_open_record_success:
  147. ssl_read_buffer_consume(ssl, consumed);
  148. if (len > 0xffff) {
  149. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  150. return -1;
  151. }
  152. SSL3_RECORD *rr = &ssl->s3->rrec;
  153. rr->type = type;
  154. rr->length = (uint16_t)len;
  155. rr->data = out;
  156. return 1;
  157. case ssl_open_record_discard:
  158. ssl_read_buffer_consume(ssl, consumed);
  159. goto again;
  160. case ssl_open_record_error:
  161. ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
  162. return -1;
  163. case ssl_open_record_partial:
  164. /* Impossible in DTLS. */
  165. break;
  166. }
  167. assert(0);
  168. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  169. return -1;
  170. }
  171. int dtls1_read_app_data(SSL *ssl, uint8_t *buf, int len, int peek) {
  172. assert(!SSL_in_init(ssl));
  173. return dtls1_read_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf, len, peek);
  174. }
  175. int dtls1_read_change_cipher_spec(SSL *ssl) {
  176. uint8_t byte;
  177. int ret = dtls1_read_bytes(ssl, SSL3_RT_CHANGE_CIPHER_SPEC, &byte,
  178. 1 /* len */, 0 /* no peek */);
  179. if (ret <= 0) {
  180. return ret;
  181. }
  182. assert(ret == 1);
  183. if (ssl->s3->rrec.length != 0 || byte != SSL3_MT_CCS) {
  184. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  185. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
  186. return -1;
  187. }
  188. if (ssl->msg_callback != NULL) {
  189. ssl->msg_callback(0, ssl->version, SSL3_RT_CHANGE_CIPHER_SPEC, &byte, 1,
  190. ssl, ssl->msg_callback_arg);
  191. }
  192. return 1;
  193. }
  194. void dtls1_read_close_notify(SSL *ssl) {
  195. /* Bidirectional shutdown doesn't make sense for an unordered transport. DTLS
  196. * alerts also aren't delivered reliably, so we may even time out because the
  197. * peer never received our close_notify. Report to the caller that the channel
  198. * has fully shut down. */
  199. ssl->shutdown |= SSL_RECEIVED_SHUTDOWN;
  200. }
  201. /* Return up to 'len' payload bytes received in 'type' records.
  202. * 'type' is one of the following:
  203. *
  204. * - SSL3_RT_HANDSHAKE (when dtls1_get_message calls us)
  205. * - SSL3_RT_CHANGE_CIPHER_SPEC (when dtls1_read_change_cipher_spec calls us)
  206. * - SSL3_RT_APPLICATION_DATA (when dtls1_read_app_data calls us)
  207. *
  208. * If we don't have stored data to work from, read a DTLS record first (possibly
  209. * multiple records if we still don't have anything to return).
  210. *
  211. * This function must handle any surprises the peer may have for us, such as
  212. * Alert records (e.g. close_notify) and out of records. */
  213. int dtls1_read_bytes(SSL *ssl, int type, unsigned char *buf, int len, int peek) {
  214. int al, ret;
  215. unsigned int n;
  216. SSL3_RECORD *rr;
  217. void (*cb)(const SSL *ssl, int type, int value) = NULL;
  218. if ((type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE &&
  219. type != SSL3_RT_CHANGE_CIPHER_SPEC) ||
  220. (peek && type != SSL3_RT_APPLICATION_DATA)) {
  221. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  222. return -1;
  223. }
  224. start:
  225. /* ssl->s3->rrec.type - is the type of record
  226. * ssl->s3->rrec.data - data
  227. * ssl->s3->rrec.off - offset into 'data' for next read
  228. * ssl->s3->rrec.length - number of bytes. */
  229. rr = &ssl->s3->rrec;
  230. /* Check for timeout */
  231. if (DTLSv1_handle_timeout(ssl) > 0) {
  232. goto start;
  233. }
  234. /* get new packet if necessary */
  235. if (rr->length == 0) {
  236. ret = dtls1_get_record(ssl);
  237. if (ret <= 0) {
  238. ret = dtls1_read_failed(ssl, ret);
  239. /* anything other than a timeout is an error */
  240. if (ret <= 0) {
  241. return ret;
  242. } else {
  243. goto start;
  244. }
  245. }
  246. }
  247. /* we now have a packet which can be read and processed */
  248. /* If the other end has shut down, throw anything we read away (even in
  249. * 'peek' mode) */
  250. if (ssl->shutdown & SSL_RECEIVED_SHUTDOWN) {
  251. rr->length = 0;
  252. return 0;
  253. }
  254. if (type == rr->type) {
  255. /* Make sure that we are not getting application data when we
  256. * are doing a handshake for the first time. */
  257. if (SSL_in_init(ssl) && (type == SSL3_RT_APPLICATION_DATA) &&
  258. (ssl->s3->aead_read_ctx == NULL)) {
  259. /* TODO(davidben): Is this check redundant with the handshake_func
  260. * check? */
  261. al = SSL_AD_UNEXPECTED_MESSAGE;
  262. OPENSSL_PUT_ERROR(SSL, SSL_R_APP_DATA_IN_HANDSHAKE);
  263. goto f_err;
  264. }
  265. /* Discard empty records. */
  266. if (rr->length == 0) {
  267. goto start;
  268. }
  269. if (len <= 0) {
  270. return len;
  271. }
  272. if ((unsigned int)len > rr->length) {
  273. n = rr->length;
  274. } else {
  275. n = (unsigned int)len;
  276. }
  277. memcpy(buf, rr->data, n);
  278. if (!peek) {
  279. rr->length -= n;
  280. rr->data += n;
  281. if (rr->length == 0) {
  282. /* The record has been consumed, so we may now clear the buffer. */
  283. ssl_read_buffer_discard(ssl);
  284. }
  285. }
  286. return n;
  287. }
  288. /* If we get here, then type != rr->type. */
  289. /* If an alert record, process the alert. */
  290. if (rr->type == SSL3_RT_ALERT) {
  291. /* Alerts records may not contain fragmented or multiple alerts. */
  292. if (rr->length != 2) {
  293. al = SSL_AD_DECODE_ERROR;
  294. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ALERT);
  295. goto f_err;
  296. }
  297. if (ssl->msg_callback) {
  298. ssl->msg_callback(0, ssl->version, SSL3_RT_ALERT, rr->data, 2, ssl,
  299. ssl->msg_callback_arg);
  300. }
  301. const uint8_t alert_level = rr->data[0];
  302. const uint8_t alert_descr = rr->data[1];
  303. rr->length -= 2;
  304. rr->data += 2;
  305. if (ssl->info_callback != NULL) {
  306. cb = ssl->info_callback;
  307. } else if (ssl->ctx->info_callback != NULL) {
  308. cb = ssl->ctx->info_callback;
  309. }
  310. if (cb != NULL) {
  311. uint16_t alert = (alert_level << 8) | alert_descr;
  312. cb(ssl, SSL_CB_READ_ALERT, alert);
  313. }
  314. if (alert_level == SSL3_AL_WARNING) {
  315. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  316. ssl->s3->clean_shutdown = 1;
  317. ssl->shutdown |= SSL_RECEIVED_SHUTDOWN;
  318. return 0;
  319. }
  320. } else if (alert_level == SSL3_AL_FATAL) {
  321. char tmp[16];
  322. OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr);
  323. BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
  324. ERR_add_error_data(2, "SSL alert number ", tmp);
  325. ssl->shutdown |= SSL_RECEIVED_SHUTDOWN;
  326. SSL_CTX_remove_session(ssl->ctx, ssl->session);
  327. return 0;
  328. } else {
  329. al = SSL_AD_ILLEGAL_PARAMETER;
  330. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_ALERT_TYPE);
  331. goto f_err;
  332. }
  333. goto start;
  334. }
  335. /* Cross-epoch records are discarded, but we may receive out-of-order
  336. * application data between ChangeCipherSpec and Finished or a ChangeCipherSpec
  337. * before the appropriate point in the handshake. Those must be silently
  338. * discarded.
  339. *
  340. * However, only allow the out-of-order records in the correct epoch.
  341. * Application data must come in the encrypted epoch, and ChangeCipherSpec in
  342. * the unencrypted epoch (we never renegotiate). Other cases fall through and
  343. * fail with a fatal error. */
  344. if ((rr->type == SSL3_RT_APPLICATION_DATA &&
  345. ssl->s3->aead_read_ctx != NULL) ||
  346. (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC &&
  347. ssl->s3->aead_read_ctx == NULL)) {
  348. rr->length = 0;
  349. goto start;
  350. }
  351. if (rr->type == SSL3_RT_HANDSHAKE) {
  352. if (type != SSL3_RT_APPLICATION_DATA) {
  353. /* Out-of-order handshake record while looking for ChangeCipherSpec. Drop
  354. * it silently. */
  355. assert(type == SSL3_RT_CHANGE_CIPHER_SPEC);
  356. rr->length = 0;
  357. goto start;
  358. }
  359. /* Parse the first fragment header to determine if this is a pre-CCS or
  360. * post-CCS handshake record. DTLS resets handshake message numbers on each
  361. * handshake, so renegotiations and retransmissions are ambiguous. */
  362. if (rr->length < DTLS1_HM_HEADER_LENGTH) {
  363. al = SSL_AD_DECODE_ERROR;
  364. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HANDSHAKE_RECORD);
  365. goto f_err;
  366. }
  367. struct hm_header_st msg_hdr;
  368. dtls1_get_message_header(rr->data, &msg_hdr);
  369. if (msg_hdr.type == SSL3_MT_FINISHED) {
  370. if (msg_hdr.frag_off == 0) {
  371. /* Retransmit our last flight of messages. If the peer sends the second
  372. * Finished, they may not have received ours. Only do this for the
  373. * first fragment, in case the Finished was fragmented. */
  374. if (dtls1_check_timeout_num(ssl) < 0) {
  375. return -1;
  376. }
  377. dtls1_retransmit_buffered_messages(ssl);
  378. }
  379. rr->length = 0;
  380. goto start;
  381. }
  382. /* Otherwise, this is a pre-CCS handshake message from an unsupported
  383. * renegotiation attempt. Fall through to the error path. */
  384. }
  385. al = SSL_AD_UNEXPECTED_MESSAGE;
  386. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  387. f_err:
  388. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  389. return -1;
  390. }
  391. int dtls1_write_app_data(SSL *ssl, const void *buf_, int len) {
  392. assert(!SSL_in_init(ssl));
  393. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  394. OPENSSL_PUT_ERROR(SSL, SSL_R_DTLS_MESSAGE_TOO_BIG);
  395. return -1;
  396. }
  397. return dtls1_write_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf_, len,
  398. dtls1_use_current_epoch);
  399. }
  400. /* Call this to write data in records of type 'type' It will return <= 0 if not
  401. * all data has been sent or non-blocking IO. */
  402. int dtls1_write_bytes(SSL *ssl, int type, const void *buf, int len,
  403. enum dtls1_use_epoch_t use_epoch) {
  404. assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
  405. return do_dtls1_write(ssl, type, buf, len, use_epoch);
  406. }
  407. static int do_dtls1_write(SSL *ssl, int type, const uint8_t *buf,
  408. unsigned int len, enum dtls1_use_epoch_t use_epoch) {
  409. /* There should never be a pending write buffer in DTLS. One can't write half
  410. * a datagram, so the write buffer is always dropped in
  411. * |ssl_write_buffer_flush|. */
  412. assert(!ssl_write_buffer_is_pending(ssl));
  413. /* If we have an alert to send, lets send it */
  414. if (ssl->s3->alert_dispatch) {
  415. int ret = ssl->method->ssl_dispatch_alert(ssl);
  416. if (ret <= 0) {
  417. return ret;
  418. }
  419. /* if it went, fall through and send more stuff */
  420. }
  421. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  422. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  423. return -1;
  424. }
  425. if (len == 0) {
  426. return 0;
  427. }
  428. size_t max_out = len + ssl_max_seal_overhead(ssl);
  429. uint8_t *out;
  430. size_t ciphertext_len;
  431. if (!ssl_write_buffer_init(ssl, &out, max_out) ||
  432. !dtls_seal_record(ssl, out, &ciphertext_len, max_out, type, buf, len,
  433. use_epoch)) {
  434. ssl_write_buffer_clear(ssl);
  435. return -1;
  436. }
  437. ssl_write_buffer_set_len(ssl, ciphertext_len);
  438. int ret = ssl_write_buffer_flush(ssl);
  439. if (ret <= 0) {
  440. return ret;
  441. }
  442. return (int)len;
  443. }
  444. int dtls1_dispatch_alert(SSL *ssl) {
  445. ssl->s3->alert_dispatch = 0;
  446. int ret = do_dtls1_write(ssl, SSL3_RT_ALERT, &ssl->s3->send_alert[0], 2,
  447. dtls1_use_current_epoch);
  448. if (ret <= 0) {
  449. ssl->s3->alert_dispatch = 1;
  450. return ret;
  451. }
  452. /* If the alert is fatal, flush the BIO now. */
  453. if (ssl->s3->send_alert[0] == SSL3_AL_FATAL) {
  454. BIO_flush(ssl->wbio);
  455. }
  456. if (ssl->msg_callback != NULL) {
  457. ssl->msg_callback(1 /* write */, ssl->version, SSL3_RT_ALERT,
  458. ssl->s3->send_alert, 2, ssl, ssl->msg_callback_arg);
  459. }
  460. void (*cb)(const SSL *ssl, int type, int value) = NULL;
  461. if (ssl->info_callback != NULL) {
  462. cb = ssl->info_callback;
  463. } else if (ssl->ctx->info_callback != NULL) {
  464. cb = ssl->ctx->info_callback;
  465. }
  466. if (cb != NULL) {
  467. int alert = (ssl->s3->send_alert[0] << 8) | ssl->s3->send_alert[1];
  468. cb(ssl, SSL_CB_WRITE_ALERT, alert);
  469. }
  470. return 1;
  471. }