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.
 
 
 
 
 
 

2265 lines
71 KiB

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