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ů.
 
 
 
 
 
 

806 řádky
26 KiB

  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2002 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com). */
  108. #include <openssl/ssl.h>
  109. #include <assert.h>
  110. #include <limits.h>
  111. #include <stdio.h>
  112. #include <string.h>
  113. #include <openssl/buf.h>
  114. #include <openssl/err.h>
  115. #include <openssl/evp.h>
  116. #include <openssl/mem.h>
  117. #include <openssl/rand.h>
  118. #include "internal.h"
  119. static int do_ssl3_write(SSL *s, int type, const uint8_t *buf, unsigned len);
  120. /* kMaxWarningAlerts is the number of consecutive warning alerts that will be
  121. * processed. */
  122. static const uint8_t kMaxWarningAlerts = 4;
  123. /* ssl3_get_record reads a new input record. On success, it places it in
  124. * |ssl->s3->rrec| and returns one. Otherwise it returns <= 0 on error or if
  125. * more data is needed. */
  126. static int ssl3_get_record(SSL *ssl) {
  127. int ret;
  128. again:
  129. /* Ensure the buffer is large enough to decrypt in-place. */
  130. ret = ssl_read_buffer_extend_to(ssl, ssl_record_prefix_len(ssl));
  131. if (ret <= 0) {
  132. return ret;
  133. }
  134. assert(ssl_read_buffer_len(ssl) >= ssl_record_prefix_len(ssl));
  135. uint8_t *out = ssl_read_buffer(ssl) + ssl_record_prefix_len(ssl);
  136. size_t max_out = ssl_read_buffer_len(ssl) - ssl_record_prefix_len(ssl);
  137. uint8_t type, alert;
  138. size_t len, consumed;
  139. switch (tls_open_record(ssl, &type, out, &len, &consumed, &alert, max_out,
  140. ssl_read_buffer(ssl), ssl_read_buffer_len(ssl))) {
  141. case ssl_open_record_success:
  142. ssl_read_buffer_consume(ssl, consumed);
  143. if (len > 0xffff) {
  144. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  145. return -1;
  146. }
  147. SSL3_RECORD *rr = &ssl->s3->rrec;
  148. rr->type = type;
  149. rr->length = (uint16_t)len;
  150. rr->off = 0;
  151. rr->data = out;
  152. return 1;
  153. case ssl_open_record_partial:
  154. ret = ssl_read_buffer_extend_to(ssl, consumed);
  155. if (ret <= 0) {
  156. return ret;
  157. }
  158. goto again;
  159. case ssl_open_record_discard:
  160. ssl_read_buffer_consume(ssl, consumed);
  161. goto again;
  162. case ssl_open_record_error:
  163. ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
  164. return -1;
  165. }
  166. assert(0);
  167. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  168. return -1;
  169. }
  170. int ssl3_write_app_data(SSL *ssl, const void *buf, int len) {
  171. return ssl3_write_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf, len);
  172. }
  173. /* Call this to write data in records of type |type|. It will return <= 0 if
  174. * not all data has been sent or non-blocking IO. */
  175. int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len) {
  176. const uint8_t *buf = buf_;
  177. unsigned int tot, n, nw;
  178. int i;
  179. s->rwstate = SSL_NOTHING;
  180. assert(s->s3->wnum <= INT_MAX);
  181. tot = s->s3->wnum;
  182. s->s3->wnum = 0;
  183. if (!s->in_handshake && SSL_in_init(s) && !SSL_in_false_start(s)) {
  184. i = s->handshake_func(s);
  185. if (i < 0) {
  186. return i;
  187. }
  188. if (i == 0) {
  189. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
  190. return -1;
  191. }
  192. }
  193. /* Ensure that if we end up with a smaller value of data to write out than
  194. * the the original len from a write which didn't complete for non-blocking
  195. * I/O and also somehow ended up avoiding the check for this in
  196. * ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be possible to
  197. * end up with (len-tot) as a large number that will then promptly send
  198. * beyond the end of the users buffer ... so we trap and report the error in
  199. * a way the user will notice. */
  200. if (len < 0 || (size_t)len < tot) {
  201. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_LENGTH);
  202. return -1;
  203. }
  204. n = (len - tot);
  205. for (;;) {
  206. /* max contains the maximum number of bytes that we can put into a
  207. * record. */
  208. unsigned max = s->max_send_fragment;
  209. if (n > max) {
  210. nw = max;
  211. } else {
  212. nw = n;
  213. }
  214. i = do_ssl3_write(s, type, &buf[tot], nw);
  215. if (i <= 0) {
  216. s->s3->wnum = tot;
  217. return i;
  218. }
  219. if (i == (int)n || (type == SSL3_RT_APPLICATION_DATA &&
  220. (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
  221. return tot + i;
  222. }
  223. n -= i;
  224. tot += i;
  225. }
  226. }
  227. /* do_ssl3_write writes an SSL record of the given type. */
  228. static int do_ssl3_write(SSL *s, int type, const uint8_t *buf, unsigned len) {
  229. /* If there is still data from the previous record, flush it. */
  230. if (ssl_write_buffer_is_pending(s)) {
  231. return ssl3_write_pending(s, type, buf, len);
  232. }
  233. /* If we have an alert to send, lets send it */
  234. if (s->s3->alert_dispatch) {
  235. int ret = s->method->ssl_dispatch_alert(s);
  236. if (ret <= 0) {
  237. return ret;
  238. }
  239. /* if it went, fall through and send more stuff */
  240. }
  241. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  242. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  243. return -1;
  244. }
  245. if (len == 0) {
  246. return 0;
  247. }
  248. size_t max_out = len + ssl_max_seal_overhead(s);
  249. if (max_out < len) {
  250. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  251. return -1;
  252. }
  253. uint8_t *out;
  254. size_t ciphertext_len;
  255. if (!ssl_write_buffer_init(s, &out, max_out) ||
  256. !tls_seal_record(s, out, &ciphertext_len, max_out, type, buf, len)) {
  257. return -1;
  258. }
  259. ssl_write_buffer_set_len(s, ciphertext_len);
  260. /* memorize arguments so that ssl3_write_pending can detect bad write retries
  261. * later */
  262. s->s3->wpend_tot = len;
  263. s->s3->wpend_buf = buf;
  264. s->s3->wpend_type = type;
  265. s->s3->wpend_ret = len;
  266. /* we now just need to write the buffer */
  267. return ssl3_write_pending(s, type, buf, len);
  268. }
  269. int ssl3_write_pending(SSL *s, int type, const uint8_t *buf, unsigned int len) {
  270. if (s->s3->wpend_tot > (int)len ||
  271. (s->s3->wpend_buf != buf &&
  272. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) ||
  273. s->s3->wpend_type != type) {
  274. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_WRITE_RETRY);
  275. return -1;
  276. }
  277. int ret = ssl_write_buffer_flush(s);
  278. if (ret <= 0) {
  279. return ret;
  280. }
  281. return s->s3->wpend_ret;
  282. }
  283. /* ssl3_expect_change_cipher_spec informs the record layer that a
  284. * ChangeCipherSpec record is required at this point. If a Handshake record is
  285. * received before ChangeCipherSpec, the connection will fail. Moreover, if
  286. * there are unprocessed handshake bytes, the handshake will also fail and the
  287. * function returns zero. Otherwise, the function returns one. */
  288. int ssl3_expect_change_cipher_spec(SSL *s) {
  289. if (s->s3->handshake_fragment_len > 0 || s->s3->tmp.reuse_message) {
  290. OPENSSL_PUT_ERROR(SSL, SSL_R_UNPROCESSED_HANDSHAKE_DATA);
  291. return 0;
  292. }
  293. s->s3->flags |= SSL3_FLAGS_EXPECT_CCS;
  294. return 1;
  295. }
  296. int ssl3_read_app_data(SSL *ssl, uint8_t *buf, int len, int peek) {
  297. return ssl3_read_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf, len, peek);
  298. }
  299. void ssl3_read_close_notify(SSL *ssl) {
  300. ssl3_read_bytes(ssl, 0, NULL, 0, 0);
  301. }
  302. /* Return up to 'len' payload bytes received in 'type' records.
  303. * 'type' is one of the following:
  304. *
  305. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  306. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  307. * - 0 (during a shutdown, no data has to be returned)
  308. *
  309. * If we don't have stored data to work from, read a SSL/TLS record first
  310. * (possibly multiple records if we still don't have anything to return).
  311. *
  312. * This function must handle any surprises the peer may have for us, such as
  313. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  314. * a surprise, but handled as if it were), or renegotiation requests.
  315. * Also if record payloads contain fragments too small to process, we store
  316. * them until there is enough for the respective protocol (the record protocol
  317. * may use arbitrary fragmentation and even interleaving):
  318. * Change cipher spec protocol
  319. * just 1 byte needed, no need for keeping anything stored
  320. * Alert protocol
  321. * 2 bytes needed (AlertLevel, AlertDescription)
  322. * Handshake protocol
  323. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  324. * to detect unexpected Client Hello and Hello Request messages
  325. * here, anything else is handled by higher layers
  326. * Application data protocol
  327. * none of our business
  328. */
  329. int ssl3_read_bytes(SSL *s, int type, uint8_t *buf, int len, int peek) {
  330. int al, i, ret;
  331. unsigned int n;
  332. SSL3_RECORD *rr;
  333. void (*cb)(const SSL *ssl, int type2, int val) = NULL;
  334. if ((type && type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) ||
  335. (peek && type != SSL3_RT_APPLICATION_DATA)) {
  336. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  337. return -1;
  338. }
  339. if (type == SSL3_RT_HANDSHAKE && s->s3->handshake_fragment_len > 0) {
  340. /* (partially) satisfy request from storage */
  341. uint8_t *src = s->s3->handshake_fragment;
  342. uint8_t *dst = buf;
  343. unsigned int k;
  344. /* peek == 0 */
  345. n = 0;
  346. while (len > 0 && s->s3->handshake_fragment_len > 0) {
  347. *dst++ = *src++;
  348. len--;
  349. s->s3->handshake_fragment_len--;
  350. n++;
  351. }
  352. /* move any remaining fragment bytes: */
  353. for (k = 0; k < s->s3->handshake_fragment_len; k++) {
  354. s->s3->handshake_fragment[k] = *src++;
  355. }
  356. return n;
  357. }
  358. /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  359. /* This may require multiple iterations. False Start will cause
  360. * |s->handshake_func| to signal success one step early, but the handshake
  361. * must be completely finished before other modes are accepted.
  362. *
  363. * TODO(davidben): Move this check up to a higher level. */
  364. while (!s->in_handshake && SSL_in_init(s)) {
  365. assert(type == SSL3_RT_APPLICATION_DATA);
  366. i = s->handshake_func(s);
  367. if (i < 0) {
  368. return i;
  369. }
  370. if (i == 0) {
  371. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
  372. return -1;
  373. }
  374. }
  375. start:
  376. s->rwstate = SSL_NOTHING;
  377. /* s->s3->rrec.type - is the type of record
  378. * s->s3->rrec.data - data
  379. * s->s3->rrec.off - offset into 'data' for next read
  380. * s->s3->rrec.length - number of bytes. */
  381. rr = &s->s3->rrec;
  382. /* get new packet if necessary */
  383. if (rr->length == 0) {
  384. ret = ssl3_get_record(s);
  385. if (ret <= 0) {
  386. return ret;
  387. }
  388. }
  389. /* we now have a packet which can be read and processed */
  390. /* |change_cipher_spec is set when we receive a ChangeCipherSpec and reset by
  391. * ssl3_get_finished. */
  392. if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE &&
  393. rr->type != SSL3_RT_ALERT) {
  394. al = SSL_AD_UNEXPECTED_MESSAGE;
  395. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  396. goto f_err;
  397. }
  398. /* If we are expecting a ChangeCipherSpec, it is illegal to receive a
  399. * Handshake record. */
  400. if (rr->type == SSL3_RT_HANDSHAKE && (s->s3->flags & SSL3_FLAGS_EXPECT_CCS)) {
  401. al = SSL_AD_UNEXPECTED_MESSAGE;
  402. OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_RECORD_BEFORE_CCS);
  403. goto f_err;
  404. }
  405. /* If the other end has shut down, throw anything we read away (even in
  406. * 'peek' mode) */
  407. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  408. rr->length = 0;
  409. s->rwstate = SSL_NOTHING;
  410. return 0;
  411. }
  412. if (type != 0 && type == rr->type) {
  413. s->s3->warning_alert_count = 0;
  414. /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  415. /* make sure that we are not getting application data when we are doing a
  416. * handshake for the first time */
  417. if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
  418. s->aead_read_ctx == NULL) {
  419. /* TODO(davidben): Is this check redundant with the handshake_func
  420. * check? */
  421. al = SSL_AD_UNEXPECTED_MESSAGE;
  422. OPENSSL_PUT_ERROR(SSL, SSL_R_APP_DATA_IN_HANDSHAKE);
  423. goto f_err;
  424. }
  425. /* Discard empty records. */
  426. if (rr->length == 0) {
  427. goto start;
  428. }
  429. if (len <= 0) {
  430. return len;
  431. }
  432. if ((unsigned int)len > rr->length) {
  433. n = rr->length;
  434. } else {
  435. n = (unsigned int)len;
  436. }
  437. memcpy(buf, &(rr->data[rr->off]), n);
  438. if (!peek) {
  439. rr->length -= n;
  440. rr->off += n;
  441. if (rr->length == 0) {
  442. rr->off = 0;
  443. /* The record has been consumed, so we may now clear the buffer. */
  444. ssl_read_buffer_discard(s);
  445. }
  446. }
  447. return n;
  448. }
  449. /* Process unexpected records. */
  450. if (rr->type == SSL3_RT_HANDSHAKE) {
  451. /* If peer renegotiations are disabled, all out-of-order handshake records
  452. * are fatal. Renegotiations as a server are never supported. */
  453. if (!s->accept_peer_renegotiations || s->server) {
  454. al = SSL_AD_NO_RENEGOTIATION;
  455. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
  456. goto f_err;
  457. }
  458. /* HelloRequests may be fragmented across multiple records. */
  459. const size_t size = sizeof(s->s3->handshake_fragment);
  460. const size_t avail = size - s->s3->handshake_fragment_len;
  461. const size_t todo = (rr->length < avail) ? rr->length : avail;
  462. memcpy(s->s3->handshake_fragment + s->s3->handshake_fragment_len,
  463. &rr->data[rr->off], todo);
  464. rr->off += todo;
  465. rr->length -= todo;
  466. s->s3->handshake_fragment_len += todo;
  467. if (s->s3->handshake_fragment_len < size) {
  468. goto start; /* fragment was too small */
  469. }
  470. /* Parse out and consume a HelloRequest. */
  471. if (s->s3->handshake_fragment[0] != SSL3_MT_HELLO_REQUEST ||
  472. s->s3->handshake_fragment[1] != 0 ||
  473. s->s3->handshake_fragment[2] != 0 ||
  474. s->s3->handshake_fragment[3] != 0) {
  475. al = SSL_AD_DECODE_ERROR;
  476. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HELLO_REQUEST);
  477. goto f_err;
  478. }
  479. s->s3->handshake_fragment_len = 0;
  480. if (s->msg_callback) {
  481. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  482. s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
  483. }
  484. if (!SSL_is_init_finished(s) || !s->s3->initial_handshake_complete) {
  485. /* This cannot happen. If a handshake is in progress, |type| must be
  486. * |SSL3_RT_HANDSHAKE|. */
  487. assert(0);
  488. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  489. goto err;
  490. }
  491. /* Renegotiation is only supported at quiescent points in the application
  492. * protocol, namely in HTTPS, just before reading the HTTP response. Require
  493. * the record-layer be idle and avoid complexities of sending a handshake
  494. * record while an application_data record is being written. */
  495. if (ssl_write_buffer_is_pending(s)) {
  496. al = SSL_AD_NO_RENEGOTIATION;
  497. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
  498. goto f_err;
  499. }
  500. /* Begin a new handshake. */
  501. s->state = SSL_ST_CONNECT;
  502. i = s->handshake_func(s);
  503. if (i < 0) {
  504. return i;
  505. }
  506. if (i == 0) {
  507. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
  508. return -1;
  509. }
  510. /* The handshake completed synchronously. Continue reading records. */
  511. goto start;
  512. }
  513. /* If an alert record, process one alert out of the record. Note that we allow
  514. * a single record to contain multiple alerts. */
  515. if (rr->type == SSL3_RT_ALERT) {
  516. /* Alerts may not be fragmented. */
  517. if (rr->length < 2) {
  518. al = SSL_AD_DECODE_ERROR;
  519. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ALERT);
  520. goto f_err;
  521. }
  522. if (s->msg_callback) {
  523. s->msg_callback(0, s->version, SSL3_RT_ALERT, &rr->data[rr->off], 2, s,
  524. s->msg_callback_arg);
  525. }
  526. const uint8_t alert_level = rr->data[rr->off++];
  527. const uint8_t alert_descr = rr->data[rr->off++];
  528. rr->length -= 2;
  529. if (s->info_callback != NULL) {
  530. cb = s->info_callback;
  531. } else if (s->ctx->info_callback != NULL) {
  532. cb = s->ctx->info_callback;
  533. }
  534. if (cb != NULL) {
  535. uint16_t alert = (alert_level << 8) | alert_descr;
  536. cb(s, SSL_CB_READ_ALERT, alert);
  537. }
  538. if (alert_level == SSL3_AL_WARNING) {
  539. s->s3->warn_alert = alert_descr;
  540. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  541. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  542. return 0;
  543. }
  544. /* This is a warning but we receive it if we requested renegotiation and
  545. * the peer denied it. Terminate with a fatal alert because if
  546. * application tried to renegotiatie it presumably had a good reason and
  547. * expects it to succeed.
  548. *
  549. * In future we might have a renegotiation where we don't care if the
  550. * peer refused it where we carry on. */
  551. else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  552. al = SSL_AD_HANDSHAKE_FAILURE;
  553. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
  554. goto f_err;
  555. }
  556. s->s3->warning_alert_count++;
  557. if (s->s3->warning_alert_count > kMaxWarningAlerts) {
  558. al = SSL_AD_UNEXPECTED_MESSAGE;
  559. OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_WARNING_ALERTS);
  560. goto f_err;
  561. }
  562. } else if (alert_level == SSL3_AL_FATAL) {
  563. char tmp[16];
  564. s->rwstate = SSL_NOTHING;
  565. s->s3->fatal_alert = alert_descr;
  566. OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr);
  567. BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
  568. ERR_add_error_data(2, "SSL alert number ", tmp);
  569. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  570. SSL_CTX_remove_session(s->ctx, s->session);
  571. return 0;
  572. } else {
  573. al = SSL_AD_ILLEGAL_PARAMETER;
  574. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_ALERT_TYPE);
  575. goto f_err;
  576. }
  577. goto start;
  578. }
  579. if (s->shutdown & SSL_SENT_SHUTDOWN) {
  580. /* close_notify has been sent, so discard all records other than alerts. */
  581. rr->length = 0;
  582. goto start;
  583. }
  584. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  585. /* 'Change Cipher Spec' is just a single byte, so we know exactly what the
  586. * record payload has to look like */
  587. if (rr->length != 1 || rr->off != 0 || rr->data[0] != SSL3_MT_CCS) {
  588. al = SSL_AD_ILLEGAL_PARAMETER;
  589. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  590. goto f_err;
  591. }
  592. /* Check we have a cipher to change to */
  593. if (s->s3->tmp.new_cipher == NULL) {
  594. al = SSL_AD_UNEXPECTED_MESSAGE;
  595. OPENSSL_PUT_ERROR(SSL, SSL_R_CCS_RECEIVED_EARLY);
  596. goto f_err;
  597. }
  598. if (!(s->s3->flags & SSL3_FLAGS_EXPECT_CCS)) {
  599. al = SSL_AD_UNEXPECTED_MESSAGE;
  600. OPENSSL_PUT_ERROR(SSL, SSL_R_CCS_RECEIVED_EARLY);
  601. goto f_err;
  602. }
  603. s->s3->flags &= ~SSL3_FLAGS_EXPECT_CCS;
  604. rr->length = 0;
  605. if (s->msg_callback) {
  606. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
  607. s->msg_callback_arg);
  608. }
  609. s->s3->change_cipher_spec = 1;
  610. if (!ssl3_do_change_cipher_spec(s)) {
  611. goto err;
  612. } else {
  613. goto start;
  614. }
  615. }
  616. /* We already handled these. */
  617. assert(rr->type != SSL3_RT_CHANGE_CIPHER_SPEC && rr->type != SSL3_RT_ALERT &&
  618. rr->type != SSL3_RT_HANDSHAKE);
  619. al = SSL_AD_UNEXPECTED_MESSAGE;
  620. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  621. f_err:
  622. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  623. err:
  624. return -1;
  625. }
  626. int ssl3_do_change_cipher_spec(SSL *s) {
  627. int i;
  628. if (s->state & SSL_ST_ACCEPT) {
  629. i = SSL3_CHANGE_CIPHER_SERVER_READ;
  630. } else {
  631. i = SSL3_CHANGE_CIPHER_CLIENT_READ;
  632. }
  633. if (s->s3->tmp.key_block == NULL) {
  634. if (s->session == NULL || s->session->master_key_length == 0) {
  635. /* might happen if dtls1_read_bytes() calls this */
  636. OPENSSL_PUT_ERROR(SSL, SSL_R_CCS_RECEIVED_EARLY);
  637. return 0;
  638. }
  639. s->session->cipher = s->s3->tmp.new_cipher;
  640. if (!s->enc_method->setup_key_block(s)) {
  641. return 0;
  642. }
  643. }
  644. if (!s->enc_method->change_cipher_state(s, i)) {
  645. return 0;
  646. }
  647. return 1;
  648. }
  649. int ssl3_send_alert(SSL *s, int level, int desc) {
  650. /* Map tls/ssl alert value to correct one */
  651. desc = s->enc_method->alert_value(desc);
  652. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION) {
  653. /* SSL 3.0 does not have protocol_version alerts */
  654. desc = SSL_AD_HANDSHAKE_FAILURE;
  655. }
  656. if (desc < 0) {
  657. return -1;
  658. }
  659. /* If a fatal one, remove from cache */
  660. if (level == 2 && s->session != NULL) {
  661. SSL_CTX_remove_session(s->ctx, s->session);
  662. }
  663. s->s3->alert_dispatch = 1;
  664. s->s3->send_alert[0] = level;
  665. s->s3->send_alert[1] = desc;
  666. if (!ssl_write_buffer_is_pending(s)) {
  667. /* Nothing is being written out, so the alert may be dispatched
  668. * immediately. */
  669. return s->method->ssl_dispatch_alert(s);
  670. }
  671. /* else data is still being written out, we will get written some time in the
  672. * future */
  673. return -1;
  674. }
  675. int ssl3_dispatch_alert(SSL *s) {
  676. int i, j;
  677. void (*cb)(const SSL *ssl, int type, int val) = NULL;
  678. s->s3->alert_dispatch = 0;
  679. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2);
  680. if (i <= 0) {
  681. s->s3->alert_dispatch = 1;
  682. } else {
  683. /* Alert sent to BIO. If it is important, flush it now. If the message
  684. * does not get sent due to non-blocking IO, we will not worry too much. */
  685. if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
  686. BIO_flush(s->wbio);
  687. }
  688. if (s->msg_callback) {
  689. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
  690. s->msg_callback_arg);
  691. }
  692. if (s->info_callback != NULL) {
  693. cb = s->info_callback;
  694. } else if (s->ctx->info_callback != NULL) {
  695. cb = s->ctx->info_callback;
  696. }
  697. if (cb != NULL) {
  698. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  699. cb(s, SSL_CB_WRITE_ALERT, j);
  700. }
  701. }
  702. return i;
  703. }