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.
 
 
 
 
 
 

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