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.
 
 
 
 
 
 

2226 lines
70 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-2007 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. *
  109. */
  110. /* ====================================================================
  111. * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  112. *
  113. * Portions of the attached software ("Contribution") are developed by
  114. * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
  115. *
  116. * The Contribution is licensed pursuant to the OpenSSL open source
  117. * license provided above.
  118. *
  119. * ECC cipher suite support in OpenSSL originally written by
  120. * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
  121. *
  122. */
  123. /* ====================================================================
  124. * Copyright 2005 Nokia. All rights reserved.
  125. *
  126. * The portions of the attached software ("Contribution") is developed by
  127. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  128. * license.
  129. *
  130. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  131. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  132. * support (see RFC 4279) to OpenSSL.
  133. *
  134. * No patent licenses or other rights except those expressly stated in
  135. * the OpenSSL open source license shall be deemed granted or received
  136. * expressly, by implication, estoppel, or otherwise.
  137. *
  138. * No assurances are provided by Nokia that the Contribution does not
  139. * infringe the patent or other intellectual property rights of any third
  140. * party or that the license provides you with all the necessary rights
  141. * to make use of the Contribution.
  142. *
  143. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  144. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  145. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  146. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  147. * OTHERWISE. */
  148. #include <openssl/ssl.h>
  149. #include <assert.h>
  150. #include <string.h>
  151. #include <openssl/bn.h>
  152. #include <openssl/buf.h>
  153. #include <openssl/bytestring.h>
  154. #include <openssl/cipher.h>
  155. #include <openssl/dh.h>
  156. #include <openssl/ec.h>
  157. #include <openssl/ecdsa.h>
  158. #include <openssl/err.h>
  159. #include <openssl/evp.h>
  160. #include <openssl/hmac.h>
  161. #include <openssl/md5.h>
  162. #include <openssl/mem.h>
  163. #include <openssl/nid.h>
  164. #include <openssl/rand.h>
  165. #include <openssl/sha.h>
  166. #include <openssl/x509.h>
  167. #include "internal.h"
  168. #include "../crypto/internal.h"
  169. #include "../crypto/dh/internal.h"
  170. static int ssl3_get_initial_bytes(SSL *ssl);
  171. static int ssl3_get_v2_client_hello(SSL *ssl);
  172. static int ssl3_get_client_hello(SSL *ssl);
  173. static int ssl3_send_server_hello(SSL *ssl);
  174. static int ssl3_send_server_certificate(SSL *ssl);
  175. static int ssl3_send_certificate_status(SSL *ssl);
  176. static int ssl3_send_server_key_exchange(SSL *ssl);
  177. static int ssl3_send_certificate_request(SSL *ssl);
  178. static int ssl3_send_server_hello_done(SSL *ssl);
  179. static int ssl3_get_client_certificate(SSL *ssl);
  180. static int ssl3_get_client_key_exchange(SSL *ssl);
  181. static int ssl3_get_cert_verify(SSL *ssl);
  182. static int ssl3_get_next_proto(SSL *ssl);
  183. static int ssl3_get_channel_id(SSL *ssl);
  184. static int ssl3_send_new_session_ticket(SSL *ssl);
  185. int ssl3_accept(SSL *ssl) {
  186. BUF_MEM *buf = NULL;
  187. uint32_t alg_a;
  188. int ret = -1;
  189. int state, skip = 0;
  190. assert(ssl->handshake_func == ssl3_accept);
  191. assert(ssl->server);
  192. for (;;) {
  193. state = ssl->state;
  194. switch (ssl->state) {
  195. case SSL_ST_ACCEPT:
  196. ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
  197. if (ssl->init_buf == NULL) {
  198. buf = BUF_MEM_new();
  199. if (!buf || !BUF_MEM_reserve(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
  200. ret = -1;
  201. goto end;
  202. }
  203. ssl->init_buf = buf;
  204. buf = NULL;
  205. }
  206. ssl->init_num = 0;
  207. /* Enable a write buffer. This groups handshake messages within a flight
  208. * into a single write. */
  209. if (!ssl_init_wbio_buffer(ssl)) {
  210. ret = -1;
  211. goto end;
  212. }
  213. if (!ssl3_init_handshake_buffer(ssl)) {
  214. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  215. ret = -1;
  216. goto end;
  217. }
  218. if (!ssl->s3->have_version && !SSL_IS_DTLS(ssl)) {
  219. ssl->state = SSL3_ST_SR_INITIAL_BYTES;
  220. } else {
  221. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  222. }
  223. break;
  224. case SSL3_ST_SR_INITIAL_BYTES:
  225. assert(!SSL_IS_DTLS(ssl));
  226. ret = ssl3_get_initial_bytes(ssl);
  227. if (ret <= 0) {
  228. goto end;
  229. }
  230. /* ssl3_get_initial_bytes sets ssl->state to one of
  231. * SSL3_ST_SR_V2_CLIENT_HELLO or SSL3_ST_SR_CLNT_HELLO_A on success. */
  232. break;
  233. case SSL3_ST_SR_V2_CLIENT_HELLO:
  234. assert(!SSL_IS_DTLS(ssl));
  235. ret = ssl3_get_v2_client_hello(ssl);
  236. if (ret <= 0) {
  237. goto end;
  238. }
  239. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  240. break;
  241. case SSL3_ST_SR_CLNT_HELLO_A:
  242. case SSL3_ST_SR_CLNT_HELLO_B:
  243. case SSL3_ST_SR_CLNT_HELLO_C:
  244. ret = ssl3_get_client_hello(ssl);
  245. if (ret <= 0) {
  246. goto end;
  247. }
  248. ssl->method->received_flight(ssl);
  249. ssl->state = SSL3_ST_SW_SRVR_HELLO_A;
  250. break;
  251. case SSL3_ST_SW_SRVR_HELLO_A:
  252. case SSL3_ST_SW_SRVR_HELLO_B:
  253. ret = ssl3_send_server_hello(ssl);
  254. if (ret <= 0) {
  255. goto end;
  256. }
  257. if (ssl->hit) {
  258. if (ssl->tlsext_ticket_expected) {
  259. ssl->state = SSL3_ST_SW_SESSION_TICKET_A;
  260. } else {
  261. ssl->state = SSL3_ST_SW_CHANGE_A;
  262. }
  263. } else {
  264. ssl->state = SSL3_ST_SW_CERT_A;
  265. }
  266. break;
  267. case SSL3_ST_SW_CERT_A:
  268. case SSL3_ST_SW_CERT_B:
  269. if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
  270. ret = ssl3_send_server_certificate(ssl);
  271. if (ret <= 0) {
  272. goto end;
  273. }
  274. if (ssl->s3->tmp.certificate_status_expected) {
  275. ssl->state = SSL3_ST_SW_CERT_STATUS_A;
  276. } else {
  277. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  278. }
  279. } else {
  280. skip = 1;
  281. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  282. }
  283. break;
  284. case SSL3_ST_SW_CERT_STATUS_A:
  285. case SSL3_ST_SW_CERT_STATUS_B:
  286. ret = ssl3_send_certificate_status(ssl);
  287. if (ret <= 0) {
  288. goto end;
  289. }
  290. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  291. break;
  292. case SSL3_ST_SW_KEY_EXCH_A:
  293. case SSL3_ST_SW_KEY_EXCH_B:
  294. case SSL3_ST_SW_KEY_EXCH_C:
  295. alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  296. /* PSK ciphers send ServerKeyExchange if there is an identity hint. */
  297. if (ssl_cipher_requires_server_key_exchange(ssl->s3->tmp.new_cipher) ||
  298. ((alg_a & SSL_aPSK) && ssl->psk_identity_hint)) {
  299. ret = ssl3_send_server_key_exchange(ssl);
  300. if (ret <= 0) {
  301. goto end;
  302. }
  303. } else {
  304. skip = 1;
  305. }
  306. ssl->state = SSL3_ST_SW_CERT_REQ_A;
  307. break;
  308. case SSL3_ST_SW_CERT_REQ_A:
  309. case SSL3_ST_SW_CERT_REQ_B:
  310. if (ssl->s3->tmp.cert_request) {
  311. ret = ssl3_send_certificate_request(ssl);
  312. if (ret <= 0) {
  313. goto end;
  314. }
  315. } else {
  316. skip = 1;
  317. }
  318. ssl->state = SSL3_ST_SW_SRVR_DONE_A;
  319. break;
  320. case SSL3_ST_SW_SRVR_DONE_A:
  321. case SSL3_ST_SW_SRVR_DONE_B:
  322. ret = ssl3_send_server_hello_done(ssl);
  323. if (ret <= 0) {
  324. goto end;
  325. }
  326. ssl->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
  327. ssl->state = SSL3_ST_SW_FLUSH;
  328. break;
  329. case SSL3_ST_SR_CERT_A:
  330. if (ssl->s3->tmp.cert_request) {
  331. ret = ssl3_get_client_certificate(ssl);
  332. if (ret <= 0) {
  333. goto end;
  334. }
  335. }
  336. ssl->state = SSL3_ST_SR_KEY_EXCH_A;
  337. break;
  338. case SSL3_ST_SR_KEY_EXCH_A:
  339. case SSL3_ST_SR_KEY_EXCH_B:
  340. ret = ssl3_get_client_key_exchange(ssl);
  341. if (ret <= 0) {
  342. goto end;
  343. }
  344. ssl->state = SSL3_ST_SR_CERT_VRFY_A;
  345. break;
  346. case SSL3_ST_SR_CERT_VRFY_A:
  347. ret = ssl3_get_cert_verify(ssl);
  348. if (ret <= 0) {
  349. goto end;
  350. }
  351. ssl->state = SSL3_ST_SR_CHANGE;
  352. break;
  353. case SSL3_ST_SR_CHANGE:
  354. ret = ssl->method->ssl_read_change_cipher_spec(ssl);
  355. if (ret <= 0) {
  356. goto end;
  357. }
  358. if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_SERVER_READ)) {
  359. ret = -1;
  360. goto end;
  361. }
  362. if (ssl->s3->next_proto_neg_seen) {
  363. ssl->state = SSL3_ST_SR_NEXT_PROTO_A;
  364. } else if (ssl->s3->tlsext_channel_id_valid) {
  365. ssl->state = SSL3_ST_SR_CHANNEL_ID_A;
  366. } else {
  367. ssl->state = SSL3_ST_SR_FINISHED_A;
  368. }
  369. break;
  370. case SSL3_ST_SR_NEXT_PROTO_A:
  371. ret = ssl3_get_next_proto(ssl);
  372. if (ret <= 0) {
  373. goto end;
  374. }
  375. if (ssl->s3->tlsext_channel_id_valid) {
  376. ssl->state = SSL3_ST_SR_CHANNEL_ID_A;
  377. } else {
  378. ssl->state = SSL3_ST_SR_FINISHED_A;
  379. }
  380. break;
  381. case SSL3_ST_SR_CHANNEL_ID_A:
  382. ret = ssl3_get_channel_id(ssl);
  383. if (ret <= 0) {
  384. goto end;
  385. }
  386. ssl->state = SSL3_ST_SR_FINISHED_A;
  387. break;
  388. case SSL3_ST_SR_FINISHED_A:
  389. ret = ssl3_get_finished(ssl);
  390. if (ret <= 0) {
  391. goto end;
  392. }
  393. ssl->method->received_flight(ssl);
  394. if (ssl->hit) {
  395. ssl->state = SSL_ST_OK;
  396. } else if (ssl->tlsext_ticket_expected) {
  397. ssl->state = SSL3_ST_SW_SESSION_TICKET_A;
  398. } else {
  399. ssl->state = SSL3_ST_SW_CHANGE_A;
  400. }
  401. /* If this is a full handshake with ChannelID then record the hashshake
  402. * hashes in |ssl->session| in case we need them to verify a ChannelID
  403. * signature on a resumption of this session in the future. */
  404. if (!ssl->hit && ssl->s3->tlsext_channel_id_valid) {
  405. ret = tls1_record_handshake_hashes_for_channel_id(ssl);
  406. if (ret <= 0) {
  407. goto end;
  408. }
  409. }
  410. break;
  411. case SSL3_ST_SW_SESSION_TICKET_A:
  412. case SSL3_ST_SW_SESSION_TICKET_B:
  413. ret = ssl3_send_new_session_ticket(ssl);
  414. if (ret <= 0) {
  415. goto end;
  416. }
  417. ssl->state = SSL3_ST_SW_CHANGE_A;
  418. break;
  419. case SSL3_ST_SW_CHANGE_A:
  420. case SSL3_ST_SW_CHANGE_B:
  421. ret = ssl->method->send_change_cipher_spec(ssl, SSL3_ST_SW_CHANGE_A,
  422. SSL3_ST_SW_CHANGE_B);
  423. if (ret <= 0) {
  424. goto end;
  425. }
  426. ssl->state = SSL3_ST_SW_FINISHED_A;
  427. if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
  428. ret = -1;
  429. goto end;
  430. }
  431. break;
  432. case SSL3_ST_SW_FINISHED_A:
  433. case SSL3_ST_SW_FINISHED_B:
  434. ret = ssl3_send_finished(ssl, SSL3_ST_SW_FINISHED_A,
  435. SSL3_ST_SW_FINISHED_B);
  436. if (ret <= 0) {
  437. goto end;
  438. }
  439. ssl->state = SSL3_ST_SW_FLUSH;
  440. if (ssl->hit) {
  441. ssl->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
  442. } else {
  443. ssl->s3->tmp.next_state = SSL_ST_OK;
  444. }
  445. break;
  446. case SSL3_ST_SW_FLUSH:
  447. if (BIO_flush(ssl->wbio) <= 0) {
  448. ssl->rwstate = SSL_WRITING;
  449. ret = -1;
  450. goto end;
  451. }
  452. ssl->state = ssl->s3->tmp.next_state;
  453. if (ssl->state != SSL_ST_OK) {
  454. ssl->method->expect_flight(ssl);
  455. }
  456. break;
  457. case SSL_ST_OK:
  458. /* clean a few things up */
  459. ssl3_cleanup_key_block(ssl);
  460. /* In DTLS, |init_buf| cannot be released because post-handshake
  461. * retransmit relies on that buffer being available as scratch space.
  462. *
  463. * TODO(davidben): Fix this. */
  464. if (!SSL_IS_DTLS(ssl)) {
  465. BUF_MEM_free(ssl->init_buf);
  466. ssl->init_buf = NULL;
  467. ssl->init_num = 0;
  468. }
  469. /* remove buffering on output */
  470. ssl_free_wbio_buffer(ssl);
  471. /* If we aren't retaining peer certificates then we can discard it
  472. * now. */
  473. if (ssl->ctx->retain_only_sha256_of_client_certs) {
  474. X509_free(ssl->session->peer);
  475. ssl->session->peer = NULL;
  476. sk_X509_pop_free(ssl->session->cert_chain, X509_free);
  477. ssl->session->cert_chain = NULL;
  478. }
  479. if (SSL_IS_DTLS(ssl)) {
  480. ssl->d1->handshake_read_seq = 0;
  481. ssl->d1->handshake_write_seq = 0;
  482. ssl->d1->next_handshake_write_seq = 0;
  483. }
  484. ssl->s3->initial_handshake_complete = 1;
  485. ssl_update_cache(ssl, SSL_SESS_CACHE_SERVER);
  486. ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_DONE, 1);
  487. ret = 1;
  488. goto end;
  489. default:
  490. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  491. ret = -1;
  492. goto end;
  493. }
  494. if (!ssl->s3->tmp.reuse_message && !skip && ssl->state != state) {
  495. int new_state = ssl->state;
  496. ssl->state = state;
  497. ssl_do_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 1);
  498. ssl->state = new_state;
  499. }
  500. skip = 0;
  501. }
  502. end:
  503. BUF_MEM_free(buf);
  504. ssl_do_info_callback(ssl, SSL_CB_ACCEPT_EXIT, ret);
  505. return ret;
  506. }
  507. static int ssl3_get_initial_bytes(SSL *ssl) {
  508. /* Read the first 5 bytes, the size of the TLS record header. This is
  509. * sufficient to detect a V2ClientHello and ensures that we never read beyond
  510. * the first record. */
  511. int ret = ssl_read_buffer_extend_to(ssl, SSL3_RT_HEADER_LENGTH);
  512. if (ret <= 0) {
  513. return ret;
  514. }
  515. assert(ssl_read_buffer_len(ssl) == SSL3_RT_HEADER_LENGTH);
  516. const uint8_t *p = ssl_read_buffer(ssl);
  517. /* Some dedicated error codes for protocol mixups should the application wish
  518. * to interpret them differently. (These do not overlap with ClientHello or
  519. * V2ClientHello.) */
  520. if (strncmp("GET ", (const char *)p, 4) == 0 ||
  521. strncmp("POST ", (const char *)p, 5) == 0 ||
  522. strncmp("HEAD ", (const char *)p, 5) == 0 ||
  523. strncmp("PUT ", (const char *)p, 4) == 0) {
  524. OPENSSL_PUT_ERROR(SSL, SSL_R_HTTP_REQUEST);
  525. return -1;
  526. }
  527. if (strncmp("CONNE", (const char *)p, 5) == 0) {
  528. OPENSSL_PUT_ERROR(SSL, SSL_R_HTTPS_PROXY_REQUEST);
  529. return -1;
  530. }
  531. /* Determine if this is a V2ClientHello. */
  532. if ((p[0] & 0x80) && p[2] == SSL2_MT_CLIENT_HELLO &&
  533. p[3] >= SSL3_VERSION_MAJOR) {
  534. /* This is a V2ClientHello. */
  535. ssl->state = SSL3_ST_SR_V2_CLIENT_HELLO;
  536. return 1;
  537. }
  538. /* Fall through to the standard logic. */
  539. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  540. return 1;
  541. }
  542. static int ssl3_get_v2_client_hello(SSL *ssl) {
  543. const uint8_t *p;
  544. int ret;
  545. CBS v2_client_hello, cipher_specs, session_id, challenge;
  546. size_t msg_length, rand_len;
  547. uint8_t msg_type;
  548. uint16_t version, cipher_spec_length, session_id_length, challenge_length;
  549. CBB client_hello, hello_body, cipher_suites;
  550. uint8_t random[SSL3_RANDOM_SIZE];
  551. /* Determine the length of the V2ClientHello. */
  552. assert(ssl_read_buffer_len(ssl) >= SSL3_RT_HEADER_LENGTH);
  553. p = ssl_read_buffer(ssl);
  554. msg_length = ((p[0] & 0x7f) << 8) | p[1];
  555. if (msg_length > (1024 * 4)) {
  556. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
  557. return -1;
  558. }
  559. if (msg_length < SSL3_RT_HEADER_LENGTH - 2) {
  560. /* Reject lengths that are too short early. We have already read
  561. * |SSL3_RT_HEADER_LENGTH| bytes, so we should not attempt to process an
  562. * (invalid) V2ClientHello which would be shorter than that. */
  563. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_LENGTH_MISMATCH);
  564. return -1;
  565. }
  566. /* Read the remainder of the V2ClientHello. */
  567. ret = ssl_read_buffer_extend_to(ssl, 2 + msg_length);
  568. if (ret <= 0) {
  569. return ret;
  570. }
  571. assert(ssl_read_buffer_len(ssl) == msg_length + 2);
  572. CBS_init(&v2_client_hello, ssl_read_buffer(ssl) + 2, msg_length);
  573. /* The V2ClientHello without the length is incorporated into the handshake
  574. * hash. */
  575. if (!ssl3_update_handshake_hash(ssl, CBS_data(&v2_client_hello),
  576. CBS_len(&v2_client_hello))) {
  577. return -1;
  578. }
  579. ssl_do_msg_callback(ssl, 0 /* read */, SSL2_VERSION, 0,
  580. CBS_data(&v2_client_hello), CBS_len(&v2_client_hello));
  581. if (!CBS_get_u8(&v2_client_hello, &msg_type) ||
  582. !CBS_get_u16(&v2_client_hello, &version) ||
  583. !CBS_get_u16(&v2_client_hello, &cipher_spec_length) ||
  584. !CBS_get_u16(&v2_client_hello, &session_id_length) ||
  585. !CBS_get_u16(&v2_client_hello, &challenge_length) ||
  586. !CBS_get_bytes(&v2_client_hello, &cipher_specs, cipher_spec_length) ||
  587. !CBS_get_bytes(&v2_client_hello, &session_id, session_id_length) ||
  588. !CBS_get_bytes(&v2_client_hello, &challenge, challenge_length) ||
  589. CBS_len(&v2_client_hello) != 0) {
  590. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  591. return -1;
  592. }
  593. /* msg_type has already been checked. */
  594. assert(msg_type == SSL2_MT_CLIENT_HELLO);
  595. /* The client_random is the V2ClientHello challenge. Truncate or
  596. * left-pad with zeros as needed. */
  597. memset(random, 0, SSL3_RANDOM_SIZE);
  598. rand_len = CBS_len(&challenge);
  599. if (rand_len > SSL3_RANDOM_SIZE) {
  600. rand_len = SSL3_RANDOM_SIZE;
  601. }
  602. memcpy(random + (SSL3_RANDOM_SIZE - rand_len), CBS_data(&challenge),
  603. rand_len);
  604. /* Write out an equivalent SSLv3 ClientHello. */
  605. CBB_zero(&client_hello);
  606. if (!CBB_init_fixed(&client_hello, (uint8_t *)ssl->init_buf->data,
  607. ssl->init_buf->max) ||
  608. !CBB_add_u8(&client_hello, SSL3_MT_CLIENT_HELLO) ||
  609. !CBB_add_u24_length_prefixed(&client_hello, &hello_body) ||
  610. !CBB_add_u16(&hello_body, version) ||
  611. !CBB_add_bytes(&hello_body, random, SSL3_RANDOM_SIZE) ||
  612. /* No session id. */
  613. !CBB_add_u8(&hello_body, 0) ||
  614. !CBB_add_u16_length_prefixed(&hello_body, &cipher_suites)) {
  615. CBB_cleanup(&client_hello);
  616. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  617. return -1;
  618. }
  619. /* Copy the cipher suites. */
  620. while (CBS_len(&cipher_specs) > 0) {
  621. uint32_t cipher_spec;
  622. if (!CBS_get_u24(&cipher_specs, &cipher_spec)) {
  623. CBB_cleanup(&client_hello);
  624. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  625. return -1;
  626. }
  627. /* Skip SSLv2 ciphers. */
  628. if ((cipher_spec & 0xff0000) != 0) {
  629. continue;
  630. }
  631. if (!CBB_add_u16(&cipher_suites, cipher_spec)) {
  632. CBB_cleanup(&client_hello);
  633. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  634. return -1;
  635. }
  636. }
  637. /* Add the null compression scheme and finish. */
  638. if (!CBB_add_u8(&hello_body, 1) || !CBB_add_u8(&hello_body, 0) ||
  639. !CBB_finish(&client_hello, NULL, &ssl->init_buf->length)) {
  640. CBB_cleanup(&client_hello);
  641. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  642. return -1;
  643. }
  644. /* Mark the message for "re"-use by the version-specific method. */
  645. ssl->s3->tmp.reuse_message = 1;
  646. ssl->s3->tmp.message_type = SSL3_MT_CLIENT_HELLO;
  647. ssl->s3->tmp.message_complete = 1;
  648. /* Consume and discard the V2ClientHello. */
  649. ssl_read_buffer_consume(ssl, 2 + msg_length);
  650. ssl_read_buffer_discard(ssl);
  651. return 1;
  652. }
  653. static int ssl3_get_client_hello(SSL *ssl) {
  654. int ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
  655. long n;
  656. const SSL_CIPHER *c;
  657. STACK_OF(SSL_CIPHER) *ciphers = NULL;
  658. struct ssl_early_callback_ctx early_ctx;
  659. CBS client_hello;
  660. uint16_t client_version;
  661. CBS client_random, session_id, cipher_suites, compression_methods;
  662. SSL_SESSION *session = NULL;
  663. /* We do this so that we will respond with our native type. If we are TLSv1
  664. * and we get SSLv3, we will respond with TLSv1, This down switching should
  665. * be handled by a different method. If we are SSLv3, we will respond with
  666. * SSLv3, even if prompted with TLSv1. */
  667. switch (ssl->state) {
  668. case SSL3_ST_SR_CLNT_HELLO_A:
  669. n = ssl->method->ssl_get_message(ssl, SSL3_MT_CLIENT_HELLO,
  670. ssl_hash_message, &ok);
  671. if (!ok) {
  672. return n;
  673. }
  674. ssl->state = SSL3_ST_SR_CLNT_HELLO_B;
  675. /* fallthrough */
  676. case SSL3_ST_SR_CLNT_HELLO_B:
  677. case SSL3_ST_SR_CLNT_HELLO_C:
  678. /* We have previously parsed the ClientHello message, and can't call
  679. * ssl_get_message again without hashing the message into the Finished
  680. * digest again. */
  681. n = ssl->init_num;
  682. memset(&early_ctx, 0, sizeof(early_ctx));
  683. early_ctx.ssl = ssl;
  684. early_ctx.client_hello = ssl->init_msg;
  685. early_ctx.client_hello_len = n;
  686. if (!ssl_early_callback_init(&early_ctx)) {
  687. al = SSL_AD_DECODE_ERROR;
  688. OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
  689. goto f_err;
  690. }
  691. if (ssl->state == SSL3_ST_SR_CLNT_HELLO_B &&
  692. ssl->ctx->select_certificate_cb != NULL) {
  693. ssl->state = SSL3_ST_SR_CLNT_HELLO_C;
  694. switch (ssl->ctx->select_certificate_cb(&early_ctx)) {
  695. case 0:
  696. ssl->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
  697. goto err;
  698. case -1:
  699. /* Connection rejected. */
  700. al = SSL_AD_ACCESS_DENIED;
  701. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  702. goto f_err;
  703. default:
  704. /* fallthrough */;
  705. }
  706. }
  707. ssl->state = SSL3_ST_SR_CLNT_HELLO_C;
  708. break;
  709. default:
  710. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  711. return -1;
  712. }
  713. CBS_init(&client_hello, ssl->init_msg, n);
  714. if (!CBS_get_u16(&client_hello, &client_version) ||
  715. !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
  716. !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
  717. CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
  718. al = SSL_AD_DECODE_ERROR;
  719. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  720. goto f_err;
  721. }
  722. /* use version from inside client hello, not from record header (may differ:
  723. * see RFC 2246, Appendix E, second paragraph) */
  724. ssl->client_version = client_version;
  725. /* Load the client random. */
  726. memcpy(ssl->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
  727. if (SSL_IS_DTLS(ssl)) {
  728. CBS cookie;
  729. if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
  730. CBS_len(&cookie) > DTLS1_COOKIE_LENGTH) {
  731. al = SSL_AD_DECODE_ERROR;
  732. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  733. goto f_err;
  734. }
  735. }
  736. /* Note: This codepath may run twice if |ssl_get_prev_session| completes
  737. * asynchronously.
  738. *
  739. * TODO(davidben): Clean up the order of events around ClientHello
  740. * processing. */
  741. if (!ssl->s3->have_version) {
  742. /* Select version to use */
  743. uint16_t version = ssl3_get_mutual_version(ssl, client_version);
  744. if (version == 0) {
  745. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
  746. ssl->version = ssl->client_version;
  747. al = SSL_AD_PROTOCOL_VERSION;
  748. goto f_err;
  749. }
  750. ssl->version = version;
  751. ssl->s3->enc_method = ssl3_get_enc_method(version);
  752. assert(ssl->s3->enc_method != NULL);
  753. /* At this point, the connection's version is known and |ssl->version| is
  754. * fixed. Begin enforcing the record-layer version. */
  755. ssl->s3->have_version = 1;
  756. } else if (SSL_IS_DTLS(ssl) ? (ssl->client_version > ssl->version)
  757. : (ssl->client_version < ssl->version)) {
  758. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_NUMBER);
  759. al = SSL_AD_PROTOCOL_VERSION;
  760. goto f_err;
  761. }
  762. ssl->hit = 0;
  763. int send_new_ticket = 0;
  764. switch (ssl_get_prev_session(ssl, &session, &send_new_ticket, &early_ctx)) {
  765. case ssl_session_success:
  766. break;
  767. case ssl_session_error:
  768. goto err;
  769. case ssl_session_retry:
  770. ssl->rwstate = SSL_PENDING_SESSION;
  771. goto err;
  772. }
  773. ssl->tlsext_ticket_expected = send_new_ticket;
  774. /* The EMS state is needed when making the resumption decision, but
  775. * extensions are not normally parsed until later. This detects the EMS
  776. * extension for the resumption decision and it's checked against the result
  777. * of the normal parse later in this function. */
  778. const uint8_t *ems_data;
  779. size_t ems_len;
  780. int have_extended_master_secret =
  781. ssl->version != SSL3_VERSION &&
  782. SSL_early_callback_ctx_extension_get(&early_ctx,
  783. TLSEXT_TYPE_extended_master_secret,
  784. &ems_data, &ems_len) &&
  785. ems_len == 0;
  786. if (session != NULL) {
  787. if (session->extended_master_secret &&
  788. !have_extended_master_secret) {
  789. /* A ClientHello without EMS that attempts to resume a session with EMS
  790. * is fatal to the connection. */
  791. al = SSL_AD_HANDSHAKE_FAILURE;
  792. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
  793. goto f_err;
  794. }
  795. ssl->hit =
  796. /* Only resume if the session's version matches the negotiated version:
  797. * most clients do not accept a mismatch. */
  798. ssl->version == session->ssl_version &&
  799. /* If the client offers the EMS extension, but the previous session
  800. * didn't use it, then negotiate a new session. */
  801. have_extended_master_secret == session->extended_master_secret;
  802. }
  803. if (ssl->hit) {
  804. /* Use the new session. */
  805. SSL_SESSION_free(ssl->session);
  806. ssl->session = session;
  807. session = NULL;
  808. ssl->verify_result = ssl->session->verify_result;
  809. } else {
  810. if (!ssl_get_new_session(ssl, 1 /* server */)) {
  811. goto err;
  812. }
  813. /* Clear the session ID if we want the session to be single-use. */
  814. if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
  815. ssl->session->session_id_length = 0;
  816. }
  817. }
  818. if (ssl->ctx->dos_protection_cb != NULL &&
  819. ssl->ctx->dos_protection_cb(&early_ctx) == 0) {
  820. /* Connection rejected for DOS reasons. */
  821. al = SSL_AD_ACCESS_DENIED;
  822. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  823. goto f_err;
  824. }
  825. if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
  826. CBS_len(&cipher_suites) == 0 ||
  827. CBS_len(&cipher_suites) % 2 != 0 ||
  828. !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
  829. CBS_len(&compression_methods) == 0) {
  830. al = SSL_AD_DECODE_ERROR;
  831. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  832. goto f_err;
  833. }
  834. ciphers = ssl_bytes_to_cipher_list(ssl, &cipher_suites);
  835. if (ciphers == NULL) {
  836. goto err;
  837. }
  838. /* If it is a hit, check that the cipher is in the list. */
  839. if (ssl->hit) {
  840. size_t j;
  841. int found_cipher = 0;
  842. uint32_t id = ssl->session->cipher->id;
  843. for (j = 0; j < sk_SSL_CIPHER_num(ciphers); j++) {
  844. c = sk_SSL_CIPHER_value(ciphers, j);
  845. if (c->id == id) {
  846. found_cipher = 1;
  847. break;
  848. }
  849. }
  850. if (!found_cipher) {
  851. /* we need to have the cipher in the cipher list if we are asked to reuse
  852. * it */
  853. al = SSL_AD_ILLEGAL_PARAMETER;
  854. OPENSSL_PUT_ERROR(SSL, SSL_R_REQUIRED_CIPHER_MISSING);
  855. goto f_err;
  856. }
  857. }
  858. /* Only null compression is supported. */
  859. if (memchr(CBS_data(&compression_methods), 0,
  860. CBS_len(&compression_methods)) == NULL) {
  861. al = SSL_AD_ILLEGAL_PARAMETER;
  862. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMPRESSION_SPECIFIED);
  863. goto f_err;
  864. }
  865. /* TLS extensions. */
  866. if (ssl->version >= SSL3_VERSION &&
  867. !ssl_parse_clienthello_tlsext(ssl, &client_hello)) {
  868. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  869. goto err;
  870. }
  871. /* There should be nothing left over in the record. */
  872. if (CBS_len(&client_hello) != 0) {
  873. /* wrong packet length */
  874. al = SSL_AD_DECODE_ERROR;
  875. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
  876. goto f_err;
  877. }
  878. if (have_extended_master_secret != ssl->s3->tmp.extended_master_secret) {
  879. al = SSL_AD_INTERNAL_ERROR;
  880. OPENSSL_PUT_ERROR(SSL, SSL_R_EMS_STATE_INCONSISTENT);
  881. goto f_err;
  882. }
  883. /* Given ciphers and SSL_get_ciphers, we must pick a cipher */
  884. if (!ssl->hit) {
  885. if (ciphers == NULL) {
  886. al = SSL_AD_ILLEGAL_PARAMETER;
  887. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_PASSED);
  888. goto f_err;
  889. }
  890. /* Let cert callback update server certificates if required */
  891. if (ssl->cert->cert_cb) {
  892. int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
  893. if (rv == 0) {
  894. al = SSL_AD_INTERNAL_ERROR;
  895. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
  896. goto f_err;
  897. }
  898. if (rv < 0) {
  899. ssl->rwstate = SSL_X509_LOOKUP;
  900. goto err;
  901. }
  902. }
  903. c = ssl3_choose_cipher(ssl, ciphers, ssl_get_cipher_preferences(ssl));
  904. if (c == NULL) {
  905. al = SSL_AD_HANDSHAKE_FAILURE;
  906. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
  907. goto f_err;
  908. }
  909. ssl->session->cipher = c;
  910. ssl->s3->tmp.new_cipher = c;
  911. /* Determine whether to request a client certificate. */
  912. ssl->s3->tmp.cert_request = !!(ssl->verify_mode & SSL_VERIFY_PEER);
  913. /* Only request a certificate if Channel ID isn't negotiated. */
  914. if ((ssl->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
  915. ssl->s3->tlsext_channel_id_valid) {
  916. ssl->s3->tmp.cert_request = 0;
  917. }
  918. /* CertificateRequest may only be sent in certificate-based ciphers. */
  919. if (!ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
  920. ssl->s3->tmp.cert_request = 0;
  921. }
  922. } else {
  923. /* Session-id reuse */
  924. ssl->s3->tmp.new_cipher = ssl->session->cipher;
  925. ssl->s3->tmp.cert_request = 0;
  926. }
  927. /* Now that the cipher is known, initialize the handshake hash. */
  928. if (!ssl3_init_handshake_hash(ssl)) {
  929. goto f_err;
  930. }
  931. /* In TLS 1.2, client authentication requires hashing the handshake transcript
  932. * under a different hash. Otherwise, release the handshake buffer. */
  933. if (!ssl->s3->tmp.cert_request ||
  934. ssl3_protocol_version(ssl) < TLS1_2_VERSION) {
  935. ssl3_free_handshake_buffer(ssl);
  936. }
  937. /* we now have the following setup;
  938. * client_random
  939. * cipher_list - our prefered list of ciphers
  940. * ciphers - the clients prefered list of ciphers
  941. * compression - basically ignored right now
  942. * ssl version is set - sslv3
  943. * ssl->session - The ssl session has been setup.
  944. * ssl->hit - session reuse flag
  945. * ssl->tmp.new_cipher - the new cipher to use. */
  946. ret = 1;
  947. if (0) {
  948. f_err:
  949. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  950. }
  951. err:
  952. sk_SSL_CIPHER_free(ciphers);
  953. SSL_SESSION_free(session);
  954. return ret;
  955. }
  956. static int ssl3_send_server_hello(SSL *ssl) {
  957. if (ssl->state == SSL3_ST_SW_SRVR_HELLO_B) {
  958. return ssl_do_write(ssl);
  959. }
  960. assert(ssl->state == SSL3_ST_SW_SRVR_HELLO_A);
  961. /* We only accept ChannelIDs on connections with ECDHE in order to avoid a
  962. * known attack while we fix ChannelID itself. */
  963. if (ssl->s3->tlsext_channel_id_valid &&
  964. (ssl->s3->tmp.new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
  965. ssl->s3->tlsext_channel_id_valid = 0;
  966. }
  967. /* If this is a resumption and the original handshake didn't support
  968. * ChannelID then we didn't record the original handshake hashes in the
  969. * session and so cannot resume with ChannelIDs. */
  970. if (ssl->hit && ssl->session->original_handshake_hash_len == 0) {
  971. ssl->s3->tlsext_channel_id_valid = 0;
  972. }
  973. if (!ssl_fill_hello_random(ssl->s3->server_random, SSL3_RANDOM_SIZE,
  974. 1 /* server */)) {
  975. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  976. return -1;
  977. }
  978. CBB cbb, session_id;
  979. size_t length;
  980. CBB_zero(&cbb);
  981. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  982. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
  983. !CBB_add_u16(&cbb, ssl->version) ||
  984. !CBB_add_bytes(&cbb, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
  985. !CBB_add_u8_length_prefixed(&cbb, &session_id) ||
  986. !CBB_add_bytes(&session_id, ssl->session->session_id,
  987. ssl->session->session_id_length) ||
  988. !CBB_add_u16(&cbb, ssl_cipher_get_value(ssl->s3->tmp.new_cipher)) ||
  989. !CBB_add_u8(&cbb, 0 /* no compression */) ||
  990. !ssl_add_serverhello_tlsext(ssl, &cbb) ||
  991. !CBB_finish(&cbb, NULL, &length) ||
  992. !ssl_set_handshake_header(ssl, SSL3_MT_SERVER_HELLO, length)) {
  993. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  994. CBB_cleanup(&cbb);
  995. return -1;
  996. }
  997. ssl->state = SSL3_ST_SW_SRVR_HELLO_B;
  998. return ssl_do_write(ssl);
  999. }
  1000. static int ssl3_send_server_certificate(SSL *ssl) {
  1001. if (ssl->state == SSL3_ST_SW_CERT_A) {
  1002. if (!ssl3_output_cert_chain(ssl)) {
  1003. return 0;
  1004. }
  1005. ssl->state = SSL3_ST_SW_CERT_B;
  1006. }
  1007. /* SSL3_ST_SW_CERT_B */
  1008. return ssl_do_write(ssl);
  1009. }
  1010. static int ssl3_send_certificate_status(SSL *ssl) {
  1011. if (ssl->state == SSL3_ST_SW_CERT_STATUS_A) {
  1012. CBB out, ocsp_response;
  1013. size_t length;
  1014. CBB_zero(&out);
  1015. if (!CBB_init_fixed(&out, ssl_handshake_start(ssl),
  1016. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
  1017. !CBB_add_u8(&out, TLSEXT_STATUSTYPE_ocsp) ||
  1018. !CBB_add_u24_length_prefixed(&out, &ocsp_response) ||
  1019. !CBB_add_bytes(&ocsp_response, ssl->ctx->ocsp_response,
  1020. ssl->ctx->ocsp_response_length) ||
  1021. !CBB_finish(&out, NULL, &length) ||
  1022. !ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_STATUS, length)) {
  1023. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1024. CBB_cleanup(&out);
  1025. return -1;
  1026. }
  1027. ssl->state = SSL3_ST_SW_CERT_STATUS_B;
  1028. }
  1029. /* SSL3_ST_SW_CERT_STATUS_B */
  1030. return ssl_do_write(ssl);
  1031. }
  1032. static int ssl3_send_server_key_exchange(SSL *ssl) {
  1033. if (ssl->state == SSL3_ST_SW_KEY_EXCH_C) {
  1034. return ssl_do_write(ssl);
  1035. }
  1036. CBB cbb, child;
  1037. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  1038. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
  1039. goto err;
  1040. }
  1041. if (ssl->state == SSL3_ST_SW_KEY_EXCH_A) {
  1042. /* This is the first iteration, so write parameters. */
  1043. uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
  1044. uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  1045. /* PSK ciphers begin with an identity hint. */
  1046. if (alg_a & SSL_aPSK) {
  1047. size_t len =
  1048. (ssl->psk_identity_hint == NULL) ? 0 : strlen(ssl->psk_identity_hint);
  1049. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1050. !CBB_add_bytes(&child, (const uint8_t *)ssl->psk_identity_hint,
  1051. len)) {
  1052. goto err;
  1053. }
  1054. }
  1055. if (alg_k & SSL_kDHE) {
  1056. /* Determine the group to use. */
  1057. DH *params = ssl->cert->dh_tmp;
  1058. if (params == NULL && ssl->cert->dh_tmp_cb != NULL) {
  1059. params = ssl->cert->dh_tmp_cb(ssl, 0, 1024);
  1060. }
  1061. if (params == NULL) {
  1062. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_DH_KEY);
  1063. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1064. goto err;
  1065. }
  1066. ssl->session->key_exchange_info = DH_num_bits(params);
  1067. /* Set up DH, generate a key, and emit the public half. */
  1068. DH *dh = DHparams_dup(params);
  1069. if (dh == NULL) {
  1070. goto err;
  1071. }
  1072. SSL_ECDH_CTX_init_for_dhe(&ssl->s3->tmp.ecdh_ctx, dh);
  1073. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1074. !BN_bn2cbb_padded(&child, BN_num_bytes(params->p), params->p) ||
  1075. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1076. !BN_bn2cbb_padded(&child, BN_num_bytes(params->g), params->g) ||
  1077. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1078. !SSL_ECDH_CTX_offer(&ssl->s3->tmp.ecdh_ctx, &child)) {
  1079. goto err;
  1080. }
  1081. } else if (alg_k & SSL_kECDHE) {
  1082. /* Determine the group to use. */
  1083. uint16_t group_id;
  1084. if (!tls1_get_shared_group(ssl, &group_id)) {
  1085. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_ECDH_KEY);
  1086. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1087. goto err;
  1088. }
  1089. ssl->session->key_exchange_info = group_id;
  1090. /* Set up ECDH, generate a key, and emit the public half. */
  1091. if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, group_id) ||
  1092. !CBB_add_u8(&cbb, NAMED_CURVE_TYPE) ||
  1093. !CBB_add_u16(&cbb, group_id) ||
  1094. !CBB_add_u8_length_prefixed(&cbb, &child) ||
  1095. !SSL_ECDH_CTX_offer(&ssl->s3->tmp.ecdh_ctx, &child)) {
  1096. goto err;
  1097. }
  1098. } else if (alg_k & SSL_kCECPQ1) {
  1099. if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, SSL_GROUP_CECPQ1) ||
  1100. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1101. !SSL_ECDH_CTX_offer(&ssl->s3->tmp.ecdh_ctx, &child)) {
  1102. goto err;
  1103. }
  1104. } else {
  1105. assert(alg_k & SSL_kPSK);
  1106. }
  1107. /* Otherwise, restore |cbb| from the previous iteration.
  1108. * TODO(davidben): When |ssl->init_buf| is gone, come up with a simpler
  1109. * pattern. Probably keep the |CBB| around in the handshake state. */
  1110. } else if (!CBB_did_write(&cbb, ssl->init_num - SSL_HM_HEADER_LENGTH(ssl))) {
  1111. goto err;
  1112. }
  1113. /* Add a signature. */
  1114. if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
  1115. if (!ssl_has_private_key(ssl)) {
  1116. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1117. goto err;
  1118. }
  1119. const size_t max_sig_len = ssl_private_key_max_signature_len(ssl);
  1120. size_t sig_len;
  1121. enum ssl_private_key_result_t sign_result;
  1122. if (ssl->state == SSL3_ST_SW_KEY_EXCH_A) {
  1123. /* This is the first iteration, so set up the signature. Sample the
  1124. * parameter length before adding a signature algorithm. */
  1125. if (!CBB_flush(&cbb)) {
  1126. goto err;
  1127. }
  1128. size_t params_len = CBB_len(&cbb);
  1129. /* Determine signature algorithm. */
  1130. const EVP_MD *md;
  1131. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1132. md = tls1_choose_signing_digest(ssl);
  1133. if (!tls12_add_sigandhash(ssl, &cbb, md)) {
  1134. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1135. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1136. goto err;
  1137. }
  1138. } else if (ssl_private_key_type(ssl) == EVP_PKEY_RSA) {
  1139. md = EVP_md5_sha1();
  1140. } else {
  1141. md = EVP_sha1();
  1142. }
  1143. /* Compute the digest and sign it. */
  1144. uint8_t digest[EVP_MAX_MD_SIZE];
  1145. unsigned digest_len = 0;
  1146. EVP_MD_CTX md_ctx;
  1147. EVP_MD_CTX_init(&md_ctx);
  1148. int digest_ret =
  1149. EVP_DigestInit_ex(&md_ctx, md, NULL) &&
  1150. EVP_DigestUpdate(&md_ctx, ssl->s3->client_random, SSL3_RANDOM_SIZE) &&
  1151. EVP_DigestUpdate(&md_ctx, ssl->s3->server_random, SSL3_RANDOM_SIZE) &&
  1152. EVP_DigestUpdate(&md_ctx, CBB_data(&cbb), params_len) &&
  1153. EVP_DigestFinal_ex(&md_ctx, digest, &digest_len);
  1154. EVP_MD_CTX_cleanup(&md_ctx);
  1155. uint8_t *ptr;
  1156. if (!digest_ret ||
  1157. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1158. !CBB_reserve(&child, &ptr, max_sig_len)) {
  1159. goto err;
  1160. }
  1161. sign_result = ssl_private_key_sign(ssl, ptr, &sig_len, max_sig_len, md,
  1162. digest, digest_len);
  1163. } else {
  1164. assert(ssl->state == SSL3_ST_SW_KEY_EXCH_B);
  1165. /* Retry the signature. */
  1166. uint8_t *ptr;
  1167. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1168. !CBB_reserve(&child, &ptr, max_sig_len)) {
  1169. goto err;
  1170. }
  1171. sign_result =
  1172. ssl_private_key_sign_complete(ssl, ptr, &sig_len, max_sig_len);
  1173. }
  1174. switch (sign_result) {
  1175. case ssl_private_key_success:
  1176. if (!CBB_did_write(&child, sig_len)) {
  1177. goto err;
  1178. }
  1179. break;
  1180. case ssl_private_key_failure:
  1181. goto err;
  1182. case ssl_private_key_retry:
  1183. /* Discard the unfinished signature and save the state of |cbb| for the
  1184. * next iteration. */
  1185. CBB_discard_child(&cbb);
  1186. ssl->init_num = SSL_HM_HEADER_LENGTH(ssl) + CBB_len(&cbb);
  1187. ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1188. ssl->state = SSL3_ST_SW_KEY_EXCH_B;
  1189. goto err;
  1190. }
  1191. }
  1192. size_t length;
  1193. if (!CBB_finish(&cbb, NULL, &length) ||
  1194. !ssl_set_handshake_header(ssl, SSL3_MT_SERVER_KEY_EXCHANGE, length)) {
  1195. goto err;
  1196. }
  1197. ssl->state = SSL3_ST_SW_KEY_EXCH_C;
  1198. return ssl_do_write(ssl);
  1199. err:
  1200. CBB_cleanup(&cbb);
  1201. return -1;
  1202. }
  1203. static int ssl3_send_certificate_request(SSL *ssl) {
  1204. uint8_t *p, *d;
  1205. size_t i;
  1206. int j, nl, off, n;
  1207. STACK_OF(X509_NAME) *sk = NULL;
  1208. X509_NAME *name;
  1209. BUF_MEM *buf;
  1210. if (ssl->state == SSL3_ST_SW_CERT_REQ_A) {
  1211. buf = ssl->init_buf;
  1212. d = p = ssl_handshake_start(ssl);
  1213. /* get the list of acceptable cert types */
  1214. p++;
  1215. n = ssl3_get_req_cert_type(ssl, p);
  1216. d[0] = n;
  1217. p += n;
  1218. n++;
  1219. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1220. const uint8_t *psigs;
  1221. nl = tls12_get_psigalgs(ssl, &psigs);
  1222. s2n(nl, p);
  1223. memcpy(p, psigs, nl);
  1224. p += nl;
  1225. n += nl + 2;
  1226. }
  1227. off = n;
  1228. p += 2;
  1229. n += 2;
  1230. sk = SSL_get_client_CA_list(ssl);
  1231. nl = 0;
  1232. if (sk != NULL) {
  1233. for (i = 0; i < sk_X509_NAME_num(sk); i++) {
  1234. name = sk_X509_NAME_value(sk, i);
  1235. j = i2d_X509_NAME(name, NULL);
  1236. if (!BUF_MEM_grow_clean(buf, SSL_HM_HEADER_LENGTH(ssl) + n + j + 2)) {
  1237. OPENSSL_PUT_ERROR(SSL, ERR_R_BUF_LIB);
  1238. goto err;
  1239. }
  1240. p = ssl_handshake_start(ssl) + n;
  1241. s2n(j, p);
  1242. i2d_X509_NAME(name, &p);
  1243. n += 2 + j;
  1244. nl += 2 + j;
  1245. }
  1246. }
  1247. /* else no CA names */
  1248. p = ssl_handshake_start(ssl) + off;
  1249. s2n(nl, p);
  1250. if (!ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_REQUEST, n)) {
  1251. goto err;
  1252. }
  1253. ssl->state = SSL3_ST_SW_CERT_REQ_B;
  1254. }
  1255. /* SSL3_ST_SW_CERT_REQ_B */
  1256. return ssl_do_write(ssl);
  1257. err:
  1258. return -1;
  1259. }
  1260. static int ssl3_send_server_hello_done(SSL *ssl) {
  1261. if (ssl->state == SSL3_ST_SW_SRVR_DONE_A) {
  1262. if (!ssl_set_handshake_header(ssl, SSL3_MT_SERVER_HELLO_DONE, 0)) {
  1263. return -1;
  1264. }
  1265. ssl->state = SSL3_ST_SW_SRVR_DONE_B;
  1266. }
  1267. /* SSL3_ST_SW_SRVR_DONE_B */
  1268. return ssl_do_write(ssl);
  1269. }
  1270. static int ssl3_get_client_certificate(SSL *ssl) {
  1271. int ok, al, ret = -1;
  1272. X509 *x = NULL;
  1273. unsigned long n;
  1274. STACK_OF(X509) *sk = NULL;
  1275. SHA256_CTX sha256;
  1276. CBS certificate_msg, certificate_list;
  1277. int is_first_certificate = 1;
  1278. assert(ssl->s3->tmp.cert_request);
  1279. n = ssl->method->ssl_get_message(ssl, -1, ssl_hash_message, &ok);
  1280. if (!ok) {
  1281. return n;
  1282. }
  1283. if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
  1284. if (ssl->version == SSL3_VERSION &&
  1285. ssl->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
  1286. /* In SSL 3.0, the Certificate message is omitted to signal no certificate. */
  1287. if ((ssl->verify_mode & SSL_VERIFY_PEER) &&
  1288. (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  1289. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1290. al = SSL_AD_HANDSHAKE_FAILURE;
  1291. goto f_err;
  1292. }
  1293. ssl->s3->tmp.reuse_message = 1;
  1294. return 1;
  1295. }
  1296. al = SSL_AD_UNEXPECTED_MESSAGE;
  1297. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  1298. goto f_err;
  1299. }
  1300. CBS_init(&certificate_msg, ssl->init_msg, n);
  1301. sk = sk_X509_new_null();
  1302. if (sk == NULL) {
  1303. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1304. goto err;
  1305. }
  1306. if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
  1307. CBS_len(&certificate_msg) != 0) {
  1308. al = SSL_AD_DECODE_ERROR;
  1309. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1310. goto f_err;
  1311. }
  1312. while (CBS_len(&certificate_list) > 0) {
  1313. CBS certificate;
  1314. const uint8_t *data;
  1315. if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
  1316. al = SSL_AD_DECODE_ERROR;
  1317. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1318. goto f_err;
  1319. }
  1320. if (is_first_certificate && ssl->ctx->retain_only_sha256_of_client_certs) {
  1321. /* If this is the first certificate, and we don't want to keep peer
  1322. * certificates in memory, then we hash it right away. */
  1323. SHA256_Init(&sha256);
  1324. SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
  1325. SHA256_Final(ssl->session->peer_sha256, &sha256);
  1326. ssl->session->peer_sha256_valid = 1;
  1327. }
  1328. is_first_certificate = 0;
  1329. /* A u24 length cannot overflow a long. */
  1330. data = CBS_data(&certificate);
  1331. x = d2i_X509(NULL, &data, (long)CBS_len(&certificate));
  1332. if (x == NULL) {
  1333. al = SSL_AD_BAD_CERTIFICATE;
  1334. OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
  1335. goto f_err;
  1336. }
  1337. if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
  1338. al = SSL_AD_DECODE_ERROR;
  1339. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  1340. goto f_err;
  1341. }
  1342. if (!sk_X509_push(sk, x)) {
  1343. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1344. goto err;
  1345. }
  1346. x = NULL;
  1347. }
  1348. if (sk_X509_num(sk) <= 0) {
  1349. /* No client certificate so the handshake buffer may be discarded. */
  1350. ssl3_free_handshake_buffer(ssl);
  1351. /* TLS does not mind 0 certs returned */
  1352. if (ssl->version == SSL3_VERSION) {
  1353. al = SSL_AD_HANDSHAKE_FAILURE;
  1354. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATES_RETURNED);
  1355. goto f_err;
  1356. } else if ((ssl->verify_mode & SSL_VERIFY_PEER) &&
  1357. (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  1358. /* Fail for TLS only if we required a certificate */
  1359. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1360. al = SSL_AD_HANDSHAKE_FAILURE;
  1361. goto f_err;
  1362. }
  1363. } else {
  1364. if (ssl_verify_cert_chain(ssl, sk) <= 0) {
  1365. al = ssl_verify_alarm_type(ssl->verify_result);
  1366. OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
  1367. goto f_err;
  1368. }
  1369. }
  1370. X509_free(ssl->session->peer);
  1371. ssl->session->peer = sk_X509_shift(sk);
  1372. ssl->session->verify_result = ssl->verify_result;
  1373. sk_X509_pop_free(ssl->session->cert_chain, X509_free);
  1374. ssl->session->cert_chain = sk;
  1375. /* Inconsistency alert: cert_chain does *not* include the peer's own
  1376. * certificate, while we do include it in s3_clnt.c */
  1377. sk = NULL;
  1378. ret = 1;
  1379. if (0) {
  1380. f_err:
  1381. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1382. }
  1383. err:
  1384. X509_free(x);
  1385. sk_X509_pop_free(sk, X509_free);
  1386. return ret;
  1387. }
  1388. static int ssl3_get_client_key_exchange(SSL *ssl) {
  1389. int al;
  1390. CBS client_key_exchange;
  1391. uint32_t alg_k;
  1392. uint32_t alg_a;
  1393. uint8_t *premaster_secret = NULL;
  1394. size_t premaster_secret_len = 0;
  1395. uint8_t *decrypt_buf = NULL;
  1396. unsigned psk_len = 0;
  1397. uint8_t psk[PSK_MAX_PSK_LEN];
  1398. if (ssl->state == SSL3_ST_SR_KEY_EXCH_A) {
  1399. int ok;
  1400. const long n = ssl->method->ssl_get_message(
  1401. ssl, SSL3_MT_CLIENT_KEY_EXCHANGE, ssl_hash_message, &ok);
  1402. if (!ok) {
  1403. return n;
  1404. }
  1405. }
  1406. CBS_init(&client_key_exchange, ssl->init_msg, ssl->init_num);
  1407. alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
  1408. alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  1409. /* If using a PSK key exchange, prepare the pre-shared key. */
  1410. if (alg_a & SSL_aPSK) {
  1411. CBS psk_identity;
  1412. /* If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
  1413. * then this is the only field in the message. */
  1414. if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
  1415. ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
  1416. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1417. al = SSL_AD_DECODE_ERROR;
  1418. goto f_err;
  1419. }
  1420. if (ssl->psk_server_callback == NULL) {
  1421. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_SERVER_CB);
  1422. al = SSL_AD_INTERNAL_ERROR;
  1423. goto f_err;
  1424. }
  1425. if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
  1426. CBS_contains_zero_byte(&psk_identity)) {
  1427. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  1428. al = SSL_AD_ILLEGAL_PARAMETER;
  1429. goto f_err;
  1430. }
  1431. if (!CBS_strdup(&psk_identity, &ssl->session->psk_identity)) {
  1432. al = SSL_AD_INTERNAL_ERROR;
  1433. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1434. goto f_err;
  1435. }
  1436. /* Look up the key for the identity. */
  1437. psk_len = ssl->psk_server_callback(ssl, ssl->session->psk_identity, psk,
  1438. sizeof(psk));
  1439. if (psk_len > PSK_MAX_PSK_LEN) {
  1440. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1441. al = SSL_AD_INTERNAL_ERROR;
  1442. goto f_err;
  1443. } else if (psk_len == 0) {
  1444. /* PSK related to the given identity not found */
  1445. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
  1446. al = SSL_AD_UNKNOWN_PSK_IDENTITY;
  1447. goto f_err;
  1448. }
  1449. }
  1450. /* Depending on the key exchange method, compute |premaster_secret| and
  1451. * |premaster_secret_len|. */
  1452. if (alg_k & SSL_kRSA) {
  1453. /* Allocate a buffer large enough for an RSA decryption. */
  1454. const size_t rsa_size = ssl_private_key_max_signature_len(ssl);
  1455. decrypt_buf = OPENSSL_malloc(rsa_size);
  1456. if (decrypt_buf == NULL) {
  1457. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1458. goto err;
  1459. }
  1460. enum ssl_private_key_result_t decrypt_result;
  1461. size_t decrypt_len;
  1462. if (ssl->state == SSL3_ST_SR_KEY_EXCH_A) {
  1463. if (!ssl_has_private_key(ssl) ||
  1464. ssl_private_key_type(ssl) != EVP_PKEY_RSA) {
  1465. al = SSL_AD_HANDSHAKE_FAILURE;
  1466. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_RSA_CERTIFICATE);
  1467. goto f_err;
  1468. }
  1469. CBS encrypted_premaster_secret;
  1470. if (ssl->version > SSL3_VERSION) {
  1471. if (!CBS_get_u16_length_prefixed(&client_key_exchange,
  1472. &encrypted_premaster_secret) ||
  1473. CBS_len(&client_key_exchange) != 0) {
  1474. al = SSL_AD_DECODE_ERROR;
  1475. OPENSSL_PUT_ERROR(SSL,
  1476. SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
  1477. goto f_err;
  1478. }
  1479. } else {
  1480. encrypted_premaster_secret = client_key_exchange;
  1481. }
  1482. /* Decrypt with no padding. PKCS#1 padding will be removed as part of the
  1483. * timing-sensitive code below. */
  1484. decrypt_result = ssl_private_key_decrypt(
  1485. ssl, decrypt_buf, &decrypt_len, rsa_size,
  1486. CBS_data(&encrypted_premaster_secret),
  1487. CBS_len(&encrypted_premaster_secret));
  1488. } else {
  1489. assert(ssl->state == SSL3_ST_SR_KEY_EXCH_B);
  1490. /* Complete async decrypt. */
  1491. decrypt_result = ssl_private_key_decrypt_complete(
  1492. ssl, decrypt_buf, &decrypt_len, rsa_size);
  1493. }
  1494. switch (decrypt_result) {
  1495. case ssl_private_key_success:
  1496. break;
  1497. case ssl_private_key_failure:
  1498. goto err;
  1499. case ssl_private_key_retry:
  1500. ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1501. ssl->state = SSL3_ST_SR_KEY_EXCH_B;
  1502. goto err;
  1503. }
  1504. if (decrypt_len != rsa_size) {
  1505. al = SSL_AD_DECRYPT_ERROR;
  1506. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
  1507. goto f_err;
  1508. }
  1509. /* Prepare a random premaster, to be used on invalid padding. See RFC 5246,
  1510. * section 7.4.7.1. */
  1511. premaster_secret_len = SSL_MAX_MASTER_KEY_LENGTH;
  1512. premaster_secret = OPENSSL_malloc(premaster_secret_len);
  1513. if (premaster_secret == NULL) {
  1514. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1515. goto err;
  1516. }
  1517. if (!RAND_bytes(premaster_secret, premaster_secret_len)) {
  1518. goto err;
  1519. }
  1520. /* The smallest padded premaster is 11 bytes of overhead. Small keys are
  1521. * publicly invalid. */
  1522. if (decrypt_len < 11 + premaster_secret_len) {
  1523. al = SSL_AD_DECRYPT_ERROR;
  1524. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
  1525. goto f_err;
  1526. }
  1527. /* Check the padding. See RFC 3447, section 7.2.2. */
  1528. size_t padding_len = decrypt_len - premaster_secret_len;
  1529. uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
  1530. constant_time_eq_int_8(decrypt_buf[1], 2);
  1531. size_t i;
  1532. for (i = 2; i < padding_len - 1; i++) {
  1533. good &= ~constant_time_is_zero_8(decrypt_buf[i]);
  1534. }
  1535. good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
  1536. /* The premaster secret must begin with |client_version|. This too must be
  1537. * checked in constant time (http://eprint.iacr.org/2003/052/). */
  1538. good &= constant_time_eq_8(decrypt_buf[padding_len],
  1539. (unsigned)(ssl->client_version >> 8));
  1540. good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
  1541. (unsigned)(ssl->client_version & 0xff));
  1542. /* Select, in constant time, either the decrypted premaster or the random
  1543. * premaster based on |good|. */
  1544. for (i = 0; i < premaster_secret_len; i++) {
  1545. premaster_secret[i] = constant_time_select_8(
  1546. good, decrypt_buf[padding_len + i], premaster_secret[i]);
  1547. }
  1548. OPENSSL_free(decrypt_buf);
  1549. decrypt_buf = NULL;
  1550. } else if (alg_k & (SSL_kECDHE|SSL_kDHE|SSL_kCECPQ1)) {
  1551. /* Parse the ClientKeyExchange. */
  1552. CBS peer_key;
  1553. if (!SSL_ECDH_CTX_get_key(&ssl->s3->tmp.ecdh_ctx, &client_key_exchange,
  1554. &peer_key) ||
  1555. CBS_len(&client_key_exchange) != 0) {
  1556. al = SSL_AD_DECODE_ERROR;
  1557. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1558. goto f_err;
  1559. }
  1560. /* Compute the premaster. */
  1561. uint8_t alert;
  1562. if (!SSL_ECDH_CTX_finish(&ssl->s3->tmp.ecdh_ctx, &premaster_secret,
  1563. &premaster_secret_len, &alert, CBS_data(&peer_key),
  1564. CBS_len(&peer_key))) {
  1565. al = alert;
  1566. goto f_err;
  1567. }
  1568. /* The key exchange state may now be discarded. */
  1569. SSL_ECDH_CTX_cleanup(&ssl->s3->tmp.ecdh_ctx);
  1570. } else if (alg_k & SSL_kPSK) {
  1571. /* For plain PSK, other_secret is a block of 0s with the same length as the
  1572. * pre-shared key. */
  1573. premaster_secret_len = psk_len;
  1574. premaster_secret = OPENSSL_malloc(premaster_secret_len);
  1575. if (premaster_secret == NULL) {
  1576. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1577. goto err;
  1578. }
  1579. memset(premaster_secret, 0, premaster_secret_len);
  1580. } else {
  1581. al = SSL_AD_HANDSHAKE_FAILURE;
  1582. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_TYPE);
  1583. goto f_err;
  1584. }
  1585. /* For a PSK cipher suite, the actual pre-master secret is combined with the
  1586. * pre-shared key. */
  1587. if (alg_a & SSL_aPSK) {
  1588. CBB new_premaster, child;
  1589. uint8_t *new_data;
  1590. size_t new_len;
  1591. CBB_zero(&new_premaster);
  1592. if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len) ||
  1593. !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1594. !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
  1595. !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1596. !CBB_add_bytes(&child, psk, psk_len) ||
  1597. !CBB_finish(&new_premaster, &new_data, &new_len)) {
  1598. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1599. CBB_cleanup(&new_premaster);
  1600. goto err;
  1601. }
  1602. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1603. OPENSSL_free(premaster_secret);
  1604. premaster_secret = new_data;
  1605. premaster_secret_len = new_len;
  1606. }
  1607. /* Compute the master secret */
  1608. ssl->session->master_key_length = tls1_generate_master_secret(
  1609. ssl, ssl->session->master_key, premaster_secret, premaster_secret_len);
  1610. if (ssl->session->master_key_length == 0) {
  1611. goto err;
  1612. }
  1613. ssl->session->extended_master_secret = ssl->s3->tmp.extended_master_secret;
  1614. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1615. OPENSSL_free(premaster_secret);
  1616. return 1;
  1617. f_err:
  1618. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1619. err:
  1620. if (premaster_secret != NULL) {
  1621. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1622. OPENSSL_free(premaster_secret);
  1623. }
  1624. OPENSSL_free(decrypt_buf);
  1625. return -1;
  1626. }
  1627. static int ssl3_get_cert_verify(SSL *ssl) {
  1628. int al, ok, ret = 0;
  1629. long n;
  1630. CBS certificate_verify, signature;
  1631. X509 *peer = ssl->session->peer;
  1632. EVP_PKEY *pkey = NULL;
  1633. const EVP_MD *md = NULL;
  1634. uint8_t digest[EVP_MAX_MD_SIZE];
  1635. size_t digest_length;
  1636. EVP_PKEY_CTX *pctx = NULL;
  1637. /* Only RSA and ECDSA client certificates are supported, so a
  1638. * CertificateVerify is required if and only if there's a client certificate.
  1639. * */
  1640. if (peer == NULL) {
  1641. ssl3_free_handshake_buffer(ssl);
  1642. return 1;
  1643. }
  1644. n = ssl->method->ssl_get_message(ssl, SSL3_MT_CERTIFICATE_VERIFY,
  1645. ssl_dont_hash_message, &ok);
  1646. if (!ok) {
  1647. return n;
  1648. }
  1649. /* Filter out unsupported certificate types. */
  1650. pkey = X509_get_pubkey(peer);
  1651. if (pkey == NULL) {
  1652. goto err;
  1653. }
  1654. if (!(X509_certificate_type(peer, pkey) & EVP_PKT_SIGN) ||
  1655. (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_EC)) {
  1656. al = SSL_AD_UNSUPPORTED_CERTIFICATE;
  1657. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
  1658. goto f_err;
  1659. }
  1660. CBS_init(&certificate_verify, ssl->init_msg, n);
  1661. /* Determine the digest type if needbe. */
  1662. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1663. uint8_t hash, signature_type;
  1664. if (!CBS_get_u8(&certificate_verify, &hash) ||
  1665. !CBS_get_u8(&certificate_verify, &signature_type)) {
  1666. al = SSL_AD_DECODE_ERROR;
  1667. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1668. goto f_err;
  1669. }
  1670. if (!tls12_check_peer_sigalg(ssl, &md, &al, hash, signature_type, pkey)) {
  1671. goto f_err;
  1672. }
  1673. }
  1674. /* Compute the digest. */
  1675. if (!ssl3_cert_verify_hash(ssl, digest, &digest_length, &md, pkey->type)) {
  1676. goto err;
  1677. }
  1678. /* The handshake buffer is no longer necessary, and we may hash the current
  1679. * message.*/
  1680. ssl3_free_handshake_buffer(ssl);
  1681. if (!ssl3_hash_current_message(ssl)) {
  1682. goto err;
  1683. }
  1684. /* Parse and verify the signature. */
  1685. if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
  1686. CBS_len(&certificate_verify) != 0) {
  1687. al = SSL_AD_DECODE_ERROR;
  1688. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1689. goto f_err;
  1690. }
  1691. pctx = EVP_PKEY_CTX_new(pkey, NULL);
  1692. if (pctx == NULL) {
  1693. goto err;
  1694. }
  1695. int sig_ok = EVP_PKEY_verify_init(pctx) &&
  1696. EVP_PKEY_CTX_set_signature_md(pctx, md) &&
  1697. EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature),
  1698. digest, digest_length);
  1699. #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
  1700. sig_ok = 1;
  1701. ERR_clear_error();
  1702. #endif
  1703. if (!sig_ok) {
  1704. al = SSL_AD_DECRYPT_ERROR;
  1705. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
  1706. goto f_err;
  1707. }
  1708. ret = 1;
  1709. if (0) {
  1710. f_err:
  1711. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1712. }
  1713. err:
  1714. EVP_PKEY_CTX_free(pctx);
  1715. EVP_PKEY_free(pkey);
  1716. return ret;
  1717. }
  1718. /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
  1719. * sets the next_proto member in s if found */
  1720. static int ssl3_get_next_proto(SSL *ssl) {
  1721. int ok;
  1722. long n;
  1723. CBS next_protocol, selected_protocol, padding;
  1724. /* Clients cannot send a NextProtocol message if we didn't see the extension
  1725. * in their ClientHello */
  1726. if (!ssl->s3->next_proto_neg_seen) {
  1727. OPENSSL_PUT_ERROR(SSL, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
  1728. return -1;
  1729. }
  1730. n = ssl->method->ssl_get_message(ssl, SSL3_MT_NEXT_PROTO, ssl_hash_message,
  1731. &ok);
  1732. if (!ok) {
  1733. return n;
  1734. }
  1735. CBS_init(&next_protocol, ssl->init_msg, n);
  1736. /* The payload looks like:
  1737. * uint8 proto_len;
  1738. * uint8 proto[proto_len];
  1739. * uint8 padding_len;
  1740. * uint8 padding[padding_len]; */
  1741. if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
  1742. !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
  1743. CBS_len(&next_protocol) != 0 ||
  1744. !CBS_stow(&selected_protocol, &ssl->s3->next_proto_negotiated,
  1745. &ssl->s3->next_proto_negotiated_len)) {
  1746. return 0;
  1747. }
  1748. return 1;
  1749. }
  1750. /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
  1751. static int ssl3_get_channel_id(SSL *ssl) {
  1752. int ret = -1, ok;
  1753. long n;
  1754. uint8_t channel_id_hash[EVP_MAX_MD_SIZE];
  1755. size_t channel_id_hash_len;
  1756. const uint8_t *p;
  1757. uint16_t extension_type;
  1758. EC_GROUP *p256 = NULL;
  1759. EC_KEY *key = NULL;
  1760. EC_POINT *point = NULL;
  1761. ECDSA_SIG sig;
  1762. BIGNUM x, y;
  1763. CBS encrypted_extensions, extension;
  1764. n = ssl->method->ssl_get_message(ssl, SSL3_MT_CHANNEL_ID_ENCRYPTED_EXTENSIONS,
  1765. ssl_dont_hash_message, &ok);
  1766. if (!ok) {
  1767. return n;
  1768. }
  1769. /* Before incorporating the EncryptedExtensions message to the handshake
  1770. * hash, compute the hash that should have been signed. */
  1771. if (!tls1_channel_id_hash(ssl, channel_id_hash, &channel_id_hash_len)) {
  1772. return -1;
  1773. }
  1774. assert(channel_id_hash_len == SHA256_DIGEST_LENGTH);
  1775. if (!ssl3_hash_current_message(ssl)) {
  1776. return -1;
  1777. }
  1778. CBS_init(&encrypted_extensions, ssl->init_msg, n);
  1779. /* EncryptedExtensions could include multiple extensions, but the only
  1780. * extension that could be negotiated is ChannelID, so there can only be one
  1781. * entry.
  1782. *
  1783. * The payload looks like:
  1784. * uint16 extension_type
  1785. * uint16 extension_len;
  1786. * uint8 x[32];
  1787. * uint8 y[32];
  1788. * uint8 r[32];
  1789. * uint8 s[32]; */
  1790. if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
  1791. !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
  1792. CBS_len(&encrypted_extensions) != 0 ||
  1793. extension_type != TLSEXT_TYPE_channel_id ||
  1794. CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE) {
  1795. OPENSSL_PUT_ERROR(SSL, SSL_R_INVALID_MESSAGE);
  1796. return -1;
  1797. }
  1798. p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
  1799. if (!p256) {
  1800. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_P256_SUPPORT);
  1801. return -1;
  1802. }
  1803. BN_init(&x);
  1804. BN_init(&y);
  1805. sig.r = BN_new();
  1806. sig.s = BN_new();
  1807. if (sig.r == NULL || sig.s == NULL) {
  1808. goto err;
  1809. }
  1810. p = CBS_data(&extension);
  1811. if (BN_bin2bn(p + 0, 32, &x) == NULL ||
  1812. BN_bin2bn(p + 32, 32, &y) == NULL ||
  1813. BN_bin2bn(p + 64, 32, sig.r) == NULL ||
  1814. BN_bin2bn(p + 96, 32, sig.s) == NULL) {
  1815. goto err;
  1816. }
  1817. point = EC_POINT_new(p256);
  1818. if (!point ||
  1819. !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL)) {
  1820. goto err;
  1821. }
  1822. key = EC_KEY_new();
  1823. if (!key || !EC_KEY_set_group(key, p256) ||
  1824. !EC_KEY_set_public_key(key, point)) {
  1825. goto err;
  1826. }
  1827. /* We stored the handshake hash in |tlsext_channel_id| the first time that we
  1828. * were called. */
  1829. if (!ECDSA_do_verify(channel_id_hash, channel_id_hash_len, &sig, key)) {
  1830. OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
  1831. ssl->s3->tlsext_channel_id_valid = 0;
  1832. goto err;
  1833. }
  1834. memcpy(ssl->s3->tlsext_channel_id, p, 64);
  1835. ret = 1;
  1836. err:
  1837. BN_free(&x);
  1838. BN_free(&y);
  1839. BN_free(sig.r);
  1840. BN_free(sig.s);
  1841. EC_KEY_free(key);
  1842. EC_POINT_free(point);
  1843. EC_GROUP_free(p256);
  1844. return ret;
  1845. }
  1846. /* send a new session ticket (not necessarily for a new session) */
  1847. static int ssl3_send_new_session_ticket(SSL *ssl) {
  1848. int ret = -1;
  1849. uint8_t *session = NULL;
  1850. size_t session_len;
  1851. EVP_CIPHER_CTX ctx;
  1852. HMAC_CTX hctx;
  1853. EVP_CIPHER_CTX_init(&ctx);
  1854. HMAC_CTX_init(&hctx);
  1855. if (ssl->state == SSL3_ST_SW_SESSION_TICKET_A) {
  1856. uint8_t *p, *macstart;
  1857. int len;
  1858. unsigned int hlen;
  1859. SSL_CTX *tctx = ssl->initial_ctx;
  1860. uint8_t iv[EVP_MAX_IV_LENGTH];
  1861. uint8_t key_name[16];
  1862. /* The maximum overhead of encrypting the session is 16 (key name) + IV +
  1863. * one block of encryption overhead + HMAC. */
  1864. const size_t max_ticket_overhead =
  1865. 16 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
  1866. /* Serialize the SSL_SESSION to be encoded into the ticket. */
  1867. if (!SSL_SESSION_to_bytes_for_ticket(ssl->session, &session,
  1868. &session_len)) {
  1869. goto err;
  1870. }
  1871. /* If the session is too long, emit a dummy value rather than abort the
  1872. * connection. */
  1873. if (session_len > 0xFFFF - max_ticket_overhead) {
  1874. static const char kTicketPlaceholder[] = "TICKET TOO LARGE";
  1875. const size_t placeholder_len = strlen(kTicketPlaceholder);
  1876. OPENSSL_free(session);
  1877. session = NULL;
  1878. p = ssl_handshake_start(ssl);
  1879. /* Emit ticket_lifetime_hint. */
  1880. l2n(0, p);
  1881. /* Emit ticket. */
  1882. s2n(placeholder_len, p);
  1883. memcpy(p, kTicketPlaceholder, placeholder_len);
  1884. p += placeholder_len;
  1885. len = p - ssl_handshake_start(ssl);
  1886. if (!ssl_set_handshake_header(ssl, SSL3_MT_NEW_SESSION_TICKET, len)) {
  1887. goto err;
  1888. }
  1889. ssl->state = SSL3_ST_SW_SESSION_TICKET_B;
  1890. return ssl_do_write(ssl);
  1891. }
  1892. /* Grow buffer if need be: the length calculation is as follows:
  1893. * handshake_header_length + 4 (ticket lifetime hint) + 2 (ticket length) +
  1894. * max_ticket_overhead + * session_length */
  1895. if (!BUF_MEM_grow(ssl->init_buf, SSL_HM_HEADER_LENGTH(ssl) + 6 +
  1896. max_ticket_overhead + session_len)) {
  1897. goto err;
  1898. }
  1899. p = ssl_handshake_start(ssl);
  1900. /* Initialize HMAC and cipher contexts. If callback present it does all the
  1901. * work otherwise use generated values from parent ctx. */
  1902. if (tctx->tlsext_ticket_key_cb) {
  1903. if (tctx->tlsext_ticket_key_cb(ssl, key_name, iv, &ctx, &hctx,
  1904. 1 /* encrypt */) < 0) {
  1905. goto err;
  1906. }
  1907. } else {
  1908. if (!RAND_bytes(iv, 16) ||
  1909. !EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
  1910. tctx->tlsext_tick_aes_key, iv) ||
  1911. !HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(),
  1912. NULL)) {
  1913. goto err;
  1914. }
  1915. memcpy(key_name, tctx->tlsext_tick_key_name, 16);
  1916. }
  1917. /* Ticket lifetime hint (advisory only): We leave this unspecified for
  1918. * resumed session (for simplicity), and guess that tickets for new
  1919. * sessions will live as long as their sessions. */
  1920. l2n(ssl->hit ? 0 : ssl->session->timeout, p);
  1921. /* Skip ticket length for now */
  1922. p += 2;
  1923. /* Output key name */
  1924. macstart = p;
  1925. memcpy(p, key_name, 16);
  1926. p += 16;
  1927. /* output IV */
  1928. memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
  1929. p += EVP_CIPHER_CTX_iv_length(&ctx);
  1930. /* Encrypt session data */
  1931. if (!EVP_EncryptUpdate(&ctx, p, &len, session, session_len)) {
  1932. goto err;
  1933. }
  1934. p += len;
  1935. if (!EVP_EncryptFinal_ex(&ctx, p, &len)) {
  1936. goto err;
  1937. }
  1938. p += len;
  1939. if (!HMAC_Update(&hctx, macstart, p - macstart) ||
  1940. !HMAC_Final(&hctx, p, &hlen)) {
  1941. goto err;
  1942. }
  1943. p += hlen;
  1944. /* Now write out lengths: p points to end of data written */
  1945. /* Total length */
  1946. len = p - ssl_handshake_start(ssl);
  1947. /* Skip ticket lifetime hint */
  1948. p = ssl_handshake_start(ssl) + 4;
  1949. s2n(len - 6, p);
  1950. if (!ssl_set_handshake_header(ssl, SSL3_MT_NEW_SESSION_TICKET, len)) {
  1951. goto err;
  1952. }
  1953. ssl->state = SSL3_ST_SW_SESSION_TICKET_B;
  1954. }
  1955. /* SSL3_ST_SW_SESSION_TICKET_B */
  1956. ret = ssl_do_write(ssl);
  1957. err:
  1958. OPENSSL_free(session);
  1959. EVP_CIPHER_CTX_cleanup(&ctx);
  1960. HMAC_CTX_cleanup(&hctx);
  1961. return ret;
  1962. }