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.
 
 
 
 
 
 

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