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.
 
 
 
 
 
 

1985 line
63 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/x509.h>
  166. #include "internal.h"
  167. #include "../crypto/internal.h"
  168. static int ssl3_get_client_hello(SSL_HANDSHAKE *hs);
  169. static int ssl3_send_server_hello(SSL_HANDSHAKE *hs);
  170. static int ssl3_send_server_certificate(SSL_HANDSHAKE *hs);
  171. static int ssl3_send_certificate_status(SSL_HANDSHAKE *hs);
  172. static int ssl3_send_server_key_exchange(SSL_HANDSHAKE *hs);
  173. static int ssl3_send_certificate_request(SSL_HANDSHAKE *hs);
  174. static int ssl3_send_server_hello_done(SSL_HANDSHAKE *hs);
  175. static int ssl3_get_client_certificate(SSL_HANDSHAKE *hs);
  176. static int ssl3_get_client_key_exchange(SSL_HANDSHAKE *hs);
  177. static int ssl3_get_cert_verify(SSL_HANDSHAKE *hs);
  178. static int ssl3_get_next_proto(SSL_HANDSHAKE *hs);
  179. static int ssl3_get_channel_id(SSL_HANDSHAKE *hs);
  180. static int ssl3_send_new_session_ticket(SSL_HANDSHAKE *hs);
  181. int ssl3_accept(SSL_HANDSHAKE *hs) {
  182. SSL *const ssl = hs->ssl;
  183. uint32_t alg_a;
  184. int ret = -1;
  185. int state, skip = 0;
  186. assert(ssl->handshake_func == ssl3_accept);
  187. assert(ssl->server);
  188. for (;;) {
  189. state = hs->state;
  190. switch (hs->state) {
  191. case SSL_ST_INIT:
  192. hs->state = SSL_ST_ACCEPT;
  193. skip = 1;
  194. break;
  195. case SSL_ST_ACCEPT:
  196. ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_START, 1);
  197. /* Enable a write buffer. This groups handshake messages within a flight
  198. * into a single write. */
  199. if (!ssl_init_wbio_buffer(ssl)) {
  200. ret = -1;
  201. goto end;
  202. }
  203. if (!ssl3_init_handshake_buffer(ssl)) {
  204. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  205. ret = -1;
  206. goto end;
  207. }
  208. hs->state = SSL3_ST_SR_CLNT_HELLO_A;
  209. break;
  210. case SSL3_ST_SR_CLNT_HELLO_A:
  211. case SSL3_ST_SR_CLNT_HELLO_B:
  212. case SSL3_ST_SR_CLNT_HELLO_C:
  213. case SSL3_ST_SR_CLNT_HELLO_D:
  214. case SSL3_ST_SR_CLNT_HELLO_E:
  215. ret = ssl3_get_client_hello(hs);
  216. if (hs->state == SSL_ST_TLS13) {
  217. break;
  218. }
  219. if (ret <= 0) {
  220. goto end;
  221. }
  222. ssl->method->received_flight(ssl);
  223. hs->state = SSL3_ST_SW_SRVR_HELLO_A;
  224. break;
  225. case SSL3_ST_SW_SRVR_HELLO_A:
  226. case SSL3_ST_SW_SRVR_HELLO_B:
  227. ret = ssl3_send_server_hello(hs);
  228. if (ret <= 0) {
  229. goto end;
  230. }
  231. if (ssl->session != NULL) {
  232. hs->state = SSL3_ST_SW_SESSION_TICKET_A;
  233. } else {
  234. hs->state = SSL3_ST_SW_CERT_A;
  235. }
  236. break;
  237. case SSL3_ST_SW_CERT_A:
  238. case SSL3_ST_SW_CERT_B:
  239. if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
  240. ret = ssl3_send_server_certificate(hs);
  241. if (ret <= 0) {
  242. goto end;
  243. }
  244. } else {
  245. skip = 1;
  246. }
  247. hs->state = SSL3_ST_SW_CERT_STATUS_A;
  248. break;
  249. case SSL3_ST_SW_CERT_STATUS_A:
  250. case SSL3_ST_SW_CERT_STATUS_B:
  251. if (hs->certificate_status_expected) {
  252. ret = ssl3_send_certificate_status(hs);
  253. if (ret <= 0) {
  254. goto end;
  255. }
  256. } else {
  257. skip = 1;
  258. }
  259. hs->state = SSL3_ST_SW_KEY_EXCH_A;
  260. break;
  261. case SSL3_ST_SW_KEY_EXCH_A:
  262. case SSL3_ST_SW_KEY_EXCH_B:
  263. case SSL3_ST_SW_KEY_EXCH_C:
  264. alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  265. /* PSK ciphers send ServerKeyExchange if there is an identity hint. */
  266. if (ssl_cipher_requires_server_key_exchange(ssl->s3->tmp.new_cipher) ||
  267. ((alg_a & SSL_aPSK) && ssl->psk_identity_hint)) {
  268. ret = ssl3_send_server_key_exchange(hs);
  269. if (ret <= 0) {
  270. goto end;
  271. }
  272. } else {
  273. skip = 1;
  274. }
  275. hs->state = SSL3_ST_SW_CERT_REQ_A;
  276. break;
  277. case SSL3_ST_SW_CERT_REQ_A:
  278. case SSL3_ST_SW_CERT_REQ_B:
  279. if (hs->cert_request) {
  280. ret = ssl3_send_certificate_request(hs);
  281. if (ret <= 0) {
  282. goto end;
  283. }
  284. } else {
  285. skip = 1;
  286. }
  287. hs->state = SSL3_ST_SW_SRVR_DONE_A;
  288. break;
  289. case SSL3_ST_SW_SRVR_DONE_A:
  290. case SSL3_ST_SW_SRVR_DONE_B:
  291. ret = ssl3_send_server_hello_done(hs);
  292. if (ret <= 0) {
  293. goto end;
  294. }
  295. hs->next_state = SSL3_ST_SR_CERT_A;
  296. hs->state = SSL3_ST_SW_FLUSH;
  297. break;
  298. case SSL3_ST_SR_CERT_A:
  299. if (hs->cert_request) {
  300. ret = ssl3_get_client_certificate(hs);
  301. if (ret <= 0) {
  302. goto end;
  303. }
  304. }
  305. hs->state = SSL3_ST_SR_KEY_EXCH_A;
  306. break;
  307. case SSL3_ST_SR_KEY_EXCH_A:
  308. case SSL3_ST_SR_KEY_EXCH_B:
  309. ret = ssl3_get_client_key_exchange(hs);
  310. if (ret <= 0) {
  311. goto end;
  312. }
  313. hs->state = SSL3_ST_SR_CERT_VRFY_A;
  314. break;
  315. case SSL3_ST_SR_CERT_VRFY_A:
  316. ret = ssl3_get_cert_verify(hs);
  317. if (ret <= 0) {
  318. goto end;
  319. }
  320. hs->state = SSL3_ST_SR_CHANGE;
  321. break;
  322. case SSL3_ST_SR_CHANGE:
  323. ret = ssl->method->read_change_cipher_spec(ssl);
  324. if (ret <= 0) {
  325. goto end;
  326. }
  327. if (!tls1_change_cipher_state(hs, SSL3_CHANGE_CIPHER_SERVER_READ)) {
  328. ret = -1;
  329. goto end;
  330. }
  331. hs->state = SSL3_ST_SR_NEXT_PROTO_A;
  332. break;
  333. case SSL3_ST_SR_NEXT_PROTO_A:
  334. if (hs->next_proto_neg_seen) {
  335. ret = ssl3_get_next_proto(hs);
  336. if (ret <= 0) {
  337. goto end;
  338. }
  339. } else {
  340. skip = 1;
  341. }
  342. hs->state = SSL3_ST_SR_CHANNEL_ID_A;
  343. break;
  344. case SSL3_ST_SR_CHANNEL_ID_A:
  345. if (ssl->s3->tlsext_channel_id_valid) {
  346. ret = ssl3_get_channel_id(hs);
  347. if (ret <= 0) {
  348. goto end;
  349. }
  350. } else {
  351. skip = 1;
  352. }
  353. hs->state = SSL3_ST_SR_FINISHED_A;
  354. break;
  355. case SSL3_ST_SR_FINISHED_A:
  356. ret = ssl3_get_finished(hs);
  357. if (ret <= 0) {
  358. goto end;
  359. }
  360. ssl->method->received_flight(ssl);
  361. if (ssl->session != NULL) {
  362. hs->state = SSL_ST_OK;
  363. } else {
  364. hs->state = SSL3_ST_SW_SESSION_TICKET_A;
  365. }
  366. /* If this is a full handshake with ChannelID then record the handshake
  367. * hashes in |ssl->s3->new_session| in case we need them to verify a
  368. * ChannelID signature on a resumption of this session in the future. */
  369. if (ssl->session == NULL && ssl->s3->tlsext_channel_id_valid) {
  370. ret = tls1_record_handshake_hashes_for_channel_id(ssl);
  371. if (ret <= 0) {
  372. goto end;
  373. }
  374. }
  375. break;
  376. case SSL3_ST_SW_SESSION_TICKET_A:
  377. case SSL3_ST_SW_SESSION_TICKET_B:
  378. if (hs->ticket_expected) {
  379. ret = ssl3_send_new_session_ticket(hs);
  380. if (ret <= 0) {
  381. goto end;
  382. }
  383. } else {
  384. skip = 1;
  385. }
  386. hs->state = SSL3_ST_SW_CHANGE;
  387. break;
  388. case SSL3_ST_SW_CHANGE:
  389. ret = ssl->method->send_change_cipher_spec(ssl);
  390. if (ret <= 0) {
  391. goto end;
  392. }
  393. hs->state = SSL3_ST_SW_FINISHED_A;
  394. if (!tls1_change_cipher_state(hs, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
  395. ret = -1;
  396. goto end;
  397. }
  398. break;
  399. case SSL3_ST_SW_FINISHED_A:
  400. case SSL3_ST_SW_FINISHED_B:
  401. ret = ssl3_send_finished(hs, SSL3_ST_SW_FINISHED_A,
  402. SSL3_ST_SW_FINISHED_B);
  403. if (ret <= 0) {
  404. goto end;
  405. }
  406. hs->state = SSL3_ST_SW_FLUSH;
  407. if (ssl->session != NULL) {
  408. hs->next_state = SSL3_ST_SR_CHANGE;
  409. } else {
  410. hs->next_state = SSL_ST_OK;
  411. }
  412. break;
  413. case SSL3_ST_SW_FLUSH:
  414. if (BIO_flush(ssl->wbio) <= 0) {
  415. ssl->rwstate = SSL_WRITING;
  416. ret = -1;
  417. goto end;
  418. }
  419. hs->state = hs->next_state;
  420. if (hs->state != SSL_ST_OK) {
  421. ssl->method->expect_flight(ssl);
  422. }
  423. break;
  424. case SSL_ST_TLS13:
  425. ret = tls13_handshake(hs);
  426. if (ret <= 0) {
  427. goto end;
  428. }
  429. hs->state = SSL_ST_OK;
  430. break;
  431. case SSL_ST_OK:
  432. ssl->method->release_current_message(ssl, 1 /* free_buffer */);
  433. /* If we aren't retaining peer certificates then we can discard it
  434. * now. */
  435. if (ssl->s3->new_session != NULL &&
  436. ssl->retain_only_sha256_of_client_certs) {
  437. X509_free(ssl->s3->new_session->x509_peer);
  438. ssl->s3->new_session->x509_peer = NULL;
  439. sk_X509_pop_free(ssl->s3->new_session->x509_chain, X509_free);
  440. ssl->s3->new_session->x509_chain = NULL;
  441. }
  442. SSL_SESSION_free(ssl->s3->established_session);
  443. if (ssl->session != NULL) {
  444. SSL_SESSION_up_ref(ssl->session);
  445. ssl->s3->established_session = ssl->session;
  446. } else {
  447. ssl->s3->established_session = ssl->s3->new_session;
  448. ssl->s3->established_session->not_resumable = 0;
  449. ssl->s3->new_session = NULL;
  450. }
  451. /* remove buffering on output */
  452. ssl_free_wbio_buffer(ssl);
  453. ssl->s3->initial_handshake_complete = 1;
  454. ssl_update_cache(hs, SSL_SESS_CACHE_SERVER);
  455. ssl_do_info_callback(ssl, SSL_CB_HANDSHAKE_DONE, 1);
  456. ret = 1;
  457. goto end;
  458. default:
  459. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  460. ret = -1;
  461. goto end;
  462. }
  463. if (!ssl->s3->tmp.reuse_message && !skip && hs->state != state) {
  464. int new_state = hs->state;
  465. hs->state = state;
  466. ssl_do_info_callback(ssl, SSL_CB_ACCEPT_LOOP, 1);
  467. hs->state = new_state;
  468. }
  469. skip = 0;
  470. }
  471. end:
  472. ssl_do_info_callback(ssl, SSL_CB_ACCEPT_EXIT, ret);
  473. return ret;
  474. }
  475. int ssl_client_cipher_list_contains_cipher(const SSL_CLIENT_HELLO *client_hello,
  476. uint16_t id) {
  477. CBS cipher_suites;
  478. CBS_init(&cipher_suites, client_hello->cipher_suites,
  479. client_hello->cipher_suites_len);
  480. while (CBS_len(&cipher_suites) > 0) {
  481. uint16_t got_id;
  482. if (!CBS_get_u16(&cipher_suites, &got_id)) {
  483. return 0;
  484. }
  485. if (got_id == id) {
  486. return 1;
  487. }
  488. }
  489. return 0;
  490. }
  491. static int negotiate_version(SSL_HANDSHAKE *hs, uint8_t *out_alert,
  492. const SSL_CLIENT_HELLO *client_hello) {
  493. SSL *const ssl = hs->ssl;
  494. uint16_t min_version, max_version;
  495. if (!ssl_get_version_range(ssl, &min_version, &max_version)) {
  496. *out_alert = SSL_AD_PROTOCOL_VERSION;
  497. return 0;
  498. }
  499. uint16_t version = 0;
  500. /* Check supported_versions extension if it is present. */
  501. CBS supported_versions;
  502. if (ssl_client_hello_get_extension(client_hello, &supported_versions,
  503. TLSEXT_TYPE_supported_versions)) {
  504. CBS versions;
  505. if (!CBS_get_u8_length_prefixed(&supported_versions, &versions) ||
  506. CBS_len(&supported_versions) != 0 ||
  507. CBS_len(&versions) == 0) {
  508. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  509. *out_alert = SSL_AD_DECODE_ERROR;
  510. return 0;
  511. }
  512. /* Choose the newest commonly-supported version advertised by the client.
  513. * The client orders the versions according to its preferences, but we're
  514. * not required to honor the client's preferences. */
  515. int found_version = 0;
  516. while (CBS_len(&versions) != 0) {
  517. uint16_t ext_version;
  518. if (!CBS_get_u16(&versions, &ext_version)) {
  519. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  520. *out_alert = SSL_AD_DECODE_ERROR;
  521. return 0;
  522. }
  523. if (!ssl->method->version_from_wire(&ext_version, ext_version)) {
  524. continue;
  525. }
  526. if (min_version <= ext_version &&
  527. ext_version <= max_version &&
  528. (!found_version || version < ext_version)) {
  529. version = ext_version;
  530. found_version = 1;
  531. }
  532. }
  533. if (!found_version) {
  534. goto unsupported_protocol;
  535. }
  536. } else {
  537. /* Process ClientHello.version instead. Note that versions beyond (D)TLS 1.2
  538. * do not use this mechanism. */
  539. if (SSL_is_dtls(ssl)) {
  540. if (client_hello->version <= DTLS1_2_VERSION) {
  541. version = TLS1_2_VERSION;
  542. } else if (client_hello->version <= DTLS1_VERSION) {
  543. version = TLS1_1_VERSION;
  544. } else {
  545. goto unsupported_protocol;
  546. }
  547. } else {
  548. if (client_hello->version >= TLS1_2_VERSION) {
  549. version = TLS1_2_VERSION;
  550. } else if (client_hello->version >= TLS1_1_VERSION) {
  551. version = TLS1_1_VERSION;
  552. } else if (client_hello->version >= TLS1_VERSION) {
  553. version = TLS1_VERSION;
  554. } else if (client_hello->version >= SSL3_VERSION) {
  555. version = SSL3_VERSION;
  556. } else {
  557. goto unsupported_protocol;
  558. }
  559. }
  560. /* Apply our minimum and maximum version. */
  561. if (version > max_version) {
  562. version = max_version;
  563. }
  564. if (version < min_version) {
  565. goto unsupported_protocol;
  566. }
  567. }
  568. /* Handle FALLBACK_SCSV. */
  569. if (ssl_client_cipher_list_contains_cipher(client_hello,
  570. SSL3_CK_FALLBACK_SCSV & 0xffff) &&
  571. version < max_version) {
  572. OPENSSL_PUT_ERROR(SSL, SSL_R_INAPPROPRIATE_FALLBACK);
  573. *out_alert = SSL3_AD_INAPPROPRIATE_FALLBACK;
  574. return 0;
  575. }
  576. hs->client_version = client_hello->version;
  577. ssl->version = ssl->method->version_to_wire(version);
  578. ssl->s3->enc_method = ssl3_get_enc_method(version);
  579. assert(ssl->s3->enc_method != NULL);
  580. /* At this point, the connection's version is known and |ssl->version| is
  581. * fixed. Begin enforcing the record-layer version. */
  582. ssl->s3->have_version = 1;
  583. return 1;
  584. unsupported_protocol:
  585. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
  586. *out_alert = SSL_AD_PROTOCOL_VERSION;
  587. return 0;
  588. }
  589. static STACK_OF(SSL_CIPHER) *
  590. ssl_parse_client_cipher_list(const SSL_CLIENT_HELLO *client_hello) {
  591. CBS cipher_suites;
  592. CBS_init(&cipher_suites, client_hello->cipher_suites,
  593. client_hello->cipher_suites_len);
  594. STACK_OF(SSL_CIPHER) *sk = sk_SSL_CIPHER_new_null();
  595. if (sk == NULL) {
  596. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  597. goto err;
  598. }
  599. while (CBS_len(&cipher_suites) > 0) {
  600. uint16_t cipher_suite;
  601. if (!CBS_get_u16(&cipher_suites, &cipher_suite)) {
  602. OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
  603. goto err;
  604. }
  605. const SSL_CIPHER *c = SSL_get_cipher_by_value(cipher_suite);
  606. if (c != NULL && !sk_SSL_CIPHER_push(sk, c)) {
  607. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  608. goto err;
  609. }
  610. }
  611. return sk;
  612. err:
  613. sk_SSL_CIPHER_free(sk);
  614. return NULL;
  615. }
  616. /* ssl_get_compatible_server_ciphers determines the key exchange and
  617. * authentication cipher suite masks compatible with the server configuration
  618. * and current ClientHello parameters of |hs|. It sets |*out_mask_k| to the key
  619. * exchange mask and |*out_mask_a| to the authentication mask. */
  620. static void ssl_get_compatible_server_ciphers(SSL_HANDSHAKE *hs,
  621. uint32_t *out_mask_k,
  622. uint32_t *out_mask_a) {
  623. SSL *const ssl = hs->ssl;
  624. if (ssl3_protocol_version(ssl) >= TLS1_3_VERSION) {
  625. *out_mask_k = SSL_kGENERIC;
  626. *out_mask_a = SSL_aGENERIC;
  627. return;
  628. }
  629. uint32_t mask_k = 0;
  630. uint32_t mask_a = 0;
  631. if (ssl->cert->x509_leaf != NULL && ssl_has_private_key(ssl)) {
  632. int type = ssl_private_key_type(ssl);
  633. if (type == NID_rsaEncryption) {
  634. mask_k |= SSL_kRSA;
  635. mask_a |= SSL_aRSA;
  636. } else if (ssl_is_ecdsa_key_type(type)) {
  637. mask_a |= SSL_aECDSA;
  638. }
  639. }
  640. if (ssl->cert->dh_tmp != NULL || ssl->cert->dh_tmp_cb != NULL) {
  641. mask_k |= SSL_kDHE;
  642. }
  643. /* Check for a shared group to consider ECDHE ciphers. */
  644. uint16_t unused;
  645. if (tls1_get_shared_group(hs, &unused)) {
  646. mask_k |= SSL_kECDHE;
  647. }
  648. /* PSK requires a server callback. */
  649. if (ssl->psk_server_callback != NULL) {
  650. mask_k |= SSL_kPSK;
  651. mask_a |= SSL_aPSK;
  652. }
  653. *out_mask_k = mask_k;
  654. *out_mask_a = mask_a;
  655. }
  656. static const SSL_CIPHER *ssl3_choose_cipher(
  657. SSL_HANDSHAKE *hs, const SSL_CLIENT_HELLO *client_hello,
  658. const struct ssl_cipher_preference_list_st *server_pref) {
  659. SSL *const ssl = hs->ssl;
  660. const SSL_CIPHER *c, *ret = NULL;
  661. STACK_OF(SSL_CIPHER) *srvr = server_pref->ciphers, *prio, *allow;
  662. int ok;
  663. size_t cipher_index;
  664. uint32_t alg_k, alg_a, mask_k, mask_a;
  665. /* in_group_flags will either be NULL, or will point to an array of bytes
  666. * which indicate equal-preference groups in the |prio| stack. See the
  667. * comment about |in_group_flags| in the |ssl_cipher_preference_list_st|
  668. * struct. */
  669. const uint8_t *in_group_flags;
  670. /* group_min contains the minimal index so far found in a group, or -1 if no
  671. * such value exists yet. */
  672. int group_min = -1;
  673. STACK_OF(SSL_CIPHER) *clnt = ssl_parse_client_cipher_list(client_hello);
  674. if (clnt == NULL) {
  675. return NULL;
  676. }
  677. if (ssl->options & SSL_OP_CIPHER_SERVER_PREFERENCE) {
  678. prio = srvr;
  679. in_group_flags = server_pref->in_group_flags;
  680. allow = clnt;
  681. } else {
  682. prio = clnt;
  683. in_group_flags = NULL;
  684. allow = srvr;
  685. }
  686. ssl_get_compatible_server_ciphers(hs, &mask_k, &mask_a);
  687. for (size_t i = 0; i < sk_SSL_CIPHER_num(prio); i++) {
  688. c = sk_SSL_CIPHER_value(prio, i);
  689. ok = 1;
  690. /* Check the TLS version. */
  691. if (SSL_CIPHER_get_min_version(c) > ssl3_protocol_version(ssl) ||
  692. SSL_CIPHER_get_max_version(c) < ssl3_protocol_version(ssl)) {
  693. ok = 0;
  694. }
  695. alg_k = c->algorithm_mkey;
  696. alg_a = c->algorithm_auth;
  697. ok = ok && (alg_k & mask_k) && (alg_a & mask_a);
  698. if (ok && sk_SSL_CIPHER_find(allow, &cipher_index, c)) {
  699. if (in_group_flags != NULL && in_group_flags[i] == 1) {
  700. /* This element of |prio| is in a group. Update the minimum index found
  701. * so far and continue looking. */
  702. if (group_min == -1 || (size_t)group_min > cipher_index) {
  703. group_min = cipher_index;
  704. }
  705. } else {
  706. if (group_min != -1 && (size_t)group_min < cipher_index) {
  707. cipher_index = group_min;
  708. }
  709. ret = sk_SSL_CIPHER_value(allow, cipher_index);
  710. break;
  711. }
  712. }
  713. if (in_group_flags != NULL && in_group_flags[i] == 0 && group_min != -1) {
  714. /* We are about to leave a group, but we found a match in it, so that's
  715. * our answer. */
  716. ret = sk_SSL_CIPHER_value(allow, group_min);
  717. break;
  718. }
  719. }
  720. sk_SSL_CIPHER_free(clnt);
  721. return ret;
  722. }
  723. static int ssl3_get_client_hello(SSL_HANDSHAKE *hs) {
  724. SSL *const ssl = hs->ssl;
  725. uint8_t al = SSL_AD_INTERNAL_ERROR;
  726. int ret = -1;
  727. SSL_SESSION *session = NULL;
  728. if (hs->state == SSL3_ST_SR_CLNT_HELLO_A) {
  729. /* The first time around, read the ClientHello. */
  730. int msg_ret = ssl->method->ssl_get_message(ssl, SSL3_MT_CLIENT_HELLO,
  731. ssl_hash_message);
  732. if (msg_ret <= 0) {
  733. return msg_ret;
  734. }
  735. hs->state = SSL3_ST_SR_CLNT_HELLO_B;
  736. }
  737. SSL_CLIENT_HELLO client_hello;
  738. if (!ssl_client_hello_init(ssl, &client_hello, ssl->init_msg,
  739. ssl->init_num)) {
  740. al = SSL_AD_DECODE_ERROR;
  741. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  742. goto f_err;
  743. }
  744. if (hs->state == SSL3_ST_SR_CLNT_HELLO_B) {
  745. /* Unlike other callbacks, the early callback is not run a second time if
  746. * paused. */
  747. hs->state = SSL3_ST_SR_CLNT_HELLO_C;
  748. /* Run the early callback. */
  749. if (ssl->ctx->select_certificate_cb != NULL) {
  750. switch (ssl->ctx->select_certificate_cb(&client_hello)) {
  751. case 0:
  752. ssl->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
  753. goto err;
  754. case -1:
  755. /* Connection rejected. */
  756. al = SSL_AD_HANDSHAKE_FAILURE;
  757. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  758. goto f_err;
  759. default:
  760. /* fallthrough */;
  761. }
  762. }
  763. }
  764. /* Negotiate the protocol version if we have not done so yet. */
  765. if (!ssl->s3->have_version) {
  766. if (!negotiate_version(hs, &al, &client_hello)) {
  767. goto f_err;
  768. }
  769. if (ssl3_protocol_version(ssl) >= TLS1_3_VERSION) {
  770. hs->state = SSL_ST_TLS13;
  771. hs->do_tls13_handshake = tls13_server_handshake;
  772. return 1;
  773. }
  774. }
  775. if (hs->state == SSL3_ST_SR_CLNT_HELLO_C) {
  776. /* Load the client random. */
  777. if (client_hello.random_len != SSL3_RANDOM_SIZE) {
  778. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  779. return -1;
  780. }
  781. memcpy(ssl->s3->client_random, client_hello.random,
  782. client_hello.random_len);
  783. /* Only null compression is supported. */
  784. if (memchr(client_hello.compression_methods, 0,
  785. client_hello.compression_methods_len) == NULL) {
  786. al = SSL_AD_ILLEGAL_PARAMETER;
  787. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMPRESSION_SPECIFIED);
  788. goto f_err;
  789. }
  790. /* TLS extensions. */
  791. if (!ssl_parse_clienthello_tlsext(hs, &client_hello)) {
  792. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  793. goto err;
  794. }
  795. hs->state = SSL3_ST_SR_CLNT_HELLO_D;
  796. }
  797. if (hs->state == SSL3_ST_SR_CLNT_HELLO_D) {
  798. /* Call |cert_cb| to update server certificates if required. */
  799. if (ssl->cert->cert_cb != NULL) {
  800. int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
  801. if (rv == 0) {
  802. al = SSL_AD_INTERNAL_ERROR;
  803. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
  804. goto f_err;
  805. }
  806. if (rv < 0) {
  807. ssl->rwstate = SSL_X509_LOOKUP;
  808. goto err;
  809. }
  810. }
  811. /* Negotiate the cipher suite. This must be done after |cert_cb| so the
  812. * certificate is finalized. */
  813. ssl->s3->tmp.new_cipher =
  814. ssl3_choose_cipher(hs, &client_hello, ssl_get_cipher_preferences(ssl));
  815. if (ssl->s3->tmp.new_cipher == NULL) {
  816. al = SSL_AD_HANDSHAKE_FAILURE;
  817. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
  818. goto f_err;
  819. }
  820. hs->state = SSL3_ST_SR_CLNT_HELLO_E;
  821. }
  822. assert(hs->state == SSL3_ST_SR_CLNT_HELLO_E);
  823. /* Determine whether we are doing session resumption. */
  824. int tickets_supported = 0, renew_ticket = 0;
  825. switch (ssl_get_prev_session(ssl, &session, &tickets_supported, &renew_ticket,
  826. &client_hello)) {
  827. case ssl_session_success:
  828. break;
  829. case ssl_session_error:
  830. goto err;
  831. case ssl_session_retry:
  832. ssl->rwstate = SSL_PENDING_SESSION;
  833. goto err;
  834. }
  835. if (session != NULL) {
  836. if (session->extended_master_secret &&
  837. !ssl->s3->tmp.extended_master_secret) {
  838. /* A ClientHello without EMS that attempts to resume a session with EMS
  839. * is fatal to the connection. */
  840. al = SSL_AD_HANDSHAKE_FAILURE;
  841. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
  842. goto f_err;
  843. }
  844. if (!ssl_session_is_resumable(ssl, session) ||
  845. /* If the client offers the EMS extension, but the previous session
  846. * didn't use it, then negotiate a new session. */
  847. ssl->s3->tmp.extended_master_secret !=
  848. session->extended_master_secret) {
  849. SSL_SESSION_free(session);
  850. session = NULL;
  851. }
  852. }
  853. if (session != NULL) {
  854. /* Use the old session. */
  855. hs->ticket_expected = renew_ticket;
  856. ssl->session = session;
  857. session = NULL;
  858. ssl->s3->session_reused = 1;
  859. } else {
  860. hs->ticket_expected = tickets_supported;
  861. ssl_set_session(ssl, NULL);
  862. if (!ssl_get_new_session(hs, 1 /* server */)) {
  863. goto err;
  864. }
  865. /* Clear the session ID if we want the session to be single-use. */
  866. if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
  867. ssl->s3->new_session->session_id_length = 0;
  868. }
  869. }
  870. if (ssl->ctx->dos_protection_cb != NULL &&
  871. ssl->ctx->dos_protection_cb(&client_hello) == 0) {
  872. /* Connection rejected for DOS reasons. */
  873. al = SSL_AD_INTERNAL_ERROR;
  874. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  875. goto f_err;
  876. }
  877. if (ssl->session == NULL) {
  878. ssl->s3->new_session->cipher = ssl->s3->tmp.new_cipher;
  879. /* On new sessions, stash the SNI value in the session. */
  880. if (hs->hostname != NULL) {
  881. ssl->s3->new_session->tlsext_hostname = BUF_strdup(hs->hostname);
  882. if (ssl->s3->new_session->tlsext_hostname == NULL) {
  883. al = SSL_AD_INTERNAL_ERROR;
  884. goto f_err;
  885. }
  886. }
  887. /* Determine whether to request a client certificate. */
  888. hs->cert_request = !!(ssl->verify_mode & SSL_VERIFY_PEER);
  889. /* Only request a certificate if Channel ID isn't negotiated. */
  890. if ((ssl->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
  891. ssl->s3->tlsext_channel_id_valid) {
  892. hs->cert_request = 0;
  893. }
  894. /* CertificateRequest may only be sent in certificate-based ciphers. */
  895. if (!ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
  896. hs->cert_request = 0;
  897. }
  898. if (!hs->cert_request) {
  899. /* OpenSSL returns X509_V_OK when no certificates are requested. This is
  900. * classed by them as a bug, but it's assumed by at least NGINX. */
  901. ssl->s3->new_session->verify_result = X509_V_OK;
  902. }
  903. }
  904. /* HTTP/2 negotiation depends on the cipher suite, so ALPN negotiation was
  905. * deferred. Complete it now. */
  906. if (!ssl_negotiate_alpn(hs, &al, &client_hello)) {
  907. goto f_err;
  908. }
  909. /* Now that all parameters are known, initialize the handshake hash. */
  910. if (!ssl3_init_handshake_hash(ssl)) {
  911. goto f_err;
  912. }
  913. /* Release the handshake buffer if client authentication isn't required. */
  914. if (!hs->cert_request) {
  915. ssl3_free_handshake_buffer(ssl);
  916. }
  917. ret = 1;
  918. if (0) {
  919. f_err:
  920. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  921. }
  922. err:
  923. SSL_SESSION_free(session);
  924. return ret;
  925. }
  926. static int ssl3_send_server_hello(SSL_HANDSHAKE *hs) {
  927. SSL *const ssl = hs->ssl;
  928. if (hs->state == SSL3_ST_SW_SRVR_HELLO_B) {
  929. return ssl->method->write_message(ssl);
  930. }
  931. assert(hs->state == SSL3_ST_SW_SRVR_HELLO_A);
  932. /* We only accept ChannelIDs on connections with ECDHE in order to avoid a
  933. * known attack while we fix ChannelID itself. */
  934. if (ssl->s3->tlsext_channel_id_valid &&
  935. (ssl->s3->tmp.new_cipher->algorithm_mkey & SSL_kECDHE) == 0) {
  936. ssl->s3->tlsext_channel_id_valid = 0;
  937. }
  938. /* If this is a resumption and the original handshake didn't support
  939. * ChannelID then we didn't record the original handshake hashes in the
  940. * session and so cannot resume with ChannelIDs. */
  941. if (ssl->session != NULL &&
  942. ssl->session->original_handshake_hash_len == 0) {
  943. ssl->s3->tlsext_channel_id_valid = 0;
  944. }
  945. struct timeval now;
  946. ssl_get_current_time(ssl, &now);
  947. ssl->s3->server_random[0] = now.tv_sec >> 24;
  948. ssl->s3->server_random[1] = now.tv_sec >> 16;
  949. ssl->s3->server_random[2] = now.tv_sec >> 8;
  950. ssl->s3->server_random[3] = now.tv_sec;
  951. if (!RAND_bytes(ssl->s3->server_random + 4, SSL3_RANDOM_SIZE - 4)) {
  952. return -1;
  953. }
  954. /* TODO(davidben): Implement the TLS 1.1 and 1.2 downgrade sentinels once TLS
  955. * 1.3 is finalized and we are not implementing a draft version. */
  956. const SSL_SESSION *session = ssl->s3->new_session;
  957. if (ssl->session != NULL) {
  958. session = ssl->session;
  959. }
  960. CBB cbb, body, session_id;
  961. if (!ssl->method->init_message(ssl, &cbb, &body, SSL3_MT_SERVER_HELLO) ||
  962. !CBB_add_u16(&body, ssl->version) ||
  963. !CBB_add_bytes(&body, ssl->s3->server_random, SSL3_RANDOM_SIZE) ||
  964. !CBB_add_u8_length_prefixed(&body, &session_id) ||
  965. !CBB_add_bytes(&session_id, session->session_id,
  966. session->session_id_length) ||
  967. !CBB_add_u16(&body, ssl_cipher_get_value(ssl->s3->tmp.new_cipher)) ||
  968. !CBB_add_u8(&body, 0 /* no compression */) ||
  969. !ssl_add_serverhello_tlsext(hs, &body) ||
  970. !ssl_complete_message(ssl, &cbb)) {
  971. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  972. CBB_cleanup(&cbb);
  973. return -1;
  974. }
  975. hs->state = SSL3_ST_SW_SRVR_HELLO_B;
  976. return ssl->method->write_message(ssl);
  977. }
  978. static int ssl3_send_server_certificate(SSL_HANDSHAKE *hs) {
  979. SSL *const ssl = hs->ssl;
  980. if (hs->state == SSL3_ST_SW_CERT_B) {
  981. return ssl->method->write_message(ssl);
  982. }
  983. if (!ssl_has_certificate(ssl)) {
  984. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
  985. return 0;
  986. }
  987. if (!ssl3_output_cert_chain(ssl)) {
  988. return 0;
  989. }
  990. hs->state = SSL3_ST_SW_CERT_B;
  991. return ssl->method->write_message(ssl);
  992. }
  993. static int ssl3_send_certificate_status(SSL_HANDSHAKE *hs) {
  994. SSL *const ssl = hs->ssl;
  995. if (hs->state == SSL3_ST_SW_CERT_STATUS_B) {
  996. return ssl->method->write_message(ssl);
  997. }
  998. CBB cbb, body, ocsp_response;
  999. if (!ssl->method->init_message(ssl, &cbb, &body,
  1000. SSL3_MT_CERTIFICATE_STATUS) ||
  1001. !CBB_add_u8(&body, TLSEXT_STATUSTYPE_ocsp) ||
  1002. !CBB_add_u24_length_prefixed(&body, &ocsp_response) ||
  1003. !CBB_add_bytes(&ocsp_response, CRYPTO_BUFFER_data(ssl->ocsp_response),
  1004. CRYPTO_BUFFER_len(ssl->ocsp_response)) ||
  1005. !ssl_complete_message(ssl, &cbb)) {
  1006. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1007. CBB_cleanup(&cbb);
  1008. return -1;
  1009. }
  1010. hs->state = SSL3_ST_SW_CERT_STATUS_B;
  1011. return ssl->method->write_message(ssl);
  1012. }
  1013. static int ssl3_send_server_key_exchange(SSL_HANDSHAKE *hs) {
  1014. SSL *const ssl = hs->ssl;
  1015. if (hs->state == SSL3_ST_SW_KEY_EXCH_C) {
  1016. return ssl->method->write_message(ssl);
  1017. }
  1018. CBB cbb, child;
  1019. CBB_zero(&cbb);
  1020. /* Put together the parameters. */
  1021. if (hs->state == SSL3_ST_SW_KEY_EXCH_A) {
  1022. uint32_t alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
  1023. uint32_t alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  1024. /* Pre-allocate enough room to comfortably fit an ECDHE public key. */
  1025. if (!CBB_init(&cbb, 128)) {
  1026. goto err;
  1027. }
  1028. /* PSK ciphers begin with an identity hint. */
  1029. if (alg_a & SSL_aPSK) {
  1030. size_t len =
  1031. (ssl->psk_identity_hint == NULL) ? 0 : strlen(ssl->psk_identity_hint);
  1032. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1033. !CBB_add_bytes(&child, (const uint8_t *)ssl->psk_identity_hint,
  1034. len)) {
  1035. goto err;
  1036. }
  1037. }
  1038. if (alg_k & SSL_kDHE) {
  1039. /* Determine the group to use. */
  1040. DH *params = ssl->cert->dh_tmp;
  1041. if (params == NULL && ssl->cert->dh_tmp_cb != NULL) {
  1042. params = ssl->cert->dh_tmp_cb(ssl, 0, 1024);
  1043. }
  1044. if (params == NULL) {
  1045. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_DH_KEY);
  1046. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1047. goto err;
  1048. }
  1049. /* Set up DH, generate a key, and emit the public half. */
  1050. DH *dh = DHparams_dup(params);
  1051. if (dh == NULL) {
  1052. goto err;
  1053. }
  1054. SSL_ECDH_CTX_init_for_dhe(&hs->ecdh_ctx, dh);
  1055. if (!CBB_add_u16_length_prefixed(&cbb, &child) ||
  1056. !BN_bn2cbb_padded(&child, BN_num_bytes(params->p), params->p) ||
  1057. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1058. !BN_bn2cbb_padded(&child, BN_num_bytes(params->g), params->g) ||
  1059. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1060. !SSL_ECDH_CTX_offer(&hs->ecdh_ctx, &child)) {
  1061. goto err;
  1062. }
  1063. } else if (alg_k & SSL_kECDHE) {
  1064. /* Determine the group to use. */
  1065. uint16_t group_id;
  1066. if (!tls1_get_shared_group(hs, &group_id)) {
  1067. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_TMP_ECDH_KEY);
  1068. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1069. goto err;
  1070. }
  1071. ssl->s3->new_session->group_id = group_id;
  1072. /* Set up ECDH, generate a key, and emit the public half. */
  1073. if (!SSL_ECDH_CTX_init(&hs->ecdh_ctx, group_id) ||
  1074. !CBB_add_u8(&cbb, NAMED_CURVE_TYPE) ||
  1075. !CBB_add_u16(&cbb, group_id) ||
  1076. !CBB_add_u8_length_prefixed(&cbb, &child) ||
  1077. !SSL_ECDH_CTX_offer(&hs->ecdh_ctx, &child)) {
  1078. goto err;
  1079. }
  1080. } else {
  1081. assert(alg_k & SSL_kPSK);
  1082. }
  1083. if (!CBB_finish(&cbb, &hs->server_params, &hs->server_params_len)) {
  1084. goto err;
  1085. }
  1086. }
  1087. /* Assemble the message. */
  1088. CBB body;
  1089. if (!ssl->method->init_message(ssl, &cbb, &body,
  1090. SSL3_MT_SERVER_KEY_EXCHANGE) ||
  1091. !CBB_add_bytes(&body, hs->server_params, hs->server_params_len)) {
  1092. goto err;
  1093. }
  1094. /* Add a signature. */
  1095. if (ssl_cipher_uses_certificate_auth(ssl->s3->tmp.new_cipher)) {
  1096. if (!ssl_has_private_key(ssl)) {
  1097. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1098. goto err;
  1099. }
  1100. /* Determine the signature algorithm. */
  1101. uint16_t signature_algorithm;
  1102. if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
  1103. goto err;
  1104. }
  1105. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1106. if (!CBB_add_u16(&body, signature_algorithm)) {
  1107. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1108. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1109. goto err;
  1110. }
  1111. }
  1112. /* Add space for the signature. */
  1113. const size_t max_sig_len = ssl_private_key_max_signature_len(ssl);
  1114. uint8_t *ptr;
  1115. if (!CBB_add_u16_length_prefixed(&body, &child) ||
  1116. !CBB_reserve(&child, &ptr, max_sig_len)) {
  1117. goto err;
  1118. }
  1119. size_t sig_len;
  1120. enum ssl_private_key_result_t sign_result;
  1121. if (hs->state == SSL3_ST_SW_KEY_EXCH_A) {
  1122. CBB transcript;
  1123. uint8_t *transcript_data;
  1124. size_t transcript_len;
  1125. if (!CBB_init(&transcript,
  1126. 2 * SSL3_RANDOM_SIZE + hs->server_params_len) ||
  1127. !CBB_add_bytes(&transcript, ssl->s3->client_random,
  1128. SSL3_RANDOM_SIZE) ||
  1129. !CBB_add_bytes(&transcript, ssl->s3->server_random,
  1130. SSL3_RANDOM_SIZE) ||
  1131. !CBB_add_bytes(&transcript, hs->server_params,
  1132. hs->server_params_len) ||
  1133. !CBB_finish(&transcript, &transcript_data, &transcript_len)) {
  1134. CBB_cleanup(&transcript);
  1135. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1136. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1137. goto err;
  1138. }
  1139. sign_result = ssl_private_key_sign(ssl, ptr, &sig_len, max_sig_len,
  1140. signature_algorithm, transcript_data,
  1141. transcript_len);
  1142. OPENSSL_free(transcript_data);
  1143. } else {
  1144. assert(hs->state == SSL3_ST_SW_KEY_EXCH_B);
  1145. sign_result = ssl_private_key_complete(ssl, ptr, &sig_len, max_sig_len);
  1146. }
  1147. switch (sign_result) {
  1148. case ssl_private_key_success:
  1149. if (!CBB_did_write(&child, sig_len)) {
  1150. goto err;
  1151. }
  1152. break;
  1153. case ssl_private_key_failure:
  1154. goto err;
  1155. case ssl_private_key_retry:
  1156. ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1157. hs->state = SSL3_ST_SW_KEY_EXCH_B;
  1158. goto err;
  1159. }
  1160. }
  1161. if (!ssl_complete_message(ssl, &cbb)) {
  1162. goto err;
  1163. }
  1164. OPENSSL_free(hs->server_params);
  1165. hs->server_params = NULL;
  1166. hs->server_params_len = 0;
  1167. hs->state = SSL3_ST_SW_KEY_EXCH_C;
  1168. return ssl->method->write_message(ssl);
  1169. err:
  1170. CBB_cleanup(&cbb);
  1171. return -1;
  1172. }
  1173. static int add_cert_types(SSL *ssl, CBB *cbb) {
  1174. /* Get configured signature algorithms. */
  1175. int have_rsa_sign = 0;
  1176. int have_ecdsa_sign = 0;
  1177. const uint16_t *sig_algs;
  1178. size_t num_sig_algs = tls12_get_verify_sigalgs(ssl, &sig_algs);
  1179. for (size_t i = 0; i < num_sig_algs; i++) {
  1180. switch (sig_algs[i]) {
  1181. case SSL_SIGN_RSA_PKCS1_SHA512:
  1182. case SSL_SIGN_RSA_PKCS1_SHA384:
  1183. case SSL_SIGN_RSA_PKCS1_SHA256:
  1184. case SSL_SIGN_RSA_PKCS1_SHA1:
  1185. have_rsa_sign = 1;
  1186. break;
  1187. case SSL_SIGN_ECDSA_SECP521R1_SHA512:
  1188. case SSL_SIGN_ECDSA_SECP384R1_SHA384:
  1189. case SSL_SIGN_ECDSA_SECP256R1_SHA256:
  1190. case SSL_SIGN_ECDSA_SHA1:
  1191. have_ecdsa_sign = 1;
  1192. break;
  1193. }
  1194. }
  1195. if (have_rsa_sign && !CBB_add_u8(cbb, SSL3_CT_RSA_SIGN)) {
  1196. return 0;
  1197. }
  1198. /* ECDSA certs can be used with RSA cipher suites as well so we don't need to
  1199. * check for SSL_kECDH or SSL_kECDHE. */
  1200. if (ssl->version >= TLS1_VERSION && have_ecdsa_sign &&
  1201. !CBB_add_u8(cbb, TLS_CT_ECDSA_SIGN)) {
  1202. return 0;
  1203. }
  1204. return 1;
  1205. }
  1206. static int ssl3_send_certificate_request(SSL_HANDSHAKE *hs) {
  1207. SSL *const ssl = hs->ssl;
  1208. if (hs->state == SSL3_ST_SW_CERT_REQ_B) {
  1209. return ssl->method->write_message(ssl);
  1210. }
  1211. CBB cbb, body, cert_types, sigalgs_cbb;
  1212. if (!ssl->method->init_message(ssl, &cbb, &body,
  1213. SSL3_MT_CERTIFICATE_REQUEST) ||
  1214. !CBB_add_u8_length_prefixed(&body, &cert_types) ||
  1215. !add_cert_types(ssl, &cert_types)) {
  1216. goto err;
  1217. }
  1218. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1219. const uint16_t *sigalgs;
  1220. size_t num_sigalgs = tls12_get_verify_sigalgs(ssl, &sigalgs);
  1221. if (!CBB_add_u16_length_prefixed(&body, &sigalgs_cbb)) {
  1222. goto err;
  1223. }
  1224. for (size_t i = 0; i < num_sigalgs; i++) {
  1225. if (!CBB_add_u16(&sigalgs_cbb, sigalgs[i])) {
  1226. goto err;
  1227. }
  1228. }
  1229. }
  1230. if (!ssl_add_client_CA_list(ssl, &body) ||
  1231. !ssl_complete_message(ssl, &cbb)) {
  1232. goto err;
  1233. }
  1234. hs->state = SSL3_ST_SW_CERT_REQ_B;
  1235. return ssl->method->write_message(ssl);
  1236. err:
  1237. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1238. CBB_cleanup(&cbb);
  1239. return -1;
  1240. }
  1241. static int ssl3_send_server_hello_done(SSL_HANDSHAKE *hs) {
  1242. SSL *const ssl = hs->ssl;
  1243. if (hs->state == SSL3_ST_SW_SRVR_DONE_B) {
  1244. return ssl->method->write_message(ssl);
  1245. }
  1246. CBB cbb, body;
  1247. if (!ssl->method->init_message(ssl, &cbb, &body, SSL3_MT_SERVER_HELLO_DONE) ||
  1248. !ssl_complete_message(ssl, &cbb)) {
  1249. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1250. CBB_cleanup(&cbb);
  1251. return -1;
  1252. }
  1253. hs->state = SSL3_ST_SW_SRVR_DONE_B;
  1254. return ssl->method->write_message(ssl);
  1255. }
  1256. static int ssl3_get_client_certificate(SSL_HANDSHAKE *hs) {
  1257. SSL *const ssl = hs->ssl;
  1258. assert(hs->cert_request);
  1259. int msg_ret = ssl->method->ssl_get_message(ssl, -1, ssl_hash_message);
  1260. if (msg_ret <= 0) {
  1261. return msg_ret;
  1262. }
  1263. if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
  1264. if (ssl->version == SSL3_VERSION &&
  1265. ssl->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
  1266. /* In SSL 3.0, the Certificate message is omitted to signal no
  1267. * certificate. */
  1268. if (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
  1269. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1270. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1271. return -1;
  1272. }
  1273. /* OpenSSL returns X509_V_OK when no certificates are received. This is
  1274. * classed by them as a bug, but it's assumed by at least NGINX. */
  1275. ssl->s3->new_session->verify_result = X509_V_OK;
  1276. ssl->s3->tmp.reuse_message = 1;
  1277. return 1;
  1278. }
  1279. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  1280. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  1281. return -1;
  1282. }
  1283. CBS certificate_msg;
  1284. CBS_init(&certificate_msg, ssl->init_msg, ssl->init_num);
  1285. sk_CRYPTO_BUFFER_pop_free(ssl->s3->new_session->certs, CRYPTO_BUFFER_free);
  1286. EVP_PKEY_free(hs->peer_pubkey);
  1287. hs->peer_pubkey = NULL;
  1288. uint8_t alert;
  1289. ssl->s3->new_session->certs =
  1290. ssl_parse_cert_chain(&alert, &hs->peer_pubkey,
  1291. ssl->retain_only_sha256_of_client_certs
  1292. ? ssl->s3->new_session->peer_sha256
  1293. : NULL,
  1294. &certificate_msg, ssl->ctx->pool);
  1295. if (ssl->s3->new_session->certs == NULL) {
  1296. ssl3_send_alert(ssl, SSL3_AL_FATAL, alert);
  1297. return -1;
  1298. }
  1299. if (CBS_len(&certificate_msg) != 0 ||
  1300. !ssl_session_x509_cache_objects(ssl->s3->new_session)) {
  1301. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1302. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1303. return -1;
  1304. }
  1305. if (sk_CRYPTO_BUFFER_num(ssl->s3->new_session->certs) == 0) {
  1306. /* No client certificate so the handshake buffer may be discarded. */
  1307. ssl3_free_handshake_buffer(ssl);
  1308. /* In SSL 3.0, sending no certificate is signaled by omitting the
  1309. * Certificate message. */
  1310. if (ssl->version == SSL3_VERSION) {
  1311. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATES_RETURNED);
  1312. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1313. return -1;
  1314. }
  1315. if (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT) {
  1316. /* Fail for TLS only if we required a certificate */
  1317. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1318. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1319. return -1;
  1320. }
  1321. /* OpenSSL returns X509_V_OK when no certificates are received. This is
  1322. * classed by them as a bug, but it's assumed by at least NGINX. */
  1323. ssl->s3->new_session->verify_result = X509_V_OK;
  1324. return 1;
  1325. }
  1326. /* The hash will have been filled in. */
  1327. if (ssl->retain_only_sha256_of_client_certs) {
  1328. ssl->s3->new_session->peer_sha256_valid = 1;
  1329. }
  1330. if (!ssl_verify_cert_chain(ssl, &ssl->s3->new_session->verify_result,
  1331. ssl->s3->new_session->x509_chain)) {
  1332. return -1;
  1333. }
  1334. return 1;
  1335. }
  1336. static int ssl3_get_client_key_exchange(SSL_HANDSHAKE *hs) {
  1337. SSL *const ssl = hs->ssl;
  1338. int al;
  1339. CBS client_key_exchange;
  1340. uint32_t alg_k;
  1341. uint32_t alg_a;
  1342. uint8_t *premaster_secret = NULL;
  1343. size_t premaster_secret_len = 0;
  1344. uint8_t *decrypt_buf = NULL;
  1345. unsigned psk_len = 0;
  1346. uint8_t psk[PSK_MAX_PSK_LEN];
  1347. if (hs->state == SSL3_ST_SR_KEY_EXCH_A) {
  1348. int ret = ssl->method->ssl_get_message(ssl, SSL3_MT_CLIENT_KEY_EXCHANGE,
  1349. ssl_hash_message);
  1350. if (ret <= 0) {
  1351. return ret;
  1352. }
  1353. }
  1354. CBS_init(&client_key_exchange, ssl->init_msg, ssl->init_num);
  1355. alg_k = ssl->s3->tmp.new_cipher->algorithm_mkey;
  1356. alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  1357. /* If using a PSK key exchange, prepare the pre-shared key. */
  1358. if (alg_a & SSL_aPSK) {
  1359. CBS psk_identity;
  1360. /* If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
  1361. * then this is the only field in the message. */
  1362. if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
  1363. ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
  1364. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1365. al = SSL_AD_DECODE_ERROR;
  1366. goto f_err;
  1367. }
  1368. if (ssl->psk_server_callback == NULL) {
  1369. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_SERVER_CB);
  1370. al = SSL_AD_INTERNAL_ERROR;
  1371. goto f_err;
  1372. }
  1373. if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
  1374. CBS_contains_zero_byte(&psk_identity)) {
  1375. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  1376. al = SSL_AD_ILLEGAL_PARAMETER;
  1377. goto f_err;
  1378. }
  1379. if (!CBS_strdup(&psk_identity, &ssl->s3->new_session->psk_identity)) {
  1380. al = SSL_AD_INTERNAL_ERROR;
  1381. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1382. goto f_err;
  1383. }
  1384. /* Look up the key for the identity. */
  1385. psk_len = ssl->psk_server_callback(ssl, ssl->s3->new_session->psk_identity,
  1386. psk, sizeof(psk));
  1387. if (psk_len > PSK_MAX_PSK_LEN) {
  1388. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1389. al = SSL_AD_INTERNAL_ERROR;
  1390. goto f_err;
  1391. } else if (psk_len == 0) {
  1392. /* PSK related to the given identity not found */
  1393. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
  1394. al = SSL_AD_UNKNOWN_PSK_IDENTITY;
  1395. goto f_err;
  1396. }
  1397. }
  1398. /* Depending on the key exchange method, compute |premaster_secret| and
  1399. * |premaster_secret_len|. */
  1400. if (alg_k & SSL_kRSA) {
  1401. /* Allocate a buffer large enough for an RSA decryption. */
  1402. const size_t rsa_size = ssl_private_key_max_signature_len(ssl);
  1403. decrypt_buf = OPENSSL_malloc(rsa_size);
  1404. if (decrypt_buf == NULL) {
  1405. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1406. goto err;
  1407. }
  1408. enum ssl_private_key_result_t decrypt_result;
  1409. size_t decrypt_len;
  1410. if (hs->state == SSL3_ST_SR_KEY_EXCH_A) {
  1411. if (!ssl_has_private_key(ssl) ||
  1412. ssl_private_key_type(ssl) != NID_rsaEncryption) {
  1413. al = SSL_AD_HANDSHAKE_FAILURE;
  1414. OPENSSL_PUT_ERROR(SSL, SSL_R_MISSING_RSA_CERTIFICATE);
  1415. goto f_err;
  1416. }
  1417. CBS encrypted_premaster_secret;
  1418. if (ssl->version > SSL3_VERSION) {
  1419. if (!CBS_get_u16_length_prefixed(&client_key_exchange,
  1420. &encrypted_premaster_secret) ||
  1421. CBS_len(&client_key_exchange) != 0) {
  1422. al = SSL_AD_DECODE_ERROR;
  1423. OPENSSL_PUT_ERROR(SSL,
  1424. SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
  1425. goto f_err;
  1426. }
  1427. } else {
  1428. encrypted_premaster_secret = client_key_exchange;
  1429. }
  1430. /* Decrypt with no padding. PKCS#1 padding will be removed as part of the
  1431. * timing-sensitive code below. */
  1432. decrypt_result = ssl_private_key_decrypt(
  1433. ssl, decrypt_buf, &decrypt_len, rsa_size,
  1434. CBS_data(&encrypted_premaster_secret),
  1435. CBS_len(&encrypted_premaster_secret));
  1436. } else {
  1437. assert(hs->state == SSL3_ST_SR_KEY_EXCH_B);
  1438. /* Complete async decrypt. */
  1439. decrypt_result =
  1440. ssl_private_key_complete(ssl, decrypt_buf, &decrypt_len, rsa_size);
  1441. }
  1442. switch (decrypt_result) {
  1443. case ssl_private_key_success:
  1444. break;
  1445. case ssl_private_key_failure:
  1446. goto err;
  1447. case ssl_private_key_retry:
  1448. ssl->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1449. hs->state = SSL3_ST_SR_KEY_EXCH_B;
  1450. goto err;
  1451. }
  1452. if (decrypt_len != rsa_size) {
  1453. al = SSL_AD_DECRYPT_ERROR;
  1454. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
  1455. goto f_err;
  1456. }
  1457. /* Prepare a random premaster, to be used on invalid padding. See RFC 5246,
  1458. * section 7.4.7.1. */
  1459. premaster_secret_len = SSL_MAX_MASTER_KEY_LENGTH;
  1460. premaster_secret = OPENSSL_malloc(premaster_secret_len);
  1461. if (premaster_secret == NULL) {
  1462. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1463. goto err;
  1464. }
  1465. if (!RAND_bytes(premaster_secret, premaster_secret_len)) {
  1466. goto err;
  1467. }
  1468. /* The smallest padded premaster is 11 bytes of overhead. Small keys are
  1469. * publicly invalid. */
  1470. if (decrypt_len < 11 + premaster_secret_len) {
  1471. al = SSL_AD_DECRYPT_ERROR;
  1472. OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED);
  1473. goto f_err;
  1474. }
  1475. /* Check the padding. See RFC 3447, section 7.2.2. */
  1476. size_t padding_len = decrypt_len - premaster_secret_len;
  1477. uint8_t good = constant_time_eq_int_8(decrypt_buf[0], 0) &
  1478. constant_time_eq_int_8(decrypt_buf[1], 2);
  1479. for (size_t i = 2; i < padding_len - 1; i++) {
  1480. good &= ~constant_time_is_zero_8(decrypt_buf[i]);
  1481. }
  1482. good &= constant_time_is_zero_8(decrypt_buf[padding_len - 1]);
  1483. /* The premaster secret must begin with |client_version|. This too must be
  1484. * checked in constant time (http://eprint.iacr.org/2003/052/). */
  1485. good &= constant_time_eq_8(decrypt_buf[padding_len],
  1486. (unsigned)(hs->client_version >> 8));
  1487. good &= constant_time_eq_8(decrypt_buf[padding_len + 1],
  1488. (unsigned)(hs->client_version & 0xff));
  1489. /* Select, in constant time, either the decrypted premaster or the random
  1490. * premaster based on |good|. */
  1491. for (size_t i = 0; i < premaster_secret_len; i++) {
  1492. premaster_secret[i] = constant_time_select_8(
  1493. good, decrypt_buf[padding_len + i], premaster_secret[i]);
  1494. }
  1495. OPENSSL_free(decrypt_buf);
  1496. decrypt_buf = NULL;
  1497. } else if (alg_k & (SSL_kECDHE|SSL_kDHE)) {
  1498. /* Parse the ClientKeyExchange. */
  1499. CBS peer_key;
  1500. if (!SSL_ECDH_CTX_get_key(&hs->ecdh_ctx, &client_key_exchange, &peer_key) ||
  1501. CBS_len(&client_key_exchange) != 0) {
  1502. al = SSL_AD_DECODE_ERROR;
  1503. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1504. goto f_err;
  1505. }
  1506. /* Compute the premaster. */
  1507. uint8_t alert;
  1508. if (!SSL_ECDH_CTX_finish(&hs->ecdh_ctx, &premaster_secret,
  1509. &premaster_secret_len, &alert, CBS_data(&peer_key),
  1510. CBS_len(&peer_key))) {
  1511. al = alert;
  1512. goto f_err;
  1513. }
  1514. /* The key exchange state may now be discarded. */
  1515. SSL_ECDH_CTX_cleanup(&hs->ecdh_ctx);
  1516. } else if (alg_k & SSL_kPSK) {
  1517. /* For plain PSK, other_secret is a block of 0s with the same length as the
  1518. * pre-shared key. */
  1519. premaster_secret_len = psk_len;
  1520. premaster_secret = OPENSSL_malloc(premaster_secret_len);
  1521. if (premaster_secret == NULL) {
  1522. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1523. goto err;
  1524. }
  1525. memset(premaster_secret, 0, premaster_secret_len);
  1526. } else {
  1527. al = SSL_AD_HANDSHAKE_FAILURE;
  1528. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_TYPE);
  1529. goto f_err;
  1530. }
  1531. /* For a PSK cipher suite, the actual pre-master secret is combined with the
  1532. * pre-shared key. */
  1533. if (alg_a & SSL_aPSK) {
  1534. CBB new_premaster, child;
  1535. uint8_t *new_data;
  1536. size_t new_len;
  1537. CBB_zero(&new_premaster);
  1538. if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len) ||
  1539. !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1540. !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
  1541. !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1542. !CBB_add_bytes(&child, psk, psk_len) ||
  1543. !CBB_finish(&new_premaster, &new_data, &new_len)) {
  1544. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1545. CBB_cleanup(&new_premaster);
  1546. goto err;
  1547. }
  1548. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1549. OPENSSL_free(premaster_secret);
  1550. premaster_secret = new_data;
  1551. premaster_secret_len = new_len;
  1552. }
  1553. /* Compute the master secret */
  1554. ssl->s3->new_session->master_key_length = tls1_generate_master_secret(
  1555. ssl, ssl->s3->new_session->master_key, premaster_secret,
  1556. premaster_secret_len);
  1557. if (ssl->s3->new_session->master_key_length == 0) {
  1558. goto err;
  1559. }
  1560. ssl->s3->new_session->extended_master_secret =
  1561. ssl->s3->tmp.extended_master_secret;
  1562. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1563. OPENSSL_free(premaster_secret);
  1564. return 1;
  1565. f_err:
  1566. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1567. err:
  1568. if (premaster_secret != NULL) {
  1569. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1570. OPENSSL_free(premaster_secret);
  1571. }
  1572. OPENSSL_free(decrypt_buf);
  1573. return -1;
  1574. }
  1575. static int ssl3_get_cert_verify(SSL_HANDSHAKE *hs) {
  1576. SSL *const ssl = hs->ssl;
  1577. int al;
  1578. CBS certificate_verify, signature;
  1579. /* Only RSA and ECDSA client certificates are supported, so a
  1580. * CertificateVerify is required if and only if there's a client certificate.
  1581. * */
  1582. if (hs->peer_pubkey == NULL) {
  1583. ssl3_free_handshake_buffer(ssl);
  1584. return 1;
  1585. }
  1586. int msg_ret = ssl->method->ssl_get_message(ssl, SSL3_MT_CERTIFICATE_VERIFY,
  1587. ssl_dont_hash_message);
  1588. if (msg_ret <= 0) {
  1589. return msg_ret;
  1590. }
  1591. CBS_init(&certificate_verify, ssl->init_msg, ssl->init_num);
  1592. /* Determine the digest type if needbe. */
  1593. uint16_t signature_algorithm = 0;
  1594. if (ssl3_protocol_version(ssl) >= TLS1_2_VERSION) {
  1595. if (!CBS_get_u16(&certificate_verify, &signature_algorithm)) {
  1596. al = SSL_AD_DECODE_ERROR;
  1597. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1598. goto f_err;
  1599. }
  1600. if (!tls12_check_peer_sigalg(ssl, &al, signature_algorithm)) {
  1601. goto f_err;
  1602. }
  1603. ssl->s3->tmp.peer_signature_algorithm = signature_algorithm;
  1604. } else if (hs->peer_pubkey->type == EVP_PKEY_RSA) {
  1605. signature_algorithm = SSL_SIGN_RSA_PKCS1_MD5_SHA1;
  1606. } else if (hs->peer_pubkey->type == EVP_PKEY_EC) {
  1607. signature_algorithm = SSL_SIGN_ECDSA_SHA1;
  1608. } else {
  1609. al = SSL_AD_UNSUPPORTED_CERTIFICATE;
  1610. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
  1611. goto f_err;
  1612. }
  1613. /* Parse and verify the signature. */
  1614. if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
  1615. CBS_len(&certificate_verify) != 0) {
  1616. al = SSL_AD_DECODE_ERROR;
  1617. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1618. goto f_err;
  1619. }
  1620. int sig_ok;
  1621. /* The SSL3 construction for CertificateVerify does not decompose into a
  1622. * single final digest and signature, and must be special-cased. */
  1623. if (ssl3_protocol_version(ssl) == SSL3_VERSION) {
  1624. const EVP_MD *md;
  1625. uint8_t digest[EVP_MAX_MD_SIZE];
  1626. size_t digest_len;
  1627. if (!ssl3_cert_verify_hash(ssl, &md, digest, &digest_len,
  1628. signature_algorithm)) {
  1629. goto err;
  1630. }
  1631. EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(hs->peer_pubkey, NULL);
  1632. sig_ok = pctx != NULL &&
  1633. EVP_PKEY_verify_init(pctx) &&
  1634. EVP_PKEY_CTX_set_signature_md(pctx, md) &&
  1635. EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature),
  1636. digest, digest_len);
  1637. EVP_PKEY_CTX_free(pctx);
  1638. } else {
  1639. sig_ok = ssl_public_key_verify(
  1640. ssl, CBS_data(&signature), CBS_len(&signature), signature_algorithm,
  1641. hs->peer_pubkey, (const uint8_t *)ssl->s3->handshake_buffer->data,
  1642. ssl->s3->handshake_buffer->length);
  1643. }
  1644. #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
  1645. sig_ok = 1;
  1646. ERR_clear_error();
  1647. #endif
  1648. if (!sig_ok) {
  1649. al = SSL_AD_DECRYPT_ERROR;
  1650. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
  1651. goto f_err;
  1652. }
  1653. /* The handshake buffer is no longer necessary, and we may hash the current
  1654. * message.*/
  1655. ssl3_free_handshake_buffer(ssl);
  1656. if (!ssl_hash_current_message(ssl)) {
  1657. goto err;
  1658. }
  1659. return 1;
  1660. f_err:
  1661. ssl3_send_alert(ssl, SSL3_AL_FATAL, al);
  1662. err:
  1663. return 0;
  1664. }
  1665. /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
  1666. * sets the next_proto member in s if found */
  1667. static int ssl3_get_next_proto(SSL_HANDSHAKE *hs) {
  1668. SSL *const ssl = hs->ssl;
  1669. int ret =
  1670. ssl->method->ssl_get_message(ssl, SSL3_MT_NEXT_PROTO, ssl_hash_message);
  1671. if (ret <= 0) {
  1672. return ret;
  1673. }
  1674. CBS next_protocol, selected_protocol, padding;
  1675. CBS_init(&next_protocol, ssl->init_msg, ssl->init_num);
  1676. if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
  1677. !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
  1678. CBS_len(&next_protocol) != 0) {
  1679. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1680. ssl3_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1681. return 0;
  1682. }
  1683. if (!CBS_stow(&selected_protocol, &ssl->s3->next_proto_negotiated,
  1684. &ssl->s3->next_proto_negotiated_len)) {
  1685. return 0;
  1686. }
  1687. return 1;
  1688. }
  1689. /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
  1690. static int ssl3_get_channel_id(SSL_HANDSHAKE *hs) {
  1691. SSL *const ssl = hs->ssl;
  1692. int msg_ret = ssl->method->ssl_get_message(ssl, SSL3_MT_CHANNEL_ID,
  1693. ssl_dont_hash_message);
  1694. if (msg_ret <= 0) {
  1695. return msg_ret;
  1696. }
  1697. if (!tls1_verify_channel_id(ssl) ||
  1698. !ssl_hash_current_message(ssl)) {
  1699. return -1;
  1700. }
  1701. return 1;
  1702. }
  1703. static int ssl3_send_new_session_ticket(SSL_HANDSHAKE *hs) {
  1704. SSL *const ssl = hs->ssl;
  1705. if (hs->state == SSL3_ST_SW_SESSION_TICKET_B) {
  1706. return ssl->method->write_message(ssl);
  1707. }
  1708. const SSL_SESSION *session;
  1709. SSL_SESSION *session_copy = NULL;
  1710. if (ssl->session == NULL) {
  1711. /* Fix the timeout to measure from the ticket issuance time. */
  1712. ssl_session_refresh_time(ssl, ssl->s3->new_session);
  1713. session = ssl->s3->new_session;
  1714. } else {
  1715. /* We are renewing an existing session. Duplicate the session to adjust the
  1716. * timeout. */
  1717. session_copy = SSL_SESSION_dup(ssl->session, SSL_SESSION_INCLUDE_NONAUTH);
  1718. if (session_copy == NULL) {
  1719. return -1;
  1720. }
  1721. ssl_session_refresh_time(ssl, session_copy);
  1722. session = session_copy;
  1723. }
  1724. CBB cbb, body, ticket;
  1725. int ok =
  1726. ssl->method->init_message(ssl, &cbb, &body, SSL3_MT_NEW_SESSION_TICKET) &&
  1727. CBB_add_u32(&body, session->timeout) &&
  1728. CBB_add_u16_length_prefixed(&body, &ticket) &&
  1729. ssl_encrypt_ticket(ssl, &ticket, session) &&
  1730. ssl_complete_message(ssl, &cbb);
  1731. SSL_SESSION_free(session_copy);
  1732. CBB_cleanup(&cbb);
  1733. if (!ok) {
  1734. return -1;
  1735. }
  1736. hs->state = SSL3_ST_SW_SESSION_TICKET_B;
  1737. return ssl->method->write_message(ssl);
  1738. }