Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

2272 Zeilen
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_error();
  181. ERR_clear_system_error();
  182. if (ssl->info_callback != NULL) {
  183. cb = ssl->info_callback;
  184. } else if (ssl->ctx->info_callback != NULL) {
  185. cb = ssl->ctx->info_callback;
  186. }
  187. ssl->in_handshake++;
  188. if (ssl->cert == NULL) {
  189. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATE_SET);
  190. return -1;
  191. }
  192. for (;;) {
  193. state = ssl->state;
  194. switch (ssl->state) {
  195. case SSL_ST_ACCEPT:
  196. if (cb != NULL) {
  197. cb(ssl, SSL_CB_HANDSHAKE_START, 1);
  198. }
  199. if (ssl->init_buf == NULL) {
  200. buf = BUF_MEM_new();
  201. if (!buf || !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
  202. ret = -1;
  203. goto end;
  204. }
  205. ssl->init_buf = buf;
  206. buf = NULL;
  207. }
  208. ssl->init_num = 0;
  209. /* Enable a write buffer. This groups handshake messages within a flight
  210. * into a single write. */
  211. if (!ssl_init_wbio_buffer(ssl, 1)) {
  212. ret = -1;
  213. goto end;
  214. }
  215. if (!ssl3_init_handshake_buffer(ssl)) {
  216. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  217. ret = -1;
  218. goto end;
  219. }
  220. if (!ssl->s3->have_version) {
  221. ssl->state = SSL3_ST_SR_INITIAL_BYTES;
  222. } else {
  223. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  224. }
  225. break;
  226. case SSL3_ST_SR_INITIAL_BYTES:
  227. ret = ssl3_get_initial_bytes(ssl);
  228. if (ret <= 0) {
  229. goto end;
  230. }
  231. /* ssl3_get_initial_bytes sets ssl->state to one of
  232. * SSL3_ST_SR_V2_CLIENT_HELLO or SSL3_ST_SR_CLNT_HELLO_A on success. */
  233. break;
  234. case SSL3_ST_SR_V2_CLIENT_HELLO:
  235. ret = ssl3_get_v2_client_hello(ssl);
  236. if (ret <= 0) {
  237. goto end;
  238. }
  239. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  240. break;
  241. case SSL3_ST_SR_CLNT_HELLO_A:
  242. case SSL3_ST_SR_CLNT_HELLO_B:
  243. case SSL3_ST_SR_CLNT_HELLO_C:
  244. case SSL3_ST_SR_CLNT_HELLO_D:
  245. ssl->shutdown = 0;
  246. ret = ssl3_get_client_hello(ssl);
  247. if (ret <= 0) {
  248. goto end;
  249. }
  250. ssl->state = SSL3_ST_SW_SRVR_HELLO_A;
  251. ssl->init_num = 0;
  252. break;
  253. case SSL3_ST_SW_SRVR_HELLO_A:
  254. case SSL3_ST_SW_SRVR_HELLO_B:
  255. ret = ssl3_send_server_hello(ssl);
  256. if (ret <= 0) {
  257. goto end;
  258. }
  259. if (ssl->hit) {
  260. if (ssl->tlsext_ticket_expected) {
  261. ssl->state = SSL3_ST_SW_SESSION_TICKET_A;
  262. } else {
  263. ssl->state = SSL3_ST_SW_CHANGE_A;
  264. }
  265. } else {
  266. ssl->state = SSL3_ST_SW_CERT_A;
  267. }
  268. ssl->init_num = 0;
  269. break;
  270. case SSL3_ST_SW_CERT_A:
  271. case SSL3_ST_SW_CERT_B:
  272. if (ssl_cipher_has_server_public_key(ssl->s3->tmp.new_cipher)) {
  273. ret = ssl3_send_server_certificate(ssl);
  274. if (ret <= 0) {
  275. goto end;
  276. }
  277. if (ssl->s3->tmp.certificate_status_expected) {
  278. ssl->state = SSL3_ST_SW_CERT_STATUS_A;
  279. } else {
  280. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  281. }
  282. } else {
  283. skip = 1;
  284. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  285. }
  286. ssl->init_num = 0;
  287. break;
  288. case SSL3_ST_SW_CERT_STATUS_A:
  289. case SSL3_ST_SW_CERT_STATUS_B:
  290. ret = ssl3_send_certificate_status(ssl);
  291. if (ret <= 0) {
  292. goto end;
  293. }
  294. ssl->state = SSL3_ST_SW_KEY_EXCH_A;
  295. ssl->init_num = 0;
  296. break;
  297. case SSL3_ST_SW_KEY_EXCH_A:
  298. case SSL3_ST_SW_KEY_EXCH_B:
  299. case SSL3_ST_SW_KEY_EXCH_C:
  300. alg_a = ssl->s3->tmp.new_cipher->algorithm_auth;
  301. /* Send a ServerKeyExchange message if:
  302. * - The key exchange is ephemeral or anonymous
  303. * Diffie-Hellman.
  304. * - There is a PSK identity hint.
  305. *
  306. * TODO(davidben): This logic is currently duplicated in d1_srvr.c. Fix
  307. * this. In the meantime, keep them in sync. */
  308. if (ssl_cipher_requires_server_key_exchange(ssl->s3->tmp.new_cipher) ||
  309. ((alg_a & SSL_aPSK) && ssl->psk_identity_hint)) {
  310. ret = ssl3_send_server_key_exchange(ssl);
  311. if (ret <= 0) {
  312. goto end;
  313. }
  314. } else {
  315. skip = 1;
  316. }
  317. ssl->state = SSL3_ST_SW_CERT_REQ_A;
  318. ssl->init_num = 0;
  319. break;
  320. case SSL3_ST_SW_CERT_REQ_A:
  321. case SSL3_ST_SW_CERT_REQ_B:
  322. if (ssl->s3->tmp.cert_request) {
  323. ret = ssl3_send_certificate_request(ssl);
  324. if (ret <= 0) {
  325. goto end;
  326. }
  327. } else {
  328. skip = 1;
  329. }
  330. ssl->state = SSL3_ST_SW_SRVR_DONE_A;
  331. ssl->init_num = 0;
  332. break;
  333. case SSL3_ST_SW_SRVR_DONE_A:
  334. case SSL3_ST_SW_SRVR_DONE_B:
  335. ret = ssl3_send_server_done(ssl);
  336. if (ret <= 0) {
  337. goto end;
  338. }
  339. ssl->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
  340. ssl->state = SSL3_ST_SW_FLUSH;
  341. ssl->init_num = 0;
  342. break;
  343. case SSL3_ST_SW_FLUSH:
  344. /* This code originally checked to see if any data was pending using
  345. * BIO_CTRL_INFO and then flushed. This caused problems as documented
  346. * in PR#1939. The proposed fix doesn't completely resolve this issue
  347. * as buggy implementations of BIO_CTRL_PENDING still exist. So instead
  348. * we just flush unconditionally. */
  349. ssl->rwstate = SSL_WRITING;
  350. if (BIO_flush(ssl->wbio) <= 0) {
  351. ret = -1;
  352. goto end;
  353. }
  354. ssl->rwstate = SSL_NOTHING;
  355. ssl->state = ssl->s3->tmp.next_state;
  356. break;
  357. case SSL3_ST_SR_CERT_A:
  358. case SSL3_ST_SR_CERT_B:
  359. if (ssl->s3->tmp.cert_request) {
  360. ret = ssl3_get_client_certificate(ssl);
  361. if (ret <= 0) {
  362. goto end;
  363. }
  364. }
  365. ssl->init_num = 0;
  366. ssl->state = SSL3_ST_SR_KEY_EXCH_A;
  367. break;
  368. case SSL3_ST_SR_KEY_EXCH_A:
  369. case SSL3_ST_SR_KEY_EXCH_B:
  370. case SSL3_ST_SR_KEY_EXCH_C:
  371. ret = ssl3_get_client_key_exchange(ssl);
  372. if (ret <= 0) {
  373. goto end;
  374. }
  375. ssl->state = SSL3_ST_SR_CERT_VRFY_A;
  376. ssl->init_num = 0;
  377. break;
  378. case SSL3_ST_SR_CERT_VRFY_A:
  379. case SSL3_ST_SR_CERT_VRFY_B:
  380. ret = ssl3_get_cert_verify(ssl);
  381. if (ret <= 0) {
  382. goto end;
  383. }
  384. ssl->state = SSL3_ST_SR_CHANGE;
  385. ssl->init_num = 0;
  386. break;
  387. case SSL3_ST_SR_CHANGE:
  388. ret = ssl->method->ssl_read_change_cipher_spec(ssl);
  389. if (ret <= 0) {
  390. goto end;
  391. }
  392. if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_SERVER_READ)) {
  393. ret = -1;
  394. goto end;
  395. }
  396. if (ssl->s3->next_proto_neg_seen) {
  397. ssl->state = SSL3_ST_SR_NEXT_PROTO_A;
  398. } else if (ssl->s3->tlsext_channel_id_valid) {
  399. ssl->state = SSL3_ST_SR_CHANNEL_ID_A;
  400. } else {
  401. ssl->state = SSL3_ST_SR_FINISHED_A;
  402. }
  403. break;
  404. case SSL3_ST_SR_NEXT_PROTO_A:
  405. case SSL3_ST_SR_NEXT_PROTO_B:
  406. ret = ssl3_get_next_proto(ssl);
  407. if (ret <= 0) {
  408. goto end;
  409. }
  410. ssl->init_num = 0;
  411. if (ssl->s3->tlsext_channel_id_valid) {
  412. ssl->state = SSL3_ST_SR_CHANNEL_ID_A;
  413. } else {
  414. ssl->state = SSL3_ST_SR_FINISHED_A;
  415. }
  416. break;
  417. case SSL3_ST_SR_CHANNEL_ID_A:
  418. case SSL3_ST_SR_CHANNEL_ID_B:
  419. ret = ssl3_get_channel_id(ssl);
  420. if (ret <= 0) {
  421. goto end;
  422. }
  423. ssl->init_num = 0;
  424. ssl->state = SSL3_ST_SR_FINISHED_A;
  425. break;
  426. case SSL3_ST_SR_FINISHED_A:
  427. case SSL3_ST_SR_FINISHED_B:
  428. ret = ssl3_get_finished(ssl, SSL3_ST_SR_FINISHED_A,
  429. SSL3_ST_SR_FINISHED_B);
  430. if (ret <= 0) {
  431. goto end;
  432. }
  433. if (ssl->hit) {
  434. ssl->state = SSL_ST_OK;
  435. } else if (ssl->tlsext_ticket_expected) {
  436. ssl->state = SSL3_ST_SW_SESSION_TICKET_A;
  437. } else {
  438. ssl->state = SSL3_ST_SW_CHANGE_A;
  439. }
  440. /* If this is a full handshake with ChannelID then record the hashshake
  441. * hashes in |ssl->session| in case we need them to verify a ChannelID
  442. * signature on a resumption of this session in the future. */
  443. if (!ssl->hit && ssl->s3->tlsext_channel_id_valid) {
  444. ret = tls1_record_handshake_hashes_for_channel_id(ssl);
  445. if (ret <= 0) {
  446. goto end;
  447. }
  448. }
  449. ssl->init_num = 0;
  450. break;
  451. case SSL3_ST_SW_SESSION_TICKET_A:
  452. case SSL3_ST_SW_SESSION_TICKET_B:
  453. ret = ssl3_send_new_session_ticket(ssl);
  454. if (ret <= 0) {
  455. goto end;
  456. }
  457. ssl->state = SSL3_ST_SW_CHANGE_A;
  458. ssl->init_num = 0;
  459. break;
  460. case SSL3_ST_SW_CHANGE_A:
  461. case SSL3_ST_SW_CHANGE_B:
  462. ret = ssl3_send_change_cipher_spec(ssl, SSL3_ST_SW_CHANGE_A,
  463. SSL3_ST_SW_CHANGE_B);
  464. if (ret <= 0) {
  465. goto end;
  466. }
  467. ssl->state = SSL3_ST_SW_FINISHED_A;
  468. ssl->init_num = 0;
  469. if (!tls1_change_cipher_state(ssl, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
  470. ret = -1;
  471. goto end;
  472. }
  473. break;
  474. case SSL3_ST_SW_FINISHED_A:
  475. case SSL3_ST_SW_FINISHED_B:
  476. ret = ssl3_send_finished(ssl, SSL3_ST_SW_FINISHED_A,
  477. SSL3_ST_SW_FINISHED_B);
  478. if (ret <= 0) {
  479. goto end;
  480. }
  481. ssl->state = SSL3_ST_SW_FLUSH;
  482. if (ssl->hit) {
  483. ssl->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
  484. } else {
  485. ssl->s3->tmp.next_state = SSL_ST_OK;
  486. }
  487. ssl->init_num = 0;
  488. break;
  489. case SSL_ST_OK:
  490. /* clean a few things up */
  491. ssl3_cleanup_key_block(ssl);
  492. BUF_MEM_free(ssl->init_buf);
  493. ssl->init_buf = NULL;
  494. /* remove buffering on output */
  495. ssl_free_wbio_buffer(ssl);
  496. ssl->init_num = 0;
  497. /* If we aren't retaining peer certificates then we can discard it
  498. * now. */
  499. if (ssl->ctx->retain_only_sha256_of_client_certs) {
  500. X509_free(ssl->session->peer);
  501. ssl->session->peer = NULL;
  502. sk_X509_pop_free(ssl->session->cert_chain, X509_free);
  503. ssl->session->cert_chain = NULL;
  504. }
  505. ssl->s3->initial_handshake_complete = 1;
  506. ssl_update_cache(ssl, SSL_SESS_CACHE_SERVER);
  507. if (cb != NULL) {
  508. cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
  509. }
  510. ret = 1;
  511. goto end;
  512. default:
  513. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  514. ret = -1;
  515. goto end;
  516. }
  517. if (!ssl->s3->tmp.reuse_message && !skip && cb != NULL &&
  518. ssl->state != state) {
  519. new_state = ssl->state;
  520. ssl->state = state;
  521. cb(ssl, SSL_CB_ACCEPT_LOOP, 1);
  522. ssl->state = new_state;
  523. }
  524. skip = 0;
  525. }
  526. end:
  527. ssl->in_handshake--;
  528. BUF_MEM_free(buf);
  529. if (cb != NULL) {
  530. cb(ssl, SSL_CB_ACCEPT_EXIT, ret);
  531. }
  532. return ret;
  533. }
  534. int ssl3_get_initial_bytes(SSL *ssl) {
  535. /* Read the first 5 bytes, the size of the TLS record header. This is
  536. * sufficient to detect a V2ClientHello and ensures that we never read beyond
  537. * the first record. */
  538. int ret = ssl_read_buffer_extend_to(ssl, SSL3_RT_HEADER_LENGTH);
  539. if (ret <= 0) {
  540. return ret;
  541. }
  542. assert(ssl_read_buffer_len(ssl) == SSL3_RT_HEADER_LENGTH);
  543. const uint8_t *p = ssl_read_buffer(ssl);
  544. /* Some dedicated error codes for protocol mixups should the application wish
  545. * to interpret them differently. (These do not overlap with ClientHello or
  546. * V2ClientHello.) */
  547. if (strncmp("GET ", (const char *)p, 4) == 0 ||
  548. strncmp("POST ", (const char *)p, 5) == 0 ||
  549. strncmp("HEAD ", (const char *)p, 5) == 0 ||
  550. strncmp("PUT ", (const char *)p, 4) == 0) {
  551. OPENSSL_PUT_ERROR(SSL, SSL_R_HTTP_REQUEST);
  552. return -1;
  553. }
  554. if (strncmp("CONNE", (const char *)p, 5) == 0) {
  555. OPENSSL_PUT_ERROR(SSL, SSL_R_HTTPS_PROXY_REQUEST);
  556. return -1;
  557. }
  558. /* Determine if this is a V2ClientHello. */
  559. if ((p[0] & 0x80) && p[2] == SSL2_MT_CLIENT_HELLO &&
  560. p[3] >= SSL3_VERSION_MAJOR) {
  561. /* This is a V2ClientHello. */
  562. ssl->state = SSL3_ST_SR_V2_CLIENT_HELLO;
  563. return 1;
  564. }
  565. /* Fall through to the standard logic. */
  566. ssl->state = SSL3_ST_SR_CLNT_HELLO_A;
  567. return 1;
  568. }
  569. int ssl3_get_v2_client_hello(SSL *ssl) {
  570. const uint8_t *p;
  571. int ret;
  572. CBS v2_client_hello, cipher_specs, session_id, challenge;
  573. size_t msg_length, rand_len, len;
  574. uint8_t msg_type;
  575. uint16_t version, cipher_spec_length, session_id_length, challenge_length;
  576. CBB client_hello, hello_body, cipher_suites;
  577. uint8_t random[SSL3_RANDOM_SIZE];
  578. /* Determine the length of the V2ClientHello. */
  579. assert(ssl_read_buffer_len(ssl) >= SSL3_RT_HEADER_LENGTH);
  580. p = ssl_read_buffer(ssl);
  581. msg_length = ((p[0] & 0x7f) << 8) | p[1];
  582. if (msg_length > (1024 * 4)) {
  583. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_TOO_LARGE);
  584. return -1;
  585. }
  586. if (msg_length < SSL3_RT_HEADER_LENGTH - 2) {
  587. /* Reject lengths that are too short early. We have already read
  588. * |SSL3_RT_HEADER_LENGTH| bytes, so we should not attempt to process an
  589. * (invalid) V2ClientHello which would be shorter than that. */
  590. OPENSSL_PUT_ERROR(SSL, SSL_R_RECORD_LENGTH_MISMATCH);
  591. return -1;
  592. }
  593. /* Read the remainder of the V2ClientHello. */
  594. ret = ssl_read_buffer_extend_to(ssl, 2 + msg_length);
  595. if (ret <= 0) {
  596. return ret;
  597. }
  598. assert(ssl_read_buffer_len(ssl) == msg_length + 2);
  599. CBS_init(&v2_client_hello, ssl_read_buffer(ssl) + 2, msg_length);
  600. /* The V2ClientHello without the length is incorporated into the handshake
  601. * hash. */
  602. if (!ssl3_update_handshake_hash(ssl, CBS_data(&v2_client_hello),
  603. CBS_len(&v2_client_hello))) {
  604. return -1;
  605. }
  606. if (ssl->msg_callback) {
  607. ssl->msg_callback(0, SSL2_VERSION, 0, CBS_data(&v2_client_hello),
  608. CBS_len(&v2_client_hello), ssl, ssl->msg_callback_arg);
  609. }
  610. if (!CBS_get_u8(&v2_client_hello, &msg_type) ||
  611. !CBS_get_u16(&v2_client_hello, &version) ||
  612. !CBS_get_u16(&v2_client_hello, &cipher_spec_length) ||
  613. !CBS_get_u16(&v2_client_hello, &session_id_length) ||
  614. !CBS_get_u16(&v2_client_hello, &challenge_length) ||
  615. !CBS_get_bytes(&v2_client_hello, &cipher_specs, cipher_spec_length) ||
  616. !CBS_get_bytes(&v2_client_hello, &session_id, session_id_length) ||
  617. !CBS_get_bytes(&v2_client_hello, &challenge, challenge_length) ||
  618. CBS_len(&v2_client_hello) != 0) {
  619. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  620. return -1;
  621. }
  622. /* msg_type has already been checked. */
  623. assert(msg_type == SSL2_MT_CLIENT_HELLO);
  624. /* The client_random is the V2ClientHello challenge. Truncate or
  625. * left-pad with zeros as needed. */
  626. memset(random, 0, SSL3_RANDOM_SIZE);
  627. rand_len = CBS_len(&challenge);
  628. if (rand_len > SSL3_RANDOM_SIZE) {
  629. rand_len = SSL3_RANDOM_SIZE;
  630. }
  631. memcpy(random + (SSL3_RANDOM_SIZE - rand_len), CBS_data(&challenge),
  632. rand_len);
  633. /* Write out an equivalent SSLv3 ClientHello. */
  634. CBB_zero(&client_hello);
  635. if (!CBB_init_fixed(&client_hello, (uint8_t *)ssl->init_buf->data,
  636. ssl->init_buf->max) ||
  637. !CBB_add_u8(&client_hello, SSL3_MT_CLIENT_HELLO) ||
  638. !CBB_add_u24_length_prefixed(&client_hello, &hello_body) ||
  639. !CBB_add_u16(&hello_body, version) ||
  640. !CBB_add_bytes(&hello_body, random, SSL3_RANDOM_SIZE) ||
  641. /* No session id. */
  642. !CBB_add_u8(&hello_body, 0) ||
  643. !CBB_add_u16_length_prefixed(&hello_body, &cipher_suites)) {
  644. CBB_cleanup(&client_hello);
  645. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  646. return -1;
  647. }
  648. /* Copy the cipher suites. */
  649. while (CBS_len(&cipher_specs) > 0) {
  650. uint32_t cipher_spec;
  651. if (!CBS_get_u24(&cipher_specs, &cipher_spec)) {
  652. CBB_cleanup(&client_hello);
  653. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  654. return -1;
  655. }
  656. /* Skip SSLv2 ciphers. */
  657. if ((cipher_spec & 0xff0000) != 0) {
  658. continue;
  659. }
  660. if (!CBB_add_u16(&cipher_suites, cipher_spec)) {
  661. CBB_cleanup(&client_hello);
  662. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  663. return -1;
  664. }
  665. }
  666. /* Add the null compression scheme and finish. */
  667. if (!CBB_add_u8(&hello_body, 1) || !CBB_add_u8(&hello_body, 0) ||
  668. !CBB_finish(&client_hello, NULL, &len)) {
  669. CBB_cleanup(&client_hello);
  670. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  671. return -1;
  672. }
  673. /* Mark the message for "re"-use by the version-specific method. */
  674. ssl->s3->tmp.reuse_message = 1;
  675. ssl->s3->tmp.message_type = SSL3_MT_CLIENT_HELLO;
  676. /* The handshake message header is 4 bytes. */
  677. ssl->s3->tmp.message_size = len - 4;
  678. /* Consume and discard the V2ClientHello. */
  679. ssl_read_buffer_consume(ssl, 2 + msg_length);
  680. ssl_read_buffer_discard(ssl);
  681. return 1;
  682. }
  683. int ssl3_get_client_hello(SSL *ssl) {
  684. int ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
  685. long n;
  686. const SSL_CIPHER *c;
  687. STACK_OF(SSL_CIPHER) *ciphers = NULL;
  688. struct ssl_early_callback_ctx early_ctx;
  689. CBS client_hello;
  690. uint16_t client_version;
  691. CBS client_random, session_id, cipher_suites, compression_methods;
  692. SSL_SESSION *session = NULL;
  693. /* We do this so that we will respond with our native type. If we are TLSv1
  694. * and we get SSLv3, we will respond with TLSv1, This down switching should
  695. * be handled by a different method. If we are SSLv3, we will respond with
  696. * SSLv3, even if prompted with TLSv1. */
  697. switch (ssl->state) {
  698. case SSL3_ST_SR_CLNT_HELLO_A:
  699. case SSL3_ST_SR_CLNT_HELLO_B:
  700. n = ssl->method->ssl_get_message(
  701. ssl, SSL3_ST_SR_CLNT_HELLO_A, SSL3_ST_SR_CLNT_HELLO_B,
  702. SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH,
  703. ssl_hash_message, &ok);
  704. if (!ok) {
  705. return n;
  706. }
  707. ssl->state = SSL3_ST_SR_CLNT_HELLO_C;
  708. /* fallthrough */
  709. case SSL3_ST_SR_CLNT_HELLO_C:
  710. case SSL3_ST_SR_CLNT_HELLO_D:
  711. /* We have previously parsed the ClientHello message, and can't call
  712. * ssl_get_message again without hashing the message into the Finished
  713. * digest again. */
  714. n = ssl->init_num;
  715. memset(&early_ctx, 0, sizeof(early_ctx));
  716. early_ctx.ssl = ssl;
  717. early_ctx.client_hello = ssl->init_msg;
  718. early_ctx.client_hello_len = n;
  719. if (!ssl_early_callback_init(&early_ctx)) {
  720. al = SSL_AD_DECODE_ERROR;
  721. OPENSSL_PUT_ERROR(SSL, SSL_R_CLIENTHELLO_PARSE_FAILED);
  722. goto f_err;
  723. }
  724. if (ssl->state == SSL3_ST_SR_CLNT_HELLO_C &&
  725. ssl->ctx->select_certificate_cb != NULL) {
  726. ssl->state = SSL3_ST_SR_CLNT_HELLO_D;
  727. switch (ssl->ctx->select_certificate_cb(&early_ctx)) {
  728. case 0:
  729. ssl->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
  730. goto err;
  731. case -1:
  732. /* Connection rejected. */
  733. al = SSL_AD_ACCESS_DENIED;
  734. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  735. goto f_err;
  736. default:
  737. /* fallthrough */;
  738. }
  739. }
  740. ssl->state = SSL3_ST_SR_CLNT_HELLO_D;
  741. break;
  742. default:
  743. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  744. return -1;
  745. }
  746. CBS_init(&client_hello, ssl->init_msg, n);
  747. if (!CBS_get_u16(&client_hello, &client_version) ||
  748. !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
  749. !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
  750. CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
  751. al = SSL_AD_DECODE_ERROR;
  752. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  753. goto f_err;
  754. }
  755. /* use version from inside client hello, not from record header (may differ:
  756. * see RFC 2246, Appendix E, second paragraph) */
  757. ssl->client_version = client_version;
  758. /* Load the client random. */
  759. memcpy(ssl->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
  760. if (SSL_IS_DTLS(ssl)) {
  761. CBS cookie;
  762. if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
  763. CBS_len(&cookie) > DTLS1_COOKIE_LENGTH) {
  764. al = SSL_AD_DECODE_ERROR;
  765. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  766. goto f_err;
  767. }
  768. }
  769. /* Note: This codepath may run twice if |ssl_get_prev_session| completes
  770. * asynchronously.
  771. *
  772. * TODO(davidben): Clean up the order of events around ClientHello
  773. * processing. */
  774. if (!ssl->s3->have_version) {
  775. /* Select version to use */
  776. uint16_t version = ssl3_get_mutual_version(ssl, client_version);
  777. if (version == 0) {
  778. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
  779. ssl->version = ssl->client_version;
  780. al = SSL_AD_PROTOCOL_VERSION;
  781. goto f_err;
  782. }
  783. ssl->version = version;
  784. ssl->enc_method = ssl3_get_enc_method(version);
  785. assert(ssl->enc_method != NULL);
  786. /* At this point, the connection's version is known and |ssl->version| is
  787. * fixed. Begin enforcing the record-layer version. */
  788. ssl->s3->have_version = 1;
  789. } else if (SSL_IS_DTLS(ssl) ? (ssl->client_version > ssl->version)
  790. : (ssl->client_version < ssl->version)) {
  791. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_NUMBER);
  792. al = SSL_AD_PROTOCOL_VERSION;
  793. goto f_err;
  794. }
  795. ssl->hit = 0;
  796. int send_new_ticket = 0;
  797. switch (ssl_get_prev_session(ssl, &session, &send_new_ticket, &early_ctx)) {
  798. case ssl_session_success:
  799. break;
  800. case ssl_session_error:
  801. goto err;
  802. case ssl_session_retry:
  803. ssl->rwstate = SSL_PENDING_SESSION;
  804. goto err;
  805. }
  806. ssl->tlsext_ticket_expected = send_new_ticket;
  807. /* The EMS state is needed when making the resumption decision, but
  808. * extensions are not normally parsed until later. This detects the EMS
  809. * extension for the resumption decision and it's checked against the result
  810. * of the normal parse later in this function. */
  811. const uint8_t *ems_data;
  812. size_t ems_len;
  813. int have_extended_master_secret =
  814. ssl->version != SSL3_VERSION &&
  815. SSL_early_callback_ctx_extension_get(&early_ctx,
  816. TLSEXT_TYPE_extended_master_secret,
  817. &ems_data, &ems_len) &&
  818. ems_len == 0;
  819. if (session != NULL) {
  820. if (session->extended_master_secret &&
  821. !have_extended_master_secret) {
  822. /* A ClientHello without EMS that attempts to resume a session with EMS
  823. * is fatal to the connection. */
  824. al = SSL_AD_HANDSHAKE_FAILURE;
  825. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
  826. goto f_err;
  827. }
  828. ssl->hit =
  829. /* Only resume if the session's version matches the negotiated version:
  830. * most clients do not accept a mismatch. */
  831. ssl->version == session->ssl_version &&
  832. /* If the client offers the EMS extension, but the previous session
  833. * didn't use it, then negotiate a new session. */
  834. have_extended_master_secret == session->extended_master_secret;
  835. }
  836. if (ssl->hit) {
  837. /* Use the new session. */
  838. SSL_SESSION_free(ssl->session);
  839. ssl->session = session;
  840. session = NULL;
  841. ssl->verify_result = ssl->session->verify_result;
  842. } else {
  843. if (!ssl_get_new_session(ssl, 1 /* server */)) {
  844. goto err;
  845. }
  846. /* Clear the session ID if we want the session to be single-use. */
  847. if (!(ssl->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)) {
  848. ssl->session->session_id_length = 0;
  849. }
  850. }
  851. if (ssl->ctx->dos_protection_cb != NULL &&
  852. ssl->ctx->dos_protection_cb(&early_ctx) == 0) {
  853. /* Connection rejected for DOS reasons. */
  854. al = SSL_AD_ACCESS_DENIED;
  855. OPENSSL_PUT_ERROR(SSL, SSL_R_CONNECTION_REJECTED);
  856. goto f_err;
  857. }
  858. if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
  859. CBS_len(&cipher_suites) == 0 ||
  860. CBS_len(&cipher_suites) % 2 != 0 ||
  861. !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
  862. CBS_len(&compression_methods) == 0) {
  863. al = SSL_AD_DECODE_ERROR;
  864. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  865. goto f_err;
  866. }
  867. ciphers = ssl_bytes_to_cipher_list(ssl, &cipher_suites);
  868. if (ciphers == NULL) {
  869. goto err;
  870. }
  871. /* If it is a hit, check that the cipher is in the list. */
  872. if (ssl->hit) {
  873. size_t j;
  874. int found_cipher = 0;
  875. uint32_t id = ssl->session->cipher->id;
  876. for (j = 0; j < sk_SSL_CIPHER_num(ciphers); j++) {
  877. c = sk_SSL_CIPHER_value(ciphers, j);
  878. if (c->id == id) {
  879. found_cipher = 1;
  880. break;
  881. }
  882. }
  883. if (!found_cipher) {
  884. /* we need to have the cipher in the cipher list if we are asked to reuse
  885. * it */
  886. al = SSL_AD_ILLEGAL_PARAMETER;
  887. OPENSSL_PUT_ERROR(SSL, SSL_R_REQUIRED_CIPHER_MISSING);
  888. goto f_err;
  889. }
  890. }
  891. /* Only null compression is supported. */
  892. if (memchr(CBS_data(&compression_methods), 0,
  893. CBS_len(&compression_methods)) == NULL) {
  894. al = SSL_AD_ILLEGAL_PARAMETER;
  895. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_COMPRESSION_SPECIFIED);
  896. goto f_err;
  897. }
  898. /* TLS extensions. */
  899. if (ssl->version >= SSL3_VERSION &&
  900. !ssl_parse_clienthello_tlsext(ssl, &client_hello)) {
  901. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  902. goto err;
  903. }
  904. /* There should be nothing left over in the record. */
  905. if (CBS_len(&client_hello) != 0) {
  906. /* wrong packet length */
  907. al = SSL_AD_DECODE_ERROR;
  908. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
  909. goto f_err;
  910. }
  911. if (have_extended_master_secret != ssl->s3->tmp.extended_master_secret) {
  912. al = SSL_AD_INTERNAL_ERROR;
  913. OPENSSL_PUT_ERROR(SSL, SSL_R_EMS_STATE_INCONSISTENT);
  914. goto f_err;
  915. }
  916. /* Given ciphers and SSL_get_ciphers, we must pick a cipher */
  917. if (!ssl->hit) {
  918. if (ciphers == NULL) {
  919. al = SSL_AD_ILLEGAL_PARAMETER;
  920. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_PASSED);
  921. goto f_err;
  922. }
  923. /* Let cert callback update server certificates if required */
  924. if (ssl->cert->cert_cb) {
  925. int rv = ssl->cert->cert_cb(ssl, ssl->cert->cert_cb_arg);
  926. if (rv == 0) {
  927. al = SSL_AD_INTERNAL_ERROR;
  928. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_CB_ERROR);
  929. goto f_err;
  930. }
  931. if (rv < 0) {
  932. ssl->rwstate = SSL_X509_LOOKUP;
  933. goto err;
  934. }
  935. ssl->rwstate = SSL_NOTHING;
  936. }
  937. c = ssl3_choose_cipher(ssl, ciphers, ssl_get_cipher_preferences(ssl));
  938. if (c == NULL) {
  939. al = SSL_AD_HANDSHAKE_FAILURE;
  940. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_SHARED_CIPHER);
  941. goto f_err;
  942. }
  943. ssl->session->cipher = c;
  944. ssl->s3->tmp.new_cipher = c;
  945. /* Determine whether to request a client certificate. */
  946. ssl->s3->tmp.cert_request = !!(ssl->verify_mode & SSL_VERIFY_PEER);
  947. /* Only request a certificate if Channel ID isn't negotiated. */
  948. if ((ssl->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
  949. ssl->s3->tlsext_channel_id_valid) {
  950. ssl->s3->tmp.cert_request = 0;
  951. }
  952. /* Plain PSK forbids Certificate and CertificateRequest. */
  953. if (ssl->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK) {
  954. ssl->s3->tmp.cert_request = 0;
  955. }
  956. } else {
  957. /* Session-id reuse */
  958. ssl->s3->tmp.new_cipher = ssl->session->cipher;
  959. ssl->s3->tmp.cert_request = 0;
  960. }
  961. /* Now that the cipher is known, initialize the handshake hash. */
  962. if (!ssl3_init_handshake_hash(ssl)) {
  963. goto f_err;
  964. }
  965. /* In TLS 1.2, client authentication requires hashing the handshake transcript
  966. * under a different hash. Otherwise, release the handshake buffer. */
  967. if (!SSL_USE_SIGALGS(ssl) || !ssl->s3->tmp.cert_request) {
  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 (SSL_USE_SIGALGS(ssl)) {
  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 (SSL_USE_SIGALGS(ssl)) {
  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 (SSL_USE_SIGALGS(ssl)) {
  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. if (!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), digest,
  1607. digest_length)) {
  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 i, 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. n = ssl->method->ssl_get_message(ssl, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B,
  1631. -1, (long)ssl->max_cert_list,
  1632. ssl_hash_message, &ok);
  1633. if (!ok) {
  1634. return n;
  1635. }
  1636. if (ssl->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
  1637. if ((ssl->verify_mode & SSL_VERIFY_PEER) &&
  1638. (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  1639. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1640. al = SSL_AD_HANDSHAKE_FAILURE;
  1641. goto f_err;
  1642. }
  1643. /* If tls asked for a client cert, the client must return a 0 list */
  1644. if (ssl->version > SSL3_VERSION && ssl->s3->tmp.cert_request) {
  1645. OPENSSL_PUT_ERROR(SSL,
  1646. SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
  1647. al = SSL_AD_UNEXPECTED_MESSAGE;
  1648. goto f_err;
  1649. }
  1650. ssl->s3->tmp.reuse_message = 1;
  1651. return 1;
  1652. }
  1653. if (ssl->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
  1654. al = SSL_AD_UNEXPECTED_MESSAGE;
  1655. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_MESSAGE_TYPE);
  1656. goto f_err;
  1657. }
  1658. CBS_init(&certificate_msg, ssl->init_msg, n);
  1659. sk = sk_X509_new_null();
  1660. if (sk == NULL) {
  1661. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1662. goto err;
  1663. }
  1664. if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
  1665. CBS_len(&certificate_msg) != 0) {
  1666. al = SSL_AD_DECODE_ERROR;
  1667. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1668. goto f_err;
  1669. }
  1670. while (CBS_len(&certificate_list) > 0) {
  1671. CBS certificate;
  1672. const uint8_t *data;
  1673. if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
  1674. al = SSL_AD_DECODE_ERROR;
  1675. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1676. goto f_err;
  1677. }
  1678. if (is_first_certificate && ssl->ctx->retain_only_sha256_of_client_certs) {
  1679. /* If this is the first certificate, and we don't want to keep peer
  1680. * certificates in memory, then we hash it right away. */
  1681. SHA256_Init(&sha256);
  1682. SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
  1683. SHA256_Final(ssl->session->peer_sha256, &sha256);
  1684. ssl->session->peer_sha256_valid = 1;
  1685. }
  1686. is_first_certificate = 0;
  1687. /* A u24 length cannot overflow a long. */
  1688. data = CBS_data(&certificate);
  1689. x = d2i_X509(NULL, &data, (long)CBS_len(&certificate));
  1690. if (x == NULL) {
  1691. al = SSL_AD_BAD_CERTIFICATE;
  1692. OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
  1693. goto f_err;
  1694. }
  1695. if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
  1696. al = SSL_AD_DECODE_ERROR;
  1697. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  1698. goto f_err;
  1699. }
  1700. if (!sk_X509_push(sk, x)) {
  1701. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1702. goto err;
  1703. }
  1704. x = NULL;
  1705. }
  1706. if (sk_X509_num(sk) <= 0) {
  1707. /* No client certificate so the handshake buffer may be discarded. */
  1708. ssl3_free_handshake_buffer(ssl);
  1709. /* TLS does not mind 0 certs returned */
  1710. if (ssl->version == SSL3_VERSION) {
  1711. al = SSL_AD_HANDSHAKE_FAILURE;
  1712. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CERTIFICATES_RETURNED);
  1713. goto f_err;
  1714. } else if ((ssl->verify_mode & SSL_VERIFY_PEER) &&
  1715. (ssl->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  1716. /* Fail for TLS only if we required a certificate */
  1717. OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  1718. al = SSL_AD_HANDSHAKE_FAILURE;
  1719. goto f_err;
  1720. }
  1721. } else {
  1722. i = ssl_verify_cert_chain(ssl, sk);
  1723. if (i <= 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. }