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.
 
 
 
 
 
 

2079 lines
64 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. */
  149. #include <openssl/ssl.h>
  150. #include <assert.h>
  151. #include <stdio.h>
  152. #include <string.h>
  153. #include <openssl/bn.h>
  154. #include <openssl/buf.h>
  155. #include <openssl/bytestring.h>
  156. #include <openssl/dh.h>
  157. #include <openssl/ec_key.h>
  158. #include <openssl/ecdsa.h>
  159. #include <openssl/err.h>
  160. #include <openssl/evp.h>
  161. #include <openssl/md5.h>
  162. #include <openssl/mem.h>
  163. #include <openssl/obj.h>
  164. #include <openssl/rand.h>
  165. #include <openssl/x509.h>
  166. #include <openssl/x509v3.h>
  167. #include "internal.h"
  168. #include "../crypto/dh/internal.h"
  169. int ssl3_connect(SSL *ssl) {
  170. BUF_MEM *buf = NULL;
  171. void (*cb)(const SSL *ssl, int type, int value) = NULL;
  172. int ret = -1;
  173. int new_state, state, skip = 0;
  174. assert(ssl->handshake_func == ssl3_connect);
  175. assert(!ssl->server);
  176. assert(!SSL_IS_DTLS(ssl));
  177. ERR_clear_system_error();
  178. if (ssl->info_callback != NULL) {
  179. cb = ssl->info_callback;
  180. } else if (ssl->ctx->info_callback != NULL) {
  181. cb = ssl->ctx->info_callback;
  182. }
  183. ssl->in_handshake++;
  184. for (;;) {
  185. state = ssl->state;
  186. switch (ssl->state) {
  187. case SSL_ST_CONNECT:
  188. if (cb != NULL) {
  189. cb(ssl, SSL_CB_HANDSHAKE_START, 1);
  190. }
  191. if (ssl->init_buf == NULL) {
  192. buf = BUF_MEM_new();
  193. if (buf == NULL ||
  194. !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
  195. ret = -1;
  196. goto end;
  197. }
  198. ssl->init_buf = buf;
  199. buf = NULL;
  200. }
  201. if (!ssl_init_wbio_buffer(ssl, 0)) {
  202. ret = -1;
  203. goto end;
  204. }
  205. /* don't push the buffering BIO quite yet */
  206. if (!ssl3_init_handshake_buffer(ssl)) {
  207. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  208. ret = -1;
  209. goto end;
  210. }
  211. ssl->state = SSL3_ST_CW_CLNT_HELLO_A;
  212. ssl->init_num = 0;
  213. break;
  214. case SSL3_ST_CW_CLNT_HELLO_A:
  215. case SSL3_ST_CW_CLNT_HELLO_B:
  216. ssl->shutdown = 0;
  217. ret = ssl3_send_client_hello(ssl);
  218. if (ret <= 0) {
  219. goto end;
  220. }
  221. ssl->state = SSL3_ST_CR_SRVR_HELLO_A;
  222. ssl->init_num = 0;
  223. /* turn on buffering for the next lot of output */
  224. if (ssl->bbio != ssl->wbio) {
  225. ssl->wbio = BIO_push(ssl->bbio, ssl->wbio);
  226. }
  227. break;
  228. case SSL3_ST_CR_SRVR_HELLO_A:
  229. case SSL3_ST_CR_SRVR_HELLO_B:
  230. ret = ssl3_get_server_hello(ssl);
  231. if (ret <= 0) {
  232. goto end;
  233. }
  234. if (ssl->hit) {
  235. ssl->state = SSL3_ST_CR_CHANGE;
  236. if (ssl->tlsext_ticket_expected) {
  237. /* receive renewed session ticket */
  238. ssl->state = SSL3_ST_CR_SESSION_TICKET_A;
  239. }
  240. } else {
  241. ssl->state = SSL3_ST_CR_CERT_A;
  242. }
  243. ssl->init_num = 0;
  244. break;
  245. case SSL3_ST_CR_CERT_A:
  246. case SSL3_ST_CR_CERT_B:
  247. if (ssl_cipher_has_server_public_key(ssl->s3->tmp.new_cipher)) {
  248. ret = ssl3_get_server_certificate(ssl);
  249. if (ret <= 0) {
  250. goto end;
  251. }
  252. if (ssl->s3->tmp.certificate_status_expected) {
  253. ssl->state = SSL3_ST_CR_CERT_STATUS_A;
  254. } else {
  255. ssl->state = SSL3_ST_VERIFY_SERVER_CERT;
  256. }
  257. } else {
  258. skip = 1;
  259. ssl->state = SSL3_ST_CR_KEY_EXCH_A;
  260. }
  261. ssl->init_num = 0;
  262. break;
  263. case SSL3_ST_VERIFY_SERVER_CERT:
  264. ret = ssl3_verify_server_cert(ssl);
  265. if (ret <= 0) {
  266. goto end;
  267. }
  268. ssl->state = SSL3_ST_CR_KEY_EXCH_A;
  269. ssl->init_num = 0;
  270. break;
  271. case SSL3_ST_CR_KEY_EXCH_A:
  272. case SSL3_ST_CR_KEY_EXCH_B:
  273. ret = ssl3_get_server_key_exchange(ssl);
  274. if (ret <= 0) {
  275. goto end;
  276. }
  277. ssl->state = SSL3_ST_CR_CERT_REQ_A;
  278. ssl->init_num = 0;
  279. break;
  280. case SSL3_ST_CR_CERT_REQ_A:
  281. case SSL3_ST_CR_CERT_REQ_B:
  282. ret = ssl3_get_certificate_request(ssl);
  283. if (ret <= 0) {
  284. goto end;
  285. }
  286. ssl->state = SSL3_ST_CR_SRVR_DONE_A;
  287. ssl->init_num = 0;
  288. break;
  289. case SSL3_ST_CR_SRVR_DONE_A:
  290. case SSL3_ST_CR_SRVR_DONE_B:
  291. ret = ssl3_get_server_done(ssl);
  292. if (ret <= 0) {
  293. goto end;
  294. }
  295. if (ssl->s3->tmp.cert_req) {
  296. ssl->state = SSL3_ST_CW_CERT_A;
  297. } else {
  298. ssl->state = SSL3_ST_CW_KEY_EXCH_A;
  299. }
  300. ssl->init_num = 0;
  301. break;
  302. case SSL3_ST_CW_CERT_A:
  303. case SSL3_ST_CW_CERT_B:
  304. case SSL3_ST_CW_CERT_C:
  305. case SSL3_ST_CW_CERT_D:
  306. ret = ssl3_send_client_certificate(ssl);
  307. if (ret <= 0) {
  308. goto end;
  309. }
  310. ssl->state = SSL3_ST_CW_KEY_EXCH_A;
  311. ssl->init_num = 0;
  312. break;
  313. case SSL3_ST_CW_KEY_EXCH_A:
  314. case SSL3_ST_CW_KEY_EXCH_B:
  315. ret = ssl3_send_client_key_exchange(ssl);
  316. if (ret <= 0) {
  317. goto end;
  318. }
  319. /* For TLS, cert_req is set to 2, so a cert chain
  320. * of nothing is sent, but no verify packet is sent */
  321. if (ssl->s3->tmp.cert_req == 1) {
  322. ssl->state = SSL3_ST_CW_CERT_VRFY_A;
  323. } else {
  324. ssl->state = SSL3_ST_CW_CHANGE_A;
  325. }
  326. ssl->init_num = 0;
  327. break;
  328. case SSL3_ST_CW_CERT_VRFY_A:
  329. case SSL3_ST_CW_CERT_VRFY_B:
  330. case SSL3_ST_CW_CERT_VRFY_C:
  331. ret = ssl3_send_cert_verify(ssl);
  332. if (ret <= 0) {
  333. goto end;
  334. }
  335. ssl->state = SSL3_ST_CW_CHANGE_A;
  336. ssl->init_num = 0;
  337. break;
  338. case SSL3_ST_CW_CHANGE_A:
  339. case SSL3_ST_CW_CHANGE_B:
  340. ret = ssl3_send_change_cipher_spec(ssl, SSL3_ST_CW_CHANGE_A,
  341. SSL3_ST_CW_CHANGE_B);
  342. if (ret <= 0) {
  343. goto end;
  344. }
  345. ssl->state = SSL3_ST_CW_FINISHED_A;
  346. if (ssl->s3->tlsext_channel_id_valid) {
  347. ssl->state = SSL3_ST_CW_CHANNEL_ID_A;
  348. }
  349. if (ssl->s3->next_proto_neg_seen) {
  350. ssl->state = SSL3_ST_CW_NEXT_PROTO_A;
  351. }
  352. ssl->init_num = 0;
  353. if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
  354. ret = -1;
  355. goto end;
  356. }
  357. break;
  358. case SSL3_ST_CW_NEXT_PROTO_A:
  359. case SSL3_ST_CW_NEXT_PROTO_B:
  360. ret = ssl3_send_next_proto(ssl);
  361. if (ret <= 0) {
  362. goto end;
  363. }
  364. if (ssl->s3->tlsext_channel_id_valid) {
  365. ssl->state = SSL3_ST_CW_CHANNEL_ID_A;
  366. } else {
  367. ssl->state = SSL3_ST_CW_FINISHED_A;
  368. }
  369. break;
  370. case SSL3_ST_CW_CHANNEL_ID_A:
  371. case SSL3_ST_CW_CHANNEL_ID_B:
  372. ret = ssl3_send_channel_id(ssl);
  373. if (ret <= 0) {
  374. goto end;
  375. }
  376. ssl->state = SSL3_ST_CW_FINISHED_A;
  377. break;
  378. case SSL3_ST_CW_FINISHED_A:
  379. case SSL3_ST_CW_FINISHED_B:
  380. ret = ssl3_send_finished(ssl, SSL3_ST_CW_FINISHED_A,
  381. SSL3_ST_CW_FINISHED_B);
  382. if (ret <= 0) {
  383. goto end;
  384. }
  385. ssl->state = SSL3_ST_CW_FLUSH;
  386. if (ssl->hit) {
  387. ssl->s3->tmp.next_state = SSL_ST_OK;
  388. } else {
  389. /* This is a non-resumption handshake. If it involves ChannelID, then
  390. * record the handshake hashes at this point in the session so that
  391. * any resumption of this session with ChannelID can sign those
  392. * hashes. */
  393. ret = tls1_record_handshake_hashes_for_channel_id(ssl);
  394. if (ret <= 0) {
  395. goto end;
  396. }
  397. if ((SSL_get_mode(ssl) & SSL_MODE_ENABLE_FALSE_START) &&
  398. ssl3_can_false_start(ssl) &&
  399. /* No False Start on renegotiation (would complicate the state
  400. * machine). */
  401. !ssl->s3->initial_handshake_complete) {
  402. ssl->s3->tmp.next_state = SSL3_ST_FALSE_START;
  403. } else {
  404. /* Allow NewSessionTicket if ticket expected */
  405. if (ssl->tlsext_ticket_expected) {
  406. ssl->s3->tmp.next_state = SSL3_ST_CR_SESSION_TICKET_A;
  407. } else {
  408. ssl->s3->tmp.next_state = SSL3_ST_CR_CHANGE;
  409. }
  410. }
  411. }
  412. ssl->init_num = 0;
  413. break;
  414. case SSL3_ST_CR_SESSION_TICKET_A:
  415. case SSL3_ST_CR_SESSION_TICKET_B:
  416. ret = ssl3_get_new_session_ticket(ssl);
  417. if (ret <= 0) {
  418. goto end;
  419. }
  420. ssl->state = SSL3_ST_CR_CHANGE;
  421. ssl->init_num = 0;
  422. break;
  423. case SSL3_ST_CR_CERT_STATUS_A:
  424. case SSL3_ST_CR_CERT_STATUS_B:
  425. ret = ssl3_get_cert_status(ssl);
  426. if (ret <= 0) {
  427. goto end;
  428. }
  429. ssl->state = SSL3_ST_VERIFY_SERVER_CERT;
  430. ssl->init_num = 0;
  431. break;
  432. case SSL3_ST_CR_CHANGE:
  433. ret = ssl->method->ssl_read_change_cipher_spec(ssl);
  434. if (ret <= 0) {
  435. goto end;
  436. }
  437. if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_CLIENT_READ)) {
  438. ret = -1;
  439. goto end;
  440. }
  441. ssl->state = SSL3_ST_CR_FINISHED_A;
  442. break;
  443. case SSL3_ST_CR_FINISHED_A:
  444. case SSL3_ST_CR_FINISHED_B:
  445. ret = ssl3_get_finished(ssl, SSL3_ST_CR_FINISHED_A,
  446. SSL3_ST_CR_FINISHED_B);
  447. if (ret <= 0) {
  448. goto end;
  449. }
  450. if (ssl->hit) {
  451. ssl->state = SSL3_ST_CW_CHANGE_A;
  452. } else {
  453. ssl->state = SSL_ST_OK;
  454. }
  455. ssl->init_num = 0;
  456. break;
  457. case SSL3_ST_CW_FLUSH:
  458. ssl->rwstate = SSL_WRITING;
  459. if (BIO_flush(ssl->wbio) <= 0) {
  460. ret = -1;
  461. goto end;
  462. }
  463. ssl->rwstate = SSL_NOTHING;
  464. ssl->state = ssl->s3->tmp.next_state;
  465. break;
  466. case SSL3_ST_FALSE_START:
  467. /* Allow NewSessionTicket if ticket expected */
  468. if (ssl->tlsext_ticket_expected) {
  469. ssl->state = SSL3_ST_CR_SESSION_TICKET_A;
  470. } else {
  471. ssl->state = SSL3_ST_CR_CHANGE;
  472. }
  473. ssl->s3->tmp.in_false_start = 1;
  474. ssl_free_wbio_buffer(ssl);
  475. ret = 1;
  476. goto end;
  477. case SSL_ST_OK:
  478. /* clean a few things up */
  479. ssl3_cleanup_key_block(ssl);
  480. BUF_MEM_free(ssl->init_buf);
  481. ssl->init_buf = NULL;
  482. /* Remove write buffering now. */
  483. ssl_free_wbio_buffer(ssl);
  484. const int is_initial_handshake = !ssl->s3->initial_handshake_complete;
  485. ssl->init_num = 0;
  486. ssl->s3->tmp.in_false_start = 0;
  487. ssl->s3->initial_handshake_complete = 1;
  488. if (is_initial_handshake) {
  489. /* Renegotiations do not participate in session resumption. */
  490. ssl_update_cache(ssl, SSL_SESS_CACHE_CLIENT);
  491. }
  492. ret = 1;
  493. /* ssl->server=0; */
  494. if (cb != NULL) {
  495. cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
  496. }
  497. goto end;
  498. default:
  499. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  500. ret = -1;
  501. goto end;
  502. }
  503. if (!ssl->s3->tmp.reuse_message && !skip) {
  504. if (cb != NULL && ssl->state != state) {
  505. new_state = ssl->state;
  506. ssl->state = state;
  507. cb(ssl, SSL_CB_CONNECT_LOOP, 1);
  508. ssl->state = new_state;
  509. }
  510. }
  511. skip = 0;
  512. }
  513. end:
  514. ssl->in_handshake--;
  515. BUF_MEM_free(buf);
  516. if (cb != NULL) {
  517. cb(ssl, SSL_CB_CONNECT_EXIT, ret);
  518. }
  519. return ret;
  520. }
  521. static int ssl3_write_client_cipher_list(SSL *ssl, CBB *out) {
  522. /* Prepare disabled cipher masks. */
  523. ssl_set_client_disabled(ssl);
  524. CBB child;
  525. if (!CBB_add_u16_length_prefixed(out, &child)) {
  526. return 0;
  527. }
  528. STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
  529. int any_enabled = 0;
  530. size_t i;
  531. for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
  532. const SSL_CIPHER *cipher = sk_SSL_CIPHER_value(ciphers, i);
  533. /* Skip disabled ciphers */
  534. if ((cipher->algorithm_mkey & ssl->cert->mask_k) ||
  535. (cipher->algorithm_auth & ssl->cert->mask_a)) {
  536. continue;
  537. }
  538. if (SSL_CIPHER_get_min_version(cipher) >
  539. ssl3_version_from_wire(ssl, ssl->client_version)) {
  540. continue;
  541. }
  542. any_enabled = 1;
  543. if (!CBB_add_u16(&child, ssl_cipher_get_value(cipher))) {
  544. return 0;
  545. }
  546. }
  547. /* If all ciphers were disabled, return the error to the caller. */
  548. if (!any_enabled) {
  549. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
  550. return 0;
  551. }
  552. /* For SSLv3, the SCSV is added. Otherwise the renegotiation extension is
  553. * added. */
  554. if (ssl->client_version == SSL3_VERSION &&
  555. !ssl->s3->initial_handshake_complete) {
  556. if (!CBB_add_u16(&child, SSL3_CK_SCSV & 0xffff)) {
  557. return 0;
  558. }
  559. /* The renegotiation extension is required to be at index zero. */
  560. ssl->s3->tmp.extensions.sent |= (1u << 0);
  561. }
  562. if ((ssl->mode & SSL_MODE_SEND_FALLBACK_SCSV) &&
  563. !CBB_add_u16(&child, SSL3_CK_FALLBACK_SCSV & 0xffff)) {
  564. return 0;
  565. }
  566. return CBB_flush(out);
  567. }
  568. int ssl3_send_client_hello(SSL *ssl) {
  569. if (ssl->state == SSL3_ST_CW_CLNT_HELLO_B) {
  570. return ssl_do_write(ssl);
  571. }
  572. /* In DTLS, reset the handshake buffer each time a new ClientHello is
  573. * assembled. We may send multiple if we receive HelloVerifyRequest. */
  574. if (SSL_IS_DTLS(ssl) && !ssl3_init_handshake_buffer(ssl)) {
  575. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  576. return -1;
  577. }
  578. CBB cbb;
  579. CBB_zero(&cbb);
  580. assert(ssl->state == SSL3_ST_CW_CLNT_HELLO_A);
  581. if (!ssl->s3->have_version) {
  582. uint16_t max_version = ssl3_get_max_client_version(ssl);
  583. /* Disabling all versions is silly: return an error. */
  584. if (max_version == 0) {
  585. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
  586. goto err;
  587. }
  588. ssl->version = max_version;
  589. /* Only set |ssl->client_version| on the initial handshake. Renegotiations,
  590. * although locked to a version, reuse the value. When using the plain RSA
  591. * key exchange, the ClientHello version is checked in the premaster secret.
  592. * Some servers fail when this value changes. */
  593. ssl->client_version = max_version;
  594. }
  595. /* If the configured session has expired or was created at a version higher
  596. * than our maximum version, drop it. */
  597. if (ssl->session != NULL &&
  598. (ssl->session->session_id_length == 0 || ssl->session->not_resumable ||
  599. ssl->session->timeout < (long)(time(NULL) - ssl->session->time) ||
  600. (!SSL_IS_DTLS(ssl) && ssl->session->ssl_version > ssl->version) ||
  601. (SSL_IS_DTLS(ssl) && ssl->session->ssl_version < ssl->version))) {
  602. SSL_set_session(ssl, NULL);
  603. }
  604. /* If resending the ClientHello in DTLS after a HelloVerifyRequest, don't
  605. * renegerate the client_random. The random must be reused. */
  606. if ((!SSL_IS_DTLS(ssl) || !ssl->d1->send_cookie) &&
  607. !ssl_fill_hello_random(ssl->s3->client_random,
  608. sizeof(ssl->s3->client_random), 0 /* client */)) {
  609. goto err;
  610. }
  611. /* Renegotiations do not participate in session resumption. */
  612. int has_session = ssl->session != NULL &&
  613. !ssl->s3->initial_handshake_complete;
  614. CBB child;
  615. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  616. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
  617. !CBB_add_u16(&cbb, ssl->client_version) ||
  618. !CBB_add_bytes(&cbb, ssl->s3->client_random, SSL3_RANDOM_SIZE) ||
  619. !CBB_add_u8_length_prefixed(&cbb, &child) ||
  620. (has_session &&
  621. !CBB_add_bytes(&child, ssl->session->session_id,
  622. ssl->session->session_id_length))) {
  623. goto err;
  624. }
  625. if (SSL_IS_DTLS(ssl)) {
  626. if (!CBB_add_u8_length_prefixed(&cbb, &child) ||
  627. !CBB_add_bytes(&child, ssl->d1->cookie, ssl->d1->cookie_len)) {
  628. goto err;
  629. }
  630. }
  631. size_t length;
  632. if (!ssl3_write_client_cipher_list(ssl, &cbb) ||
  633. !CBB_add_u8(&cbb, 1 /* one compression method */) ||
  634. !CBB_add_u8(&cbb, 0 /* null compression */) ||
  635. !ssl_add_clienthello_tlsext(ssl, &cbb,
  636. CBB_len(&cbb) + SSL_HM_HEADER_LENGTH(ssl)) ||
  637. !CBB_finish(&cbb, NULL, &length) ||
  638. !ssl_set_handshake_header(ssl, SSL3_MT_CLIENT_HELLO, length)) {
  639. goto err;
  640. }
  641. ssl->state = SSL3_ST_CW_CLNT_HELLO_B;
  642. return ssl_do_write(ssl);
  643. err:
  644. CBB_cleanup(&cbb);
  645. return -1;
  646. }
  647. int ssl3_get_server_hello(SSL *ssl) {
  648. STACK_OF(SSL_CIPHER) *sk;
  649. const SSL_CIPHER *c;
  650. CERT *ct = ssl->cert;
  651. int al = SSL_AD_INTERNAL_ERROR, ok;
  652. long n;
  653. CBS server_hello, server_random, session_id;
  654. uint16_t server_version, cipher_suite;
  655. uint8_t compression_method;
  656. n = ssl->method->ssl_get_message(ssl, SSL3_ST_CR_SRVR_HELLO_A,
  657. SSL3_ST_CR_SRVR_HELLO_B, SSL3_MT_SERVER_HELLO,
  658. 20000, /* ?? */
  659. ssl_hash_message, &ok);
  660. if (!ok) {
  661. uint32_t err = ERR_peek_error();
  662. if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
  663. ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
  664. /* Add a dedicated error code to the queue for a handshake_failure alert
  665. * in response to ClientHello. This matches NSS's client behavior and
  666. * gives a better error on a (probable) failure to negotiate initial
  667. * parameters. Note: this error code comes after the original one.
  668. *
  669. * See https://crbug.com/446505. */
  670. OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
  671. }
  672. return n;
  673. }
  674. CBS_init(&server_hello, ssl->init_msg, n);
  675. if (!CBS_get_u16(&server_hello, &server_version) ||
  676. !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
  677. !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
  678. CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
  679. !CBS_get_u16(&server_hello, &cipher_suite) ||
  680. !CBS_get_u8(&server_hello, &compression_method)) {
  681. al = SSL_AD_DECODE_ERROR;
  682. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  683. goto f_err;
  684. }
  685. assert(ssl->s3->have_version == ssl->s3->initial_handshake_complete);
  686. if (!ssl->s3->have_version) {
  687. if (!ssl3_is_version_enabled(ssl, server_version)) {
  688. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
  689. ssl->version = server_version;
  690. /* Mark the version as fixed so the record-layer version is not clamped
  691. * to TLS 1.0. */
  692. ssl->s3->have_version = 1;
  693. al = SSL_AD_PROTOCOL_VERSION;
  694. goto f_err;
  695. }
  696. ssl->version = server_version;
  697. ssl->s3->enc_method = ssl3_get_enc_method(server_version);
  698. assert(ssl->s3->enc_method != NULL);
  699. /* At this point, the connection's version is known and ssl->version is
  700. * fixed. Begin enforcing the record-layer version. */
  701. ssl->s3->have_version = 1;
  702. } else if (server_version != ssl->version) {
  703. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
  704. al = SSL_AD_PROTOCOL_VERSION;
  705. goto f_err;
  706. }
  707. /* Copy over the server random. */
  708. memcpy(ssl->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
  709. assert(ssl->session == NULL || ssl->session->session_id_length > 0);
  710. if (!ssl->s3->initial_handshake_complete && ssl->session != NULL &&
  711. CBS_mem_equal(&session_id, ssl->session->session_id,
  712. ssl->session->session_id_length)) {
  713. if (ssl->sid_ctx_length != ssl->session->sid_ctx_length ||
  714. memcmp(ssl->session->sid_ctx, ssl->sid_ctx, ssl->sid_ctx_length)) {
  715. /* actually a client application bug */
  716. al = SSL_AD_ILLEGAL_PARAMETER;
  717. OPENSSL_PUT_ERROR(SSL,
  718. SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
  719. goto f_err;
  720. }
  721. ssl->hit = 1;
  722. } else {
  723. /* The session wasn't resumed. Create a fresh SSL_SESSION to
  724. * fill out. */
  725. ssl->hit = 0;
  726. if (!ssl_get_new_session(ssl, 0 /* client */)) {
  727. goto f_err;
  728. }
  729. /* Note: session_id could be empty. */
  730. ssl->session->session_id_length = CBS_len(&session_id);
  731. memcpy(ssl->session->session_id, CBS_data(&session_id),
  732. CBS_len(&session_id));
  733. }
  734. c = SSL_get_cipher_by_value(cipher_suite);
  735. if (c == NULL) {
  736. /* unknown cipher */
  737. al = SSL_AD_ILLEGAL_PARAMETER;
  738. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
  739. goto f_err;
  740. }
  741. /* If the cipher is disabled then we didn't sent it in the ClientHello, so if
  742. * the server selected it, it's an error. */
  743. if ((c->algorithm_mkey & ct->mask_k) || (c->algorithm_auth & ct->mask_a) ||
  744. SSL_CIPHER_get_min_version(c) > ssl3_protocol_version(ssl)) {
  745. al = SSL_AD_ILLEGAL_PARAMETER;
  746. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
  747. goto f_err;
  748. }
  749. sk = ssl_get_ciphers_by_id(ssl);
  750. if (!sk_SSL_CIPHER_find(sk, NULL, c)) {
  751. /* we did not say we would use this cipher */
  752. al = SSL_AD_ILLEGAL_PARAMETER;
  753. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
  754. goto f_err;
  755. }
  756. if (ssl->hit) {
  757. if (ssl->session->cipher != c) {
  758. al = SSL_AD_ILLEGAL_PARAMETER;
  759. OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
  760. goto f_err;
  761. }
  762. if (ssl->session->ssl_version != ssl->version) {
  763. al = SSL_AD_ILLEGAL_PARAMETER;
  764. OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
  765. goto f_err;
  766. }
  767. } else {
  768. ssl->session->cipher = c;
  769. }
  770. ssl->s3->tmp.new_cipher = c;
  771. /* Now that the cipher is known, initialize the handshake hash. */
  772. if (!ssl3_init_handshake_hash(ssl)) {
  773. goto f_err;
  774. }
  775. /* If doing a full handshake with TLS 1.2, the server may request a client
  776. * certificate which requires hashing the handshake transcript under a
  777. * different hash. Otherwise, the handshake buffer may be released. */
  778. if (ssl->hit || ssl3_protocol_version(ssl) < TLS1_2_VERSION) {
  779. ssl3_free_handshake_buffer(ssl);
  780. }
  781. /* Only the NULL compression algorithm is supported. */
  782. if (compression_method != 0) {
  783. al = SSL_AD_ILLEGAL_PARAMETER;
  784. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
  785. goto f_err;
  786. }
  787. /* TLS extensions */
  788. if (!ssl_parse_serverhello_tlsext(ssl, &server_hello)) {
  789. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  790. goto err;
  791. }
  792. /* There should be nothing left over in the record. */
  793. if (CBS_len(&server_hello) != 0) {
  794. /* wrong packet length */
  795. al = SSL_AD_DECODE_ERROR;
  796. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
  797. goto f_err;
  798. }
  799. if (ssl->hit &&
  800. ssl->s3->tmp.extended_master_secret !=
  801. ssl->session->extended_master_secret) {
  802. al = SSL_AD_HANDSHAKE_FAILURE;
  803. if (ssl->session->extended_master_secret) {
  804. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
  805. } else {
  806. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
  807. }
  808. goto f_err;
  809. }
  810. return 1;
  811. f_err:
  812. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  813. err:
  814. return -1;
  815. }
  816. /* ssl3_check_leaf_certificate returns one if |leaf| is a suitable leaf server
  817. * certificate for |ssl|. Otherwise, it returns zero and pushes an error on the
  818. * error queue. */
  819. static int ssl3_check_leaf_certificate(SSL *ssl, X509 *leaf) {
  820. int ret = 0;
  821. EVP_PKEY *pkey = X509_get_pubkey(leaf);
  822. if (pkey == NULL) {
  823. goto err;
  824. }
  825. /* Check the certificate's type matches the cipher. */
  826. const SSL_CIPHER *cipher = ssl->s3->tmp.new_cipher;
  827. int expected_type = ssl_cipher_get_key_type(cipher);
  828. assert(expected_type != EVP_PKEY_NONE);
  829. if (pkey->type != expected_type) {
  830. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CERTIFICATE_TYPE);
  831. goto err;
  832. }
  833. if (cipher->algorithm_auth & SSL_aECDSA) {
  834. /* TODO(davidben): This behavior is preserved from upstream. Should key
  835. * usages be checked in other cases as well? */
  836. /* This call populates the ex_flags field correctly */
  837. X509_check_purpose(leaf, -1, 0);
  838. if ((leaf->ex_flags & EXFLAG_KUSAGE) &&
  839. !(leaf->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE)) {
  840. OPENSSL_PUT_ERROR(SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
  841. goto err;
  842. }
  843. if (!tls1_check_ec_cert(ssl, leaf)) {
  844. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECC_CERT);
  845. goto err;
  846. }
  847. }
  848. ret = 1;
  849. err:
  850. EVP_PKEY_free(pkey);
  851. return ret;
  852. }
  853. int ssl3_get_server_certificate(SSL *ssl) {
  854. int al, ok, ret = -1;
  855. unsigned long n;
  856. X509 *x = NULL;
  857. STACK_OF(X509) *sk = NULL;
  858. EVP_PKEY *pkey = NULL;
  859. CBS cbs, certificate_list;
  860. const uint8_t *data;
  861. n = ssl->method->ssl_get_message(ssl, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B,
  862. SSL3_MT_CERTIFICATE, (long)ssl->max_cert_list,
  863. ssl_hash_message, &ok);
  864. if (!ok) {
  865. return n;
  866. }
  867. CBS_init(&cbs, ssl->init_msg, n);
  868. sk = sk_X509_new_null();
  869. if (sk == NULL) {
  870. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  871. goto err;
  872. }
  873. if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
  874. CBS_len(&certificate_list) == 0 ||
  875. CBS_len(&cbs) != 0) {
  876. al = SSL_AD_DECODE_ERROR;
  877. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  878. goto f_err;
  879. }
  880. while (CBS_len(&certificate_list) > 0) {
  881. CBS certificate;
  882. if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
  883. al = SSL_AD_DECODE_ERROR;
  884. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  885. goto f_err;
  886. }
  887. /* A u24 length cannot overflow a long. */
  888. data = CBS_data(&certificate);
  889. x = d2i_X509(NULL, &data, (long)CBS_len(&certificate));
  890. if (x == NULL) {
  891. al = SSL_AD_BAD_CERTIFICATE;
  892. OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
  893. goto f_err;
  894. }
  895. if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
  896. al = SSL_AD_DECODE_ERROR;
  897. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  898. goto f_err;
  899. }
  900. if (!sk_X509_push(sk, x)) {
  901. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  902. goto err;
  903. }
  904. x = NULL;
  905. }
  906. X509 *leaf = sk_X509_value(sk, 0);
  907. if (!ssl3_check_leaf_certificate(ssl, leaf)) {
  908. al = SSL_AD_ILLEGAL_PARAMETER;
  909. goto f_err;
  910. }
  911. /* NOTE: Unlike the server half, the client's copy of |cert_chain| includes
  912. * the leaf. */
  913. sk_X509_pop_free(ssl->session->cert_chain, X509_free);
  914. ssl->session->cert_chain = sk;
  915. sk = NULL;
  916. X509_free(ssl->session->peer);
  917. ssl->session->peer = X509_up_ref(leaf);
  918. ssl->session->verify_result = ssl->verify_result;
  919. ret = 1;
  920. if (0) {
  921. f_err:
  922. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  923. }
  924. err:
  925. EVP_PKEY_free(pkey);
  926. X509_free(x);
  927. sk_X509_pop_free(sk, X509_free);
  928. return ret;
  929. }
  930. int ssl3_get_server_key_exchange(SSL *ssl) {
  931. EVP_MD_CTX md_ctx;
  932. int al, ok;
  933. EVP_PKEY *pkey = NULL;
  934. DH *dh = NULL;
  935. EC_KEY *ecdh = NULL;
  936. EC_POINT *srvr_ecpoint = NULL;
  937. /* use same message size as in ssl3_get_certificate_request() as
  938. * ServerKeyExchange message may be skipped */
  939. long n = ssl->method->ssl_get_message(
  940. ssl, SSL3_ST_CR_KEY_EXCH_A, SSL3_ST_CR_KEY_EXCH_B, -1, ssl->max_cert_list,
  941. ssl_hash_message, &ok);
  942. if (!ok) {
  943. return n;
  944. }
  945. if (ssl->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
  946. if (ssl_cipher_requires_server_key_exchange(ssl->s3->tmp.new_cipher)) {
  947. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  948. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  949. return -1;
  950. }
  951. /* In plain PSK ciphersuite, ServerKeyExchange may be omitted to send no
  952. * identity hint. */
  953. if (ssl->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK) {
  954. /* TODO(davidben): This should be reset in one place with the rest of the
  955. * handshake state. */
  956. OPENSSL_free(ssl->s3->tmp.peer_psk_identity_hint);
  957. ssl->s3->tmp.peer_psk_identity_hint = NULL;
  958. }
  959. ssl->s3->tmp.reuse_message = 1;
  960. return 1;
  961. }
  962. /* Retain a copy of the original CBS to compute the signature over. */
  963. CBS server_key_exchange;
  964. CBS_init(&server_key_exchange, ssl->init_msg, n);
  965. CBS server_key_exchange_orig = server_key_exchange;
  966. uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
  967. uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  968. EVP_MD_CTX_init(&md_ctx);
  969. if (alg_a & SSL_aPSK) {
  970. CBS psk_identity_hint;
  971. /* Each of the PSK key exchanges begins with a psk_identity_hint. */
  972. if (!CBS_get_u16_length_prefixed(&server_key_exchange,
  973. &psk_identity_hint)) {
  974. al = SSL_AD_DECODE_ERROR;
  975. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  976. goto f_err;
  977. }
  978. /* Store PSK identity hint for later use, hint is used in
  979. * ssl3_send_client_key_exchange. Assume that the maximum length of a PSK
  980. * identity hint can be as long as the maximum length of a PSK identity.
  981. * Also do not allow NULL characters; identities are saved as C strings.
  982. *
  983. * TODO(davidben): Should invalid hints be ignored? It's a hint rather than
  984. * a specific identity. */
  985. if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
  986. CBS_contains_zero_byte(&psk_identity_hint)) {
  987. al = SSL_AD_HANDSHAKE_FAILURE;
  988. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  989. goto f_err;
  990. }
  991. /* Save the identity hint as a C string. */
  992. if (!CBS_strdup(&psk_identity_hint, &ssl->s3->tmp.peer_psk_identity_hint)) {
  993. al = SSL_AD_INTERNAL_ERROR;
  994. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  995. goto f_err;
  996. }
  997. }
  998. if (alg_k & SSL_kDHE) {
  999. CBS dh_p, dh_g, dh_Ys;
  1000. if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
  1001. CBS_len(&dh_p) == 0 ||
  1002. !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
  1003. CBS_len(&dh_g) == 0 ||
  1004. !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
  1005. CBS_len(&dh_Ys) == 0) {
  1006. al = SSL_AD_DECODE_ERROR;
  1007. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1008. goto f_err;
  1009. }
  1010. dh = DH_new();
  1011. if (dh == NULL) {
  1012. goto err;
  1013. }
  1014. dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL);
  1015. dh->g = BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL);
  1016. if (dh->p == NULL || dh->g == NULL) {
  1017. goto err;
  1018. }
  1019. ssl->session->key_exchange_info = DH_num_bits(dh);
  1020. if (ssl->session->key_exchange_info < 1024) {
  1021. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_DH_P_LENGTH);
  1022. goto err;
  1023. } else if (ssl->session->key_exchange_info > 4096) {
  1024. /* Overly large DHE groups are prohibitively expensive, so enforce a limit
  1025. * to prevent a server from causing us to perform too expensive of a
  1026. * computation. */
  1027. OPENSSL_PUT_ERROR(SSL, SSL_R_DH_P_TOO_LONG);
  1028. goto err;
  1029. }
  1030. SSL_ECDH_CTX_init_for_dhe(&ssl->s3->tmp.ecdh_ctx, dh);
  1031. dh = NULL;
  1032. /* Save the peer public key for later. */
  1033. size_t peer_key_len;
  1034. if (!CBS_stow(&dh_Ys, &ssl->s3->tmp.peer_key, &peer_key_len)) {
  1035. goto err;
  1036. }
  1037. /* |dh_Ys| has a u16 length prefix, so this fits in a |uint16_t|. */
  1038. assert(sizeof(ssl->s3->tmp.peer_key_len) == 2 && peer_key_len <= 0xffff);
  1039. ssl->s3->tmp.peer_key_len = (uint16_t)peer_key_len;
  1040. } else if (alg_k & SSL_kECDHE) {
  1041. /* Parse the server parameters. */
  1042. uint8_t curve_type;
  1043. uint16_t curve_id;
  1044. CBS point;
  1045. if (!CBS_get_u8(&server_key_exchange, &curve_type) ||
  1046. curve_type != NAMED_CURVE_TYPE ||
  1047. !CBS_get_u16(&server_key_exchange, &curve_id) ||
  1048. !CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
  1049. al = SSL_AD_DECODE_ERROR;
  1050. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1051. goto f_err;
  1052. }
  1053. ssl->session->key_exchange_info = curve_id;
  1054. /* Ensure the curve is consistent with preferences. */
  1055. if (!tls1_check_curve_id(ssl, curve_id)) {
  1056. al = SSL_AD_ILLEGAL_PARAMETER;
  1057. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
  1058. goto f_err;
  1059. }
  1060. /* Initialize ECDH and save the peer public key for later. */
  1061. size_t peer_key_len;
  1062. if (!SSL_ECDH_CTX_init(&ssl->s3->tmp.ecdh_ctx, curve_id) ||
  1063. !CBS_stow(&point, &ssl->s3->tmp.peer_key, &peer_key_len)) {
  1064. goto err;
  1065. }
  1066. /* |point| has a u8 length prefix, so this fits in a |uint16_t|. */
  1067. assert(sizeof(ssl->s3->tmp.peer_key_len) == 2 && peer_key_len <= 0xffff);
  1068. ssl->s3->tmp.peer_key_len = (uint16_t)peer_key_len;
  1069. } else if (!(alg_k & SSL_kPSK)) {
  1070. al = SSL_AD_UNEXPECTED_MESSAGE;
  1071. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  1072. goto f_err;
  1073. }
  1074. /* At this point, |server_key_exchange| contains the signature, if any, while
  1075. * |server_key_exchange_orig| contains the entire message. From that, derive
  1076. * a CBS containing just the parameter. */
  1077. CBS parameter;
  1078. CBS_init(&parameter, CBS_data(&server_key_exchange_orig),
  1079. CBS_len(&server_key_exchange_orig) - CBS_len(&server_key_exchange));
  1080. /* ServerKeyExchange should be signed by the server's public key. */
  1081. if (ssl_cipher_has_server_public_key(ssl->s3->tmp.new_cipher)) {
  1082. pkey = X509_get_pubkey(ssl->session->peer);
  1083. if (pkey == NULL) {
  1084. goto err;
  1085. }
  1086. const EVP_MD *md = NULL;
  1087. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1088. uint8_t hash, signature;
  1089. if (!CBS_get_u8(&server_key_exchange, &hash) ||
  1090. !CBS_get_u8(&server_key_exchange, &signature)) {
  1091. al = SSL_AD_DECODE_ERROR;
  1092. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1093. goto f_err;
  1094. }
  1095. if (!tls12_check_peer_sigalg(ssl, &md, &al, hash, signature, pkey)) {
  1096. goto f_err;
  1097. }
  1098. ssl->s3->tmp.server_key_exchange_hash = hash;
  1099. } else if (pkey->type == EVP_PKEY_RSA) {
  1100. md = EVP_md5_sha1();
  1101. } else {
  1102. md = EVP_sha1();
  1103. }
  1104. /* The last field in |server_key_exchange| is the signature. */
  1105. CBS signature;
  1106. if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
  1107. CBS_len(&server_key_exchange) != 0) {
  1108. al = SSL_AD_DECODE_ERROR;
  1109. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1110. goto f_err;
  1111. }
  1112. int sig_ok = EVP_DigestVerifyInit(&md_ctx, NULL, md, NULL, pkey) &&
  1113. EVP_DigestVerifyUpdate(&md_ctx, ssl->s3->client_random,
  1114. SSL3_RANDOM_SIZE) &&
  1115. EVP_DigestVerifyUpdate(&md_ctx, ssl->s3->server_random,
  1116. SSL3_RANDOM_SIZE) &&
  1117. EVP_DigestVerifyUpdate(&md_ctx, CBS_data(&parameter),
  1118. CBS_len(&parameter)) &&
  1119. EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
  1120. CBS_len(&signature));
  1121. #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
  1122. sig_ok = 1;
  1123. ERR_clear_error();
  1124. #endif
  1125. if (!sig_ok) {
  1126. /* bad signature */
  1127. al = SSL_AD_DECRYPT_ERROR;
  1128. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
  1129. goto f_err;
  1130. }
  1131. } else {
  1132. /* PSK ciphers are the only supported certificate-less ciphers. */
  1133. assert(alg_a == SSL_aPSK);
  1134. if (CBS_len(&server_key_exchange) > 0) {
  1135. al = SSL_AD_DECODE_ERROR;
  1136. OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
  1137. goto f_err;
  1138. }
  1139. }
  1140. EVP_PKEY_free(pkey);
  1141. EVP_MD_CTX_cleanup(&md_ctx);
  1142. return 1;
  1143. f_err:
  1144. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1145. err:
  1146. EVP_PKEY_free(pkey);
  1147. DH_free(dh);
  1148. EC_POINT_free(srvr_ecpoint);
  1149. EC_KEY_free(ecdh);
  1150. EVP_MD_CTX_cleanup(&md_ctx);
  1151. return -1;
  1152. }
  1153. static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b) {
  1154. return X509_NAME_cmp(*a, *b);
  1155. }
  1156. int ssl3_get_certificate_request(SSL *ssl) {
  1157. int ok, ret = 0;
  1158. X509_NAME *xn = NULL;
  1159. STACK_OF(X509_NAME) *ca_sk = NULL;
  1160. long n = ssl->method->ssl_get_message(
  1161. ssl, SSL3_ST_CR_CERT_REQ_A, SSL3_ST_CR_CERT_REQ_B, -1, ssl->max_cert_list,
  1162. ssl_hash_message, &ok);
  1163. if (!ok) {
  1164. return n;
  1165. }
  1166. ssl->s3->tmp.cert_req = 0;
  1167. if (ssl->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
  1168. ssl->s3->tmp.reuse_message = 1;
  1169. /* If we get here we don't need the handshake buffer as we won't be doing
  1170. * client auth. */
  1171. ssl3_free_handshake_buffer(ssl);
  1172. return 1;
  1173. }
  1174. if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
  1175. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  1176. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  1177. goto err;
  1178. }
  1179. CBS cbs;
  1180. CBS_init(&cbs, ssl->init_msg, n);
  1181. ca_sk = sk_X509_NAME_new(ca_dn_cmp);
  1182. if (ca_sk == NULL) {
  1183. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1184. goto err;
  1185. }
  1186. /* get the certificate types */
  1187. CBS certificate_types;
  1188. if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types)) {
  1189. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1190. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1191. goto err;
  1192. }
  1193. if (!CBS_stow(&certificate_types, &ssl->s3->tmp.certificate_types,
  1194. &ssl->s3->tmp.num_certificate_types)) {
  1195. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1196. goto err;
  1197. }
  1198. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1199. CBS supported_signature_algorithms;
  1200. if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms) ||
  1201. !tls1_parse_peer_sigalgs(ssl, &supported_signature_algorithms)) {
  1202. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1203. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1204. goto err;
  1205. }
  1206. }
  1207. /* get the CA RDNs */
  1208. CBS certificate_authorities;
  1209. if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities)) {
  1210. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1211. OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
  1212. goto err;
  1213. }
  1214. while (CBS_len(&certificate_authorities) > 0) {
  1215. CBS distinguished_name;
  1216. if (!CBS_get_u16_length_prefixed(&certificate_authorities,
  1217. &distinguished_name)) {
  1218. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1219. OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_TOO_LONG);
  1220. goto err;
  1221. }
  1222. const uint8_t *data = CBS_data(&distinguished_name);
  1223. /* A u16 length cannot overflow a long. */
  1224. xn = d2i_X509_NAME(NULL, &data, (long)CBS_len(&distinguished_name));
  1225. if (xn == NULL ||
  1226. data != CBS_data(&distinguished_name) + CBS_len(&distinguished_name)) {
  1227. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1228. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1229. goto err;
  1230. }
  1231. if (!sk_X509_NAME_push(ca_sk, xn)) {
  1232. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1233. goto err;
  1234. }
  1235. xn = NULL;
  1236. }
  1237. /* we should setup a certificate to return.... */
  1238. ssl->s3->tmp.cert_req = 1;
  1239. sk_X509_NAME_pop_free(ssl->s3->tmp.ca_names, X509_NAME_free);
  1240. ssl->s3->tmp.ca_names = ca_sk;
  1241. ca_sk = NULL;
  1242. ret = 1;
  1243. err:
  1244. X509_NAME_free(xn);
  1245. sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
  1246. return ret;
  1247. }
  1248. int ssl3_get_new_session_ticket(SSL *ssl) {
  1249. int ok, al;
  1250. long n = ssl->method->ssl_get_message(
  1251. ssl, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B,
  1252. SSL3_MT_NEWSESSION_TICKET, 16384, ssl_hash_message, &ok);
  1253. if (!ok) {
  1254. return n;
  1255. }
  1256. CBS new_session_ticket, ticket;
  1257. uint32_t ticket_lifetime_hint;
  1258. CBS_init(&new_session_ticket, ssl->init_msg, n);
  1259. if (!CBS_get_u32(&new_session_ticket, &ticket_lifetime_hint) ||
  1260. !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
  1261. CBS_len(&new_session_ticket) != 0) {
  1262. al = SSL_AD_DECODE_ERROR;
  1263. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1264. goto f_err;
  1265. }
  1266. if (CBS_len(&ticket) == 0) {
  1267. /* RFC 5077 allows a server to change its mind and send no ticket after
  1268. * negotiating the extension. The value of |tlsext_ticket_expected| is
  1269. * checked in |ssl_update_cache| so is cleared here to avoid an unnecessary
  1270. * update. */
  1271. ssl->tlsext_ticket_expected = 0;
  1272. return 1;
  1273. }
  1274. if (ssl->hit) {
  1275. /* The server is sending a new ticket for an existing session. Sessions are
  1276. * immutable once established, so duplicate all but the ticket of the
  1277. * existing session. */
  1278. uint8_t *bytes;
  1279. size_t bytes_len;
  1280. if (!SSL_SESSION_to_bytes_for_ticket(ssl->session, &bytes, &bytes_len)) {
  1281. goto err;
  1282. }
  1283. SSL_SESSION *new_session = SSL_SESSION_from_bytes(bytes, bytes_len);
  1284. OPENSSL_free(bytes);
  1285. if (new_session == NULL) {
  1286. /* This should never happen. */
  1287. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1288. goto err;
  1289. }
  1290. SSL_SESSION_free(ssl->session);
  1291. ssl->session = new_session;
  1292. }
  1293. if (!CBS_stow(&ticket, &ssl->session->tlsext_tick,
  1294. &ssl->session->tlsext_ticklen)) {
  1295. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1296. goto err;
  1297. }
  1298. ssl->session->tlsext_tick_lifetime_hint = ticket_lifetime_hint;
  1299. /* Generate a session ID for this session based on the session ticket. We use
  1300. * the session ID mechanism for detecting ticket resumption. This also fits in
  1301. * with assumptions elsewhere in OpenSSL.*/
  1302. if (!EVP_Digest(CBS_data(&ticket), CBS_len(&ticket), ssl->session->session_id,
  1303. &ssl->session->session_id_length, EVP_sha256(), NULL)) {
  1304. goto err;
  1305. }
  1306. return 1;
  1307. f_err:
  1308. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1309. err:
  1310. return -1;
  1311. }
  1312. int ssl3_get_cert_status(SSL *ssl) {
  1313. int ok, al;
  1314. long n;
  1315. CBS certificate_status, ocsp_response;
  1316. uint8_t status_type;
  1317. n = ssl->method->ssl_get_message(
  1318. ssl, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B,
  1319. -1, 16384, ssl_hash_message, &ok);
  1320. if (!ok) {
  1321. return n;
  1322. }
  1323. if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE_STATUS) {
  1324. /* A server may send status_request in ServerHello and then change
  1325. * its mind about sending CertificateStatus. */
  1326. ssl->s3->tmp.reuse_message = 1;
  1327. return 1;
  1328. }
  1329. CBS_init(&certificate_status, ssl->init_msg, n);
  1330. if (!CBS_get_u8(&certificate_status, &status_type) ||
  1331. status_type != TLSEXT_STATUSTYPE_ocsp ||
  1332. !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
  1333. CBS_len(&ocsp_response) == 0 ||
  1334. CBS_len(&certificate_status) != 0) {
  1335. al = SSL_AD_DECODE_ERROR;
  1336. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1337. goto f_err;
  1338. }
  1339. if (!CBS_stow(&ocsp_response, &ssl->session->ocsp_response,
  1340. &ssl->session->ocsp_response_length)) {
  1341. al = SSL_AD_INTERNAL_ERROR;
  1342. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1343. goto f_err;
  1344. }
  1345. return 1;
  1346. f_err:
  1347. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1348. return -1;
  1349. }
  1350. int ssl3_get_server_done(SSL *ssl) {
  1351. int ok;
  1352. long n;
  1353. n = ssl->method->ssl_get_message(ssl, SSL3_ST_CR_SRVR_DONE_A,
  1354. SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
  1355. 30, /* should be very small, like 0 :-) */
  1356. ssl_hash_message, &ok);
  1357. if (!ok) {
  1358. return n;
  1359. }
  1360. if (n > 0) {
  1361. /* should contain no data */
  1362. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1363. OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
  1364. return -1;
  1365. }
  1366. return 1;
  1367. }
  1368. OPENSSL_COMPILE_ASSERT(sizeof(size_t) >= sizeof(unsigned),
  1369. SIZE_T_IS_SMALLER_THAN_UNSIGNED);
  1370. int ssl3_send_client_key_exchange(SSL *ssl) {
  1371. if (ssl->state == SSL3_ST_CW_KEY_EXCH_B) {
  1372. return ssl_do_write(ssl);
  1373. }
  1374. assert(ssl->state == SSL3_ST_CW_KEY_EXCH_A);
  1375. uint8_t *pms = NULL;
  1376. size_t pms_len = 0;
  1377. CBB cbb;
  1378. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  1379. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
  1380. goto err;
  1381. }
  1382. uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
  1383. uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  1384. /* If using a PSK key exchange, prepare the pre-shared key. */
  1385. unsigned psk_len = 0;
  1386. uint8_t psk[PSK_MAX_PSK_LEN];
  1387. if (alg_a & SSL_aPSK) {
  1388. if (ssl->psk_client_callback == NULL) {
  1389. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
  1390. goto err;
  1391. }
  1392. char identity[PSK_MAX_IDENTITY_LEN + 1];
  1393. memset(identity, 0, sizeof(identity));
  1394. psk_len = ssl->psk_client_callback(
  1395. ssl, ssl->s3->tmp.peer_psk_identity_hint, identity, sizeof(identity),
  1396. psk, sizeof(psk));
  1397. if (psk_len == 0) {
  1398. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
  1399. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1400. goto err;
  1401. }
  1402. assert(psk_len <= PSK_MAX_PSK_LEN);
  1403. OPENSSL_free(ssl->session->psk_identity);
  1404. ssl->session->psk_identity = BUF_strdup(identity);
  1405. if (ssl->session->psk_identity == NULL) {
  1406. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1407. goto err;
  1408. }
  1409. /* Write out psk_identity. */
  1410. CBB child;
  1411. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1412. !CBB_add_bytes(&child, (const uint8_t *)identity,
  1413. OPENSSL_strnlen(identity, sizeof(identity))) ||
  1414. !CBB_flush(&cbb)) {
  1415. goto err;
  1416. }
  1417. }
  1418. /* Depending on the key exchange method, compute |pms| and |pms_len|. */
  1419. if (alg_k & SSL_kRSA) {
  1420. pms_len = SSL_MAX_MASTER_KEY_LENGTH;
  1421. pms = OPENSSL_malloc(pms_len);
  1422. if (pms == NULL) {
  1423. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1424. goto err;
  1425. }
  1426. EVP_PKEY *pkey = X509_get_pubkey(ssl->session->peer);
  1427. if (pkey == NULL) {
  1428. goto err;
  1429. }
  1430. RSA *rsa = EVP_PKEY_get0_RSA(pkey);
  1431. if (rsa == NULL) {
  1432. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1433. EVP_PKEY_free(pkey);
  1434. goto err;
  1435. }
  1436. ssl->session->key_exchange_info = EVP_PKEY_bits(pkey);
  1437. EVP_PKEY_free(pkey);
  1438. pms[0] = ssl->client_version >> 8;
  1439. pms[1] = ssl->client_version & 0xff;
  1440. if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
  1441. goto err;
  1442. }
  1443. CBB child, *enc_pms = &cbb;
  1444. size_t enc_pms_len;
  1445. /* In TLS, there is a length prefix. */
  1446. if (ssl->version > SSL3_VERSION) {
  1447. if (!CBB_add_u16_length_prefixed(&cbb, &child)) {
  1448. goto err;
  1449. }
  1450. enc_pms = &child;
  1451. }
  1452. uint8_t *ptr;
  1453. if (!CBB_reserve(enc_pms, &ptr, RSA_size(rsa)) ||
  1454. !RSA_encrypt(rsa, &enc_pms_len, ptr, RSA_size(rsa), pms, pms_len,
  1455. RSA_PKCS1_PADDING) ||
  1456. /* Log the premaster secret, if logging is enabled. */
  1457. !ssl_log_rsa_client_key_exchange(ssl, ptr, enc_pms_len, pms, pms_len) ||
  1458. !CBB_did_write(enc_pms, enc_pms_len) ||
  1459. !CBB_flush(&cbb)) {
  1460. goto err;
  1461. }
  1462. } else if (alg_k & (SSL_kECDHE|SSL_kDHE)) {
  1463. /* Generate a keypair and serialize the public half. ECDHE uses a u8 length
  1464. * prefix while DHE uses u16. */
  1465. CBB child;
  1466. int child_ok;
  1467. if (alg_k & SSL_kECDHE) {
  1468. child_ok = CBB_add_u8_length_prefixed(&cbb, &child);
  1469. } else {
  1470. child_ok = CBB_add_u16_length_prefixed(&cbb, &child);
  1471. }
  1472. if (!child_ok ||
  1473. !SSL_ECDH_CTX_generate_keypair(&ssl->s3->tmp.ecdh_ctx, &child) ||
  1474. !CBB_flush(&cbb)) {
  1475. goto err;
  1476. }
  1477. /* Compute the premaster. */
  1478. uint8_t alert;
  1479. if (!SSL_ECDH_CTX_compute_secret(&ssl->s3->tmp.ecdh_ctx, &pms, &pms_len,
  1480. &alert, ssl->s3->tmp.peer_key,
  1481. ssl->s3->tmp.peer_key_len)) {
  1482. ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
  1483. goto err;
  1484. }
  1485. /* The key exchange state may now be discarded. */
  1486. SSL_ECDH_CTX_cleanup(&ssl->s3->tmp.ecdh_ctx);
  1487. OPENSSL_free(ssl->s3->tmp.peer_key);
  1488. ssl->s3->tmp.peer_key = NULL;
  1489. } else if (alg_k & SSL_kPSK) {
  1490. /* For plain PSK, other_secret is a block of 0s with the same length as
  1491. * the pre-shared key. */
  1492. pms_len = psk_len;
  1493. pms = OPENSSL_malloc(pms_len);
  1494. if (pms == NULL) {
  1495. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1496. goto err;
  1497. }
  1498. memset(pms, 0, pms_len);
  1499. } else {
  1500. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1501. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1502. goto err;
  1503. }
  1504. /* For a PSK cipher suite, other_secret is combined with the pre-shared
  1505. * key. */
  1506. if (alg_a & SSL_aPSK) {
  1507. CBB pms_cbb, child;
  1508. uint8_t *new_pms;
  1509. size_t new_pms_len;
  1510. CBB_zero(&pms_cbb);
  1511. if (!CBB_init(&pms_cbb, 2 + psk_len + 2 + pms_len) ||
  1512. !CBB_add_u16_length_prefixed(&pms_cbb, &child) ||
  1513. !CBB_add_bytes(&child, pms, pms_len) ||
  1514. !CBB_add_u16_length_prefixed(&pms_cbb, &child) ||
  1515. !CBB_add_bytes(&child, psk, psk_len) ||
  1516. !CBB_finish(&pms_cbb, &new_pms, &new_pms_len)) {
  1517. CBB_cleanup(&pms_cbb);
  1518. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1519. goto err;
  1520. }
  1521. OPENSSL_cleanse(pms, pms_len);
  1522. OPENSSL_free(pms);
  1523. pms = new_pms;
  1524. pms_len = new_pms_len;
  1525. }
  1526. /* The message must be added to the finished hash before calculating the
  1527. * master secret. */
  1528. size_t length;
  1529. if (!CBB_finish(&cbb, NULL, &length) ||
  1530. !ssl_set_handshake_header(ssl, SSL3_MT_CLIENT_KEY_EXCHANGE, length)) {
  1531. goto err;
  1532. }
  1533. ssl->state = SSL3_ST_CW_KEY_EXCH_B;
  1534. ssl->session->master_key_length =
  1535. tls1_generate_master_secret(ssl, ssl->session->master_key, pms, pms_len);
  1536. if (ssl->session->master_key_length == 0) {
  1537. goto err;
  1538. }
  1539. ssl->session->extended_master_secret = ssl->s3->tmp.extended_master_secret;
  1540. OPENSSL_cleanse(pms, pms_len);
  1541. OPENSSL_free(pms);
  1542. /* SSL3_ST_CW_KEY_EXCH_B */
  1543. return ssl_do_write(ssl);
  1544. err:
  1545. CBB_cleanup(&cbb);
  1546. if (pms != NULL) {
  1547. OPENSSL_cleanse(pms, pms_len);
  1548. OPENSSL_free(pms);
  1549. }
  1550. return -1;
  1551. }
  1552. int ssl3_send_cert_verify(SSL *ssl) {
  1553. if (ssl->state == SSL3_ST_CW_CERT_VRFY_C) {
  1554. return ssl_do_write(ssl);
  1555. }
  1556. CBB cbb, child;
  1557. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  1558. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl))) {
  1559. goto err;
  1560. }
  1561. assert(ssl_has_private_key(ssl));
  1562. const size_t max_sig_len = ssl_private_key_max_signature_len(ssl);
  1563. size_t sig_len;
  1564. enum ssl_private_key_result_t sign_result;
  1565. if (ssl->state == SSL3_ST_CW_CERT_VRFY_A) {
  1566. /* Select and write out the digest type in TLS 1.2. */
  1567. const EVP_MD *md = NULL;
  1568. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1569. md = tls1_choose_signing_digest(ssl);
  1570. if (!tls12_add_sigandhash(ssl, &cbb, md)) {
  1571. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1572. goto err;
  1573. }
  1574. }
  1575. /* Compute the digest. In TLS 1.1 and below, the digest type is also
  1576. * selected here. */
  1577. uint8_t digest[EVP_MAX_MD_SIZE];
  1578. size_t digest_len;
  1579. if (!ssl3_cert_verify_hash(ssl, digest, &digest_len, &md,
  1580. ssl_private_key_type(ssl))) {
  1581. goto err;
  1582. }
  1583. /* The handshake buffer is no longer necessary. */
  1584. ssl3_free_handshake_buffer(ssl);
  1585. /* Sign the digest. */
  1586. uint8_t *ptr;
  1587. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1588. !CBB_reserve(&child, &ptr, max_sig_len)) {
  1589. goto err;
  1590. }
  1591. sign_result = ssl_private_key_sign(ssl, ptr, &sig_len, max_sig_len, md,
  1592. digest, digest_len);
  1593. } else {
  1594. assert(ssl->state == SSL3_ST_CW_CERT_VRFY_B);
  1595. /* Skip over the already written signature algorithm and retry the
  1596. * signature. */
  1597. uint8_t *ptr;
  1598. if ((ssl3_protocol_version(ssl) >= TLS1_2_VERSION &&
  1599. !CBB_did_write(&cbb, 2)) ||
  1600. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1601. !CBB_reserve(&child, &ptr, max_sig_len)) {
  1602. goto err;
  1603. }
  1604. sign_result =
  1605. ssl_private_key_sign_complete(ssl, ptr, &sig_len, max_sig_len);
  1606. }
  1607. switch (sign_result) {
  1608. case ssl_private_key_success:
  1609. ssl->rwstate = SSL_NOTHING;
  1610. break;
  1611. case ssl_private_key_failure:
  1612. ssl->rwstate = SSL_NOTHING;
  1613. goto err;
  1614. case ssl_private_key_retry:
  1615. ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1616. ssl->state = SSL3_ST_CW_CERT_VRFY_B;
  1617. goto err;
  1618. }
  1619. size_t length;
  1620. if (!CBB_did_write(&child, sig_len) ||
  1621. !CBB_finish(&cbb, NULL, &length) ||
  1622. !ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE_VERIFY, length)) {
  1623. goto err;
  1624. }
  1625. ssl->state = SSL3_ST_CW_CERT_VRFY_C;
  1626. return ssl_do_write(ssl);
  1627. err:
  1628. CBB_cleanup(&cbb);
  1629. return -1;
  1630. }
  1631. /* ssl3_has_client_certificate returns true if a client certificate is
  1632. * configured. */
  1633. static int ssl3_has_client_certificate(SSL *ssl) {
  1634. return ssl->cert && ssl->cert->x509 && ssl_has_private_key(ssl);
  1635. }
  1636. int ssl3_send_client_certificate(SSL *ssl) {
  1637. if (ssl->state == SSL3_ST_CW_CERT_A) {
  1638. /* Call cert_cb to update the certificate. */
  1639. if (ssl->cert->cert_cb) {
  1640. int ret = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
  1641. if (ret < 0) {
  1642. ssl->rwstate = SSL_X509_LOOKUP;
  1643. return -1;
  1644. }
  1645. if (ret == 0) {
  1646. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1647. return -1;
  1648. }
  1649. ssl->rwstate = SSL_NOTHING;
  1650. }
  1651. if (ssl3_has_client_certificate(ssl)) {
  1652. ssl->state = SSL3_ST_CW_CERT_C;
  1653. } else {
  1654. ssl->state = SSL3_ST_CW_CERT_B;
  1655. }
  1656. }
  1657. if (ssl->state == SSL3_ST_CW_CERT_B) {
  1658. /* Call client_cert_cb to update the certificate. */
  1659. X509 *x509 = NULL;
  1660. EVP_PKEY *pkey = NULL;
  1661. int ret = ssl_do_client_cert_cb(ssl, &x509, &pkey);
  1662. if (ret < 0) {
  1663. ssl->rwstate = SSL_X509_LOOKUP;
  1664. return -1;
  1665. }
  1666. ssl->rwstate = SSL_NOTHING;
  1667. int setup_error = ret == 1 && (!SSL_use_certificate(ssl, x509) ||
  1668. !SSL_use_PrivateKey(ssl, pkey));
  1669. X509_free(x509);
  1670. EVP_PKEY_free(pkey);
  1671. if (setup_error) {
  1672. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1673. return -1;
  1674. }
  1675. ssl->state = SSL3_ST_CW_CERT_C;
  1676. }
  1677. if (ssl->state == SSL3_ST_CW_CERT_C) {
  1678. if (!ssl3_has_client_certificate(ssl)) {
  1679. /* Without a client certificate, the handshake buffer may be released. */
  1680. ssl3_free_handshake_buffer(ssl);
  1681. if (ssl->version == SSL3_VERSION) {
  1682. /* In SSL 3.0, send no certificate by skipping both messages. */
  1683. ssl->s3->tmp.cert_req = 0;
  1684. ssl3_send_alert(ssl, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
  1685. return 1;
  1686. }
  1687. /* In TLS, send an empty Certificate message. */
  1688. ssl->s3->tmp.cert_req = 2;
  1689. uint8_t *p = ssl_handshake_start(ssl);
  1690. l2n3(0, p);
  1691. if (!ssl_set_handshake_header(ssl, SSL3_MT_CERTIFICATE, 3)) {
  1692. return -1;
  1693. }
  1694. } else if (!ssl3_output_cert_chain(ssl)) {
  1695. return -1;
  1696. }
  1697. ssl->state = SSL3_ST_CW_CERT_D;
  1698. }
  1699. assert(ssl->state == SSL3_ST_CW_CERT_D);
  1700. return ssl_do_write(ssl);
  1701. }
  1702. int ssl3_send_next_proto(SSL *ssl) {
  1703. if (ssl->state == SSL3_ST_CW_NEXT_PROTO_B) {
  1704. return ssl_do_write(ssl);
  1705. }
  1706. assert(ssl->state == SSL3_ST_CW_NEXT_PROTO_A);
  1707. static const uint8_t kZero[32] = {0};
  1708. size_t padding_len = 32 - ((ssl->s3->next_proto_negotiated_len + 2) % 32);
  1709. CBB cbb, child;
  1710. size_t length;
  1711. CBB_zero(&cbb);
  1712. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  1713. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
  1714. !CBB_add_u8_length_prefixed(&cbb, &child) ||
  1715. !CBB_add_bytes(&child, ssl->s3->next_proto_negotiated,
  1716. ssl->s3->next_proto_negotiated_len) ||
  1717. !CBB_add_u8_length_prefixed(&cbb, &child) ||
  1718. !CBB_add_bytes(&child, kZero, padding_len) ||
  1719. !CBB_finish(&cbb, NULL, &length) ||
  1720. !ssl_set_handshake_header(ssl, SSL3_MT_NEXT_PROTO, length)) {
  1721. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1722. CBB_cleanup(&cbb);
  1723. return -1;
  1724. }
  1725. ssl->state = SSL3_ST_CW_NEXT_PROTO_B;
  1726. return ssl_do_write(ssl);
  1727. }
  1728. int ssl3_send_channel_id(SSL *ssl) {
  1729. if (ssl->state == SSL3_ST_CW_CHANNEL_ID_B) {
  1730. return ssl_do_write(ssl);
  1731. }
  1732. assert(ssl->state == SSL3_ST_CW_CHANNEL_ID_A);
  1733. if (ssl->tlsext_channel_id_private == NULL &&
  1734. ssl->ctx->channel_id_cb != NULL) {
  1735. EVP_PKEY *key = NULL;
  1736. ssl->ctx->channel_id_cb(ssl, &key);
  1737. if (key != NULL &&
  1738. !SSL_set1_tls_channel_id(ssl, key)) {
  1739. EVP_PKEY_free(key);
  1740. return -1;
  1741. }
  1742. EVP_PKEY_free(key);
  1743. }
  1744. if (ssl->tlsext_channel_id_private == NULL) {
  1745. ssl->rwstate = SSL_CHANNEL_ID_LOOKUP;
  1746. return -1;
  1747. }
  1748. ssl->rwstate = SSL_NOTHING;
  1749. EC_KEY *ec_key = EVP_PKEY_get0_EC_KEY(ssl->tlsext_channel_id_private);
  1750. if (ec_key == NULL) {
  1751. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1752. return -1;
  1753. }
  1754. int ret = -1;
  1755. BIGNUM *x = BN_new();
  1756. BIGNUM *y = BN_new();
  1757. ECDSA_SIG *sig = NULL;
  1758. if (x == NULL || y == NULL ||
  1759. !EC_POINT_get_affine_coordinates_GFp(EC_KEY_get0_group(ec_key),
  1760. EC_KEY_get0_public_key(ec_key),
  1761. x, y, NULL)) {
  1762. goto err;
  1763. }
  1764. uint8_t digest[EVP_MAX_MD_SIZE];
  1765. size_t digest_len;
  1766. if (!tls1_channel_id_hash(ssl, digest, &digest_len)) {
  1767. goto err;
  1768. }
  1769. sig = ECDSA_do_sign(digest, digest_len, ec_key);
  1770. if (sig == NULL) {
  1771. goto err;
  1772. }
  1773. CBB cbb, child;
  1774. size_t length;
  1775. CBB_zero(&cbb);
  1776. if (!CBB_init_fixed(&cbb, ssl_handshake_start(ssl),
  1777. ssl->init_buf->max - SSL_HM_HEADER_LENGTH(ssl)) ||
  1778. !CBB_add_u16(&cbb, TLSEXT_TYPE_channel_id) ||
  1779. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1780. !BN_bn2cbb_padded(&child, 32, x) ||
  1781. !BN_bn2cbb_padded(&child, 32, y) ||
  1782. !BN_bn2cbb_padded(&child, 32, sig->r) ||
  1783. !BN_bn2cbb_padded(&child, 32, sig->s) ||
  1784. !CBB_finish(&cbb, NULL, &length) ||
  1785. !ssl_set_handshake_header(ssl, SSL3_MT_ENCRYPTED_EXTENSIONS, length)) {
  1786. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1787. CBB_cleanup(&cbb);
  1788. goto err;
  1789. }
  1790. ssl->state = SSL3_ST_CW_CHANNEL_ID_B;
  1791. ret = ssl_do_write(ssl);
  1792. err:
  1793. BN_free(x);
  1794. BN_free(y);
  1795. ECDSA_SIG_free(sig);
  1796. return ret;
  1797. }
  1798. int ssl_do_client_cert_cb(SSL *ssl, X509 **out_x509, EVP_PKEY **out_pkey) {
  1799. if (ssl->ctx->client_cert_cb == NULL) {
  1800. return 0;
  1801. }
  1802. int ret = ssl->ctx->client_cert_cb(ssl, out_x509, out_pkey);
  1803. if (ret <= 0) {
  1804. return ret;
  1805. }
  1806. assert(*out_x509 != NULL);
  1807. assert(*out_pkey != NULL);
  1808. return 1;
  1809. }
  1810. int ssl3_verify_server_cert(SSL *ssl) {
  1811. int ret = ssl_verify_cert_chain(ssl, ssl->session->cert_chain);
  1812. if (ssl->verify_mode != SSL_VERIFY_NONE && ret <= 0) {
  1813. int al = ssl_verify_alarm_type(ssl->verify_result);
  1814. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1815. OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
  1816. } else {
  1817. ret = 1;
  1818. ERR_clear_error(); /* but we keep ssl->verify_result */
  1819. }
  1820. return ret;
  1821. }