You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

828 lines
27 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. static int ssl3_write_pending(SSL *s, int type, const uint8_t *buf,
  228. unsigned int len) {
  229. if (s->s3->wpend_tot > (int)len ||
  230. (s->s3->wpend_buf != buf &&
  231. !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) ||
  232. s->s3->wpend_type != type) {
  233. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_WRITE_RETRY);
  234. return -1;
  235. }
  236. int ret = ssl_write_buffer_flush(s);
  237. if (ret <= 0) {
  238. return ret;
  239. }
  240. return s->s3->wpend_ret;
  241. }
  242. /* do_ssl3_write writes an SSL record of the given type. */
  243. static int do_ssl3_write(SSL *s, int type, const uint8_t *buf, unsigned len) {
  244. /* If there is still data from the previous record, flush it. */
  245. if (ssl_write_buffer_is_pending(s)) {
  246. return ssl3_write_pending(s, type, buf, len);
  247. }
  248. /* If we have an alert to send, lets send it */
  249. if (s->s3->alert_dispatch) {
  250. int ret = s->method->ssl_dispatch_alert(s);
  251. if (ret <= 0) {
  252. return ret;
  253. }
  254. /* if it went, fall through and send more stuff */
  255. }
  256. if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
  257. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  258. return -1;
  259. }
  260. if (len == 0) {
  261. return 0;
  262. }
  263. size_t max_out = len + ssl_max_seal_overhead(s);
  264. if (max_out < len) {
  265. OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
  266. return -1;
  267. }
  268. uint8_t *out;
  269. size_t ciphertext_len;
  270. if (!ssl_write_buffer_init(s, &out, max_out) ||
  271. !tls_seal_record(s, out, &ciphertext_len, max_out, type, buf, len)) {
  272. return -1;
  273. }
  274. ssl_write_buffer_set_len(s, ciphertext_len);
  275. /* memorize arguments so that ssl3_write_pending can detect bad write retries
  276. * later */
  277. s->s3->wpend_tot = len;
  278. s->s3->wpend_buf = buf;
  279. s->s3->wpend_type = type;
  280. s->s3->wpend_ret = len;
  281. /* we now just need to write the buffer */
  282. return ssl3_write_pending(s, type, buf, len);
  283. }
  284. /* ssl3_expect_change_cipher_spec informs the record layer that a
  285. * ChangeCipherSpec record is required at this point. If a Handshake record is
  286. * received before ChangeCipherSpec, the connection will fail. Moreover, if
  287. * there are unprocessed handshake bytes, the handshake will also fail and the
  288. * function returns zero. Otherwise, the function returns one. */
  289. int ssl3_expect_change_cipher_spec(SSL *s) {
  290. if (s->s3->handshake_fragment_len > 0 || s->s3->tmp.reuse_message) {
  291. OPENSSL_PUT_ERROR(SSL, SSL_R_UNPROCESSED_HANDSHAKE_DATA);
  292. return 0;
  293. }
  294. s->s3->flags |= SSL3_FLAGS_EXPECT_CCS;
  295. return 1;
  296. }
  297. int ssl3_read_app_data(SSL *ssl, uint8_t *buf, int len, int peek) {
  298. return ssl3_read_bytes(ssl, SSL3_RT_APPLICATION_DATA, buf, len, peek);
  299. }
  300. void ssl3_read_close_notify(SSL *ssl) {
  301. ssl3_read_bytes(ssl, 0, NULL, 0, 0);
  302. }
  303. static int ssl3_can_renegotiate(SSL *ssl) {
  304. switch (ssl->renegotiate_mode) {
  305. case ssl_renegotiate_never:
  306. return 0;
  307. case ssl_renegotiate_once:
  308. return ssl->s3->total_renegotiations == 0;
  309. case ssl_renegotiate_freely:
  310. return 1;
  311. case ssl_renegotiate_ignore:
  312. return 1;
  313. }
  314. assert(0);
  315. return 0;
  316. }
  317. /* Return up to 'len' payload bytes received in 'type' records.
  318. * 'type' is one of the following:
  319. *
  320. * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
  321. * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
  322. * - 0 (during a shutdown, no data has to be returned)
  323. *
  324. * If we don't have stored data to work from, read a SSL/TLS record first
  325. * (possibly multiple records if we still don't have anything to return).
  326. *
  327. * This function must handle any surprises the peer may have for us, such as
  328. * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
  329. * a surprise, but handled as if it were), or renegotiation requests.
  330. * Also if record payloads contain fragments too small to process, we store
  331. * them until there is enough for the respective protocol (the record protocol
  332. * may use arbitrary fragmentation and even interleaving):
  333. * Change cipher spec protocol
  334. * just 1 byte needed, no need for keeping anything stored
  335. * Alert protocol
  336. * 2 bytes needed (AlertLevel, AlertDescription)
  337. * Handshake protocol
  338. * 4 bytes needed (HandshakeType, uint24 length) -- we just have
  339. * to detect unexpected Client Hello and Hello Request messages
  340. * here, anything else is handled by higher layers
  341. * Application data protocol
  342. * none of our business
  343. */
  344. int ssl3_read_bytes(SSL *s, int type, uint8_t *buf, int len, int peek) {
  345. int al, i, ret;
  346. unsigned int n;
  347. SSL3_RECORD *rr;
  348. void (*cb)(const SSL *ssl, int type, int value) = NULL;
  349. if ((type && type != SSL3_RT_APPLICATION_DATA && type != SSL3_RT_HANDSHAKE) ||
  350. (peek && type != SSL3_RT_APPLICATION_DATA)) {
  351. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  352. return -1;
  353. }
  354. if (type == SSL3_RT_HANDSHAKE && s->s3->handshake_fragment_len > 0) {
  355. /* (partially) satisfy request from storage */
  356. uint8_t *src = s->s3->handshake_fragment;
  357. uint8_t *dst = buf;
  358. unsigned int k;
  359. /* peek == 0 */
  360. n = 0;
  361. while (len > 0 && s->s3->handshake_fragment_len > 0) {
  362. *dst++ = *src++;
  363. len--;
  364. s->s3->handshake_fragment_len--;
  365. n++;
  366. }
  367. /* move any remaining fragment bytes: */
  368. for (k = 0; k < s->s3->handshake_fragment_len; k++) {
  369. s->s3->handshake_fragment[k] = *src++;
  370. }
  371. return n;
  372. }
  373. /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
  374. /* This may require multiple iterations. False Start will cause
  375. * |s->handshake_func| to signal success one step early, but the handshake
  376. * must be completely finished before other modes are accepted.
  377. *
  378. * TODO(davidben): Move this check up to a higher level. */
  379. while (!s->in_handshake && SSL_in_init(s)) {
  380. assert(type == SSL3_RT_APPLICATION_DATA);
  381. i = s->handshake_func(s);
  382. if (i < 0) {
  383. return i;
  384. }
  385. if (i == 0) {
  386. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
  387. return -1;
  388. }
  389. }
  390. start:
  391. s->rwstate = SSL_NOTHING;
  392. /* s->s3->rrec.type - is the type of record
  393. * s->s3->rrec.data - data
  394. * s->s3->rrec.off - offset into 'data' for next read
  395. * s->s3->rrec.length - number of bytes. */
  396. rr = &s->s3->rrec;
  397. /* get new packet if necessary */
  398. if (rr->length == 0) {
  399. ret = ssl3_get_record(s);
  400. if (ret <= 0) {
  401. return ret;
  402. }
  403. }
  404. /* we now have a packet which can be read and processed */
  405. /* |change_cipher_spec is set when we receive a ChangeCipherSpec and reset by
  406. * ssl3_get_finished. */
  407. if (s->s3->change_cipher_spec && rr->type != SSL3_RT_HANDSHAKE &&
  408. rr->type != SSL3_RT_ALERT) {
  409. al = SSL_AD_UNEXPECTED_MESSAGE;
  410. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
  411. goto f_err;
  412. }
  413. /* If we are expecting a ChangeCipherSpec, it is illegal to receive a
  414. * Handshake record. */
  415. if (rr->type == SSL3_RT_HANDSHAKE && (s->s3->flags & SSL3_FLAGS_EXPECT_CCS)) {
  416. al = SSL_AD_UNEXPECTED_MESSAGE;
  417. OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_RECORD_BEFORE_CCS);
  418. goto f_err;
  419. }
  420. /* If the other end has shut down, throw anything we read away (even in
  421. * 'peek' mode) */
  422. if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
  423. rr->length = 0;
  424. s->rwstate = SSL_NOTHING;
  425. return 0;
  426. }
  427. if (type != 0 && type == rr->type) {
  428. s->s3->warning_alert_count = 0;
  429. /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
  430. /* make sure that we are not getting application data when we are doing a
  431. * handshake for the first time */
  432. if (SSL_in_init(s) && type == SSL3_RT_APPLICATION_DATA &&
  433. s->aead_read_ctx == NULL) {
  434. /* TODO(davidben): Is this check redundant with the handshake_func
  435. * check? */
  436. al = SSL_AD_UNEXPECTED_MESSAGE;
  437. OPENSSL_PUT_ERROR(SSL, SSL_R_APP_DATA_IN_HANDSHAKE);
  438. goto f_err;
  439. }
  440. /* Discard empty records. */
  441. if (rr->length == 0) {
  442. goto start;
  443. }
  444. if (len <= 0) {
  445. return len;
  446. }
  447. if ((unsigned int)len > rr->length) {
  448. n = rr->length;
  449. } else {
  450. n = (unsigned int)len;
  451. }
  452. memcpy(buf, &(rr->data[rr->off]), n);
  453. if (!peek) {
  454. rr->length -= n;
  455. rr->off += n;
  456. if (rr->length == 0) {
  457. rr->off = 0;
  458. /* The record has been consumed, so we may now clear the buffer. */
  459. ssl_read_buffer_discard(s);
  460. }
  461. }
  462. return n;
  463. }
  464. /* Process unexpected records. */
  465. if (rr->type == SSL3_RT_HANDSHAKE) {
  466. /* If peer renegotiations are disabled, all out-of-order handshake records
  467. * are fatal. Renegotiations as a server are never supported. */
  468. if (s->server || !ssl3_can_renegotiate(s)) {
  469. al = SSL_AD_NO_RENEGOTIATION;
  470. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
  471. goto f_err;
  472. }
  473. /* HelloRequests may be fragmented across multiple records. */
  474. const size_t size = sizeof(s->s3->handshake_fragment);
  475. const size_t avail = size - s->s3->handshake_fragment_len;
  476. const size_t todo = (rr->length < avail) ? rr->length : avail;
  477. memcpy(s->s3->handshake_fragment + s->s3->handshake_fragment_len,
  478. &rr->data[rr->off], todo);
  479. rr->off += todo;
  480. rr->length -= todo;
  481. s->s3->handshake_fragment_len += todo;
  482. if (s->s3->handshake_fragment_len < size) {
  483. goto start; /* fragment was too small */
  484. }
  485. /* Parse out and consume a HelloRequest. */
  486. if (s->s3->handshake_fragment[0] != SSL3_MT_HELLO_REQUEST ||
  487. s->s3->handshake_fragment[1] != 0 ||
  488. s->s3->handshake_fragment[2] != 0 ||
  489. s->s3->handshake_fragment[3] != 0) {
  490. al = SSL_AD_DECODE_ERROR;
  491. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_HELLO_REQUEST);
  492. goto f_err;
  493. }
  494. s->s3->handshake_fragment_len = 0;
  495. if (s->msg_callback) {
  496. s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
  497. s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
  498. }
  499. if (!SSL_is_init_finished(s) || !s->s3->initial_handshake_complete) {
  500. /* This cannot happen. If a handshake is in progress, |type| must be
  501. * |SSL3_RT_HANDSHAKE|. */
  502. assert(0);
  503. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  504. goto err;
  505. }
  506. if (s->renegotiate_mode == ssl_renegotiate_ignore) {
  507. goto start;
  508. }
  509. /* Renegotiation is only supported at quiescent points in the application
  510. * protocol, namely in HTTPS, just before reading the HTTP response. Require
  511. * the record-layer be idle and avoid complexities of sending a handshake
  512. * record while an application_data record is being written. */
  513. if (ssl_write_buffer_is_pending(s)) {
  514. al = SSL_AD_NO_RENEGOTIATION;
  515. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
  516. goto f_err;
  517. }
  518. /* Begin a new handshake. */
  519. s->s3->total_renegotiations++;
  520. s->state = SSL_ST_CONNECT;
  521. i = s->handshake_func(s);
  522. if (i < 0) {
  523. return i;
  524. }
  525. if (i == 0) {
  526. OPENSSL_PUT_ERROR(SSL, SSL_R_SSL_HANDSHAKE_FAILURE);
  527. return -1;
  528. }
  529. /* The handshake completed synchronously. Continue reading records. */
  530. goto start;
  531. }
  532. /* If an alert record, process one alert out of the record. Note that we allow
  533. * a single record to contain multiple alerts. */
  534. if (rr->type == SSL3_RT_ALERT) {
  535. /* Alerts may not be fragmented. */
  536. if (rr->length < 2) {
  537. al = SSL_AD_DECODE_ERROR;
  538. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ALERT);
  539. goto f_err;
  540. }
  541. if (s->msg_callback) {
  542. s->msg_callback(0, s->version, SSL3_RT_ALERT, &rr->data[rr->off], 2, s,
  543. s->msg_callback_arg);
  544. }
  545. const uint8_t alert_level = rr->data[rr->off++];
  546. const uint8_t alert_descr = rr->data[rr->off++];
  547. rr->length -= 2;
  548. if (s->info_callback != NULL) {
  549. cb = s->info_callback;
  550. } else if (s->ctx->info_callback != NULL) {
  551. cb = s->ctx->info_callback;
  552. }
  553. if (cb != NULL) {
  554. uint16_t alert = (alert_level << 8) | alert_descr;
  555. cb(s, SSL_CB_READ_ALERT, alert);
  556. }
  557. if (alert_level == SSL3_AL_WARNING) {
  558. s->s3->warn_alert = alert_descr;
  559. if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
  560. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  561. return 0;
  562. }
  563. /* This is a warning but we receive it if we requested renegotiation and
  564. * the peer denied it. Terminate with a fatal alert because if
  565. * application tried to renegotiatie it presumably had a good reason and
  566. * expects it to succeed.
  567. *
  568. * In future we might have a renegotiation where we don't care if the
  569. * peer refused it where we carry on. */
  570. else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
  571. al = SSL_AD_HANDSHAKE_FAILURE;
  572. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
  573. goto f_err;
  574. }
  575. s->s3->warning_alert_count++;
  576. if (s->s3->warning_alert_count > kMaxWarningAlerts) {
  577. al = SSL_AD_UNEXPECTED_MESSAGE;
  578. OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_WARNING_ALERTS);
  579. goto f_err;
  580. }
  581. } else if (alert_level == SSL3_AL_FATAL) {
  582. char tmp[16];
  583. s->rwstate = SSL_NOTHING;
  584. s->s3->fatal_alert = alert_descr;
  585. OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr);
  586. BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
  587. ERR_add_error_data(2, "SSL alert number ", tmp);
  588. s->shutdown |= SSL_RECEIVED_SHUTDOWN;
  589. SSL_CTX_remove_session(s->ctx, s->session);
  590. return 0;
  591. } else {
  592. al = SSL_AD_ILLEGAL_PARAMETER;
  593. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_ALERT_TYPE);
  594. goto f_err;
  595. }
  596. goto start;
  597. }
  598. if (s->shutdown & SSL_SENT_SHUTDOWN) {
  599. /* close_notify has been sent, so discard all records other than alerts. */
  600. rr->length = 0;
  601. goto start;
  602. }
  603. if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
  604. /* 'Change Cipher Spec' is just a single byte, so we know exactly what the
  605. * record payload has to look like */
  606. if (rr->length != 1 || rr->off != 0 || rr->data[0] != SSL3_MT_CCS) {
  607. al = SSL_AD_ILLEGAL_PARAMETER;
  608. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
  609. goto f_err;
  610. }
  611. /* Check we have a cipher to change to */
  612. if (s->s3->tmp.new_cipher == NULL) {
  613. al = SSL_AD_UNEXPECTED_MESSAGE;
  614. OPENSSL_PUT_ERROR(SSL, SSL_R_CCS_RECEIVED_EARLY);
  615. goto f_err;
  616. }
  617. if (!(s->s3->flags & SSL3_FLAGS_EXPECT_CCS)) {
  618. al = SSL_AD_UNEXPECTED_MESSAGE;
  619. OPENSSL_PUT_ERROR(SSL, SSL_R_CCS_RECEIVED_EARLY);
  620. goto f_err;
  621. }
  622. s->s3->flags &= ~SSL3_FLAGS_EXPECT_CCS;
  623. rr->length = 0;
  624. if (s->msg_callback) {
  625. s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
  626. s->msg_callback_arg);
  627. }
  628. s->s3->change_cipher_spec = 1;
  629. if (!ssl3_do_change_cipher_spec(s)) {
  630. goto err;
  631. } else {
  632. goto start;
  633. }
  634. }
  635. /* We already handled these. */
  636. assert(rr->type != SSL3_RT_CHANGE_CIPHER_SPEC && rr->type != SSL3_RT_ALERT &&
  637. rr->type != SSL3_RT_HANDSHAKE);
  638. al = SSL_AD_UNEXPECTED_MESSAGE;
  639. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
  640. f_err:
  641. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  642. err:
  643. return -1;
  644. }
  645. int ssl3_do_change_cipher_spec(SSL *s) {
  646. int i;
  647. if (s->state & SSL_ST_ACCEPT) {
  648. i = SSL3_CHANGE_CIPHER_SERVER_READ;
  649. } else {
  650. i = SSL3_CHANGE_CIPHER_CLIENT_READ;
  651. }
  652. if (s->s3->tmp.key_block == NULL) {
  653. if (s->session == NULL || s->session->master_key_length == 0) {
  654. /* might happen if dtls1_read_bytes() calls this */
  655. OPENSSL_PUT_ERROR(SSL, SSL_R_CCS_RECEIVED_EARLY);
  656. return 0;
  657. }
  658. s->session->cipher = s->s3->tmp.new_cipher;
  659. if (!s->enc_method->setup_key_block(s)) {
  660. return 0;
  661. }
  662. }
  663. if (!s->enc_method->change_cipher_state(s, i)) {
  664. return 0;
  665. }
  666. return 1;
  667. }
  668. int ssl3_send_alert(SSL *s, int level, int desc) {
  669. /* Map tls/ssl alert value to correct one */
  670. desc = s->enc_method->alert_value(desc);
  671. if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION) {
  672. /* SSL 3.0 does not have protocol_version alerts */
  673. desc = SSL_AD_HANDSHAKE_FAILURE;
  674. }
  675. if (desc < 0) {
  676. return -1;
  677. }
  678. /* If a fatal one, remove from cache */
  679. if (level == 2 && s->session != NULL) {
  680. SSL_CTX_remove_session(s->ctx, s->session);
  681. }
  682. s->s3->alert_dispatch = 1;
  683. s->s3->send_alert[0] = level;
  684. s->s3->send_alert[1] = desc;
  685. if (!ssl_write_buffer_is_pending(s)) {
  686. /* Nothing is being written out, so the alert may be dispatched
  687. * immediately. */
  688. return s->method->ssl_dispatch_alert(s);
  689. }
  690. /* else data is still being written out, we will get written some time in the
  691. * future */
  692. return -1;
  693. }
  694. int ssl3_dispatch_alert(SSL *s) {
  695. int i, j;
  696. void (*cb)(const SSL *ssl, int type, int value) = NULL;
  697. s->s3->alert_dispatch = 0;
  698. i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2);
  699. if (i <= 0) {
  700. s->s3->alert_dispatch = 1;
  701. } else {
  702. /* Alert sent to BIO. If it is important, flush it now. If the message
  703. * does not get sent due to non-blocking IO, we will not worry too much. */
  704. if (s->s3->send_alert[0] == SSL3_AL_FATAL) {
  705. BIO_flush(s->wbio);
  706. }
  707. if (s->msg_callback) {
  708. s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s,
  709. s->msg_callback_arg);
  710. }
  711. if (s->info_callback != NULL) {
  712. cb = s->info_callback;
  713. } else if (s->ctx->info_callback != NULL) {
  714. cb = s->ctx->info_callback;
  715. }
  716. if (cb != NULL) {
  717. j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
  718. cb(s, SSL_CB_WRITE_ALERT, j);
  719. }
  720. }
  721. return i;
  722. }