選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

2779 行
88 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 <assert.h>
  149. #include <stdio.h>
  150. #include <string.h>
  151. #include <openssl/bn.h>
  152. #include <openssl/buf.h>
  153. #include <openssl/bytestring.h>
  154. #include <openssl/cipher.h>
  155. #include <openssl/dh.h>
  156. #include <openssl/ec.h>
  157. #include <openssl/ecdsa.h>
  158. #include <openssl/evp.h>
  159. #include <openssl/hmac.h>
  160. #include <openssl/md5.h>
  161. #include <openssl/mem.h>
  162. #include <openssl/obj.h>
  163. #include <openssl/rand.h>
  164. #include <openssl/sha.h>
  165. #include <openssl/x509.h>
  166. #include "ssl_locl.h"
  167. #include "../crypto/internal.h"
  168. #include "../crypto/dh/internal.h"
  169. /* INITIAL_SNIFF_BUFFER_SIZE is the number of bytes read in the initial sniff
  170. * buffer. */
  171. #define INITIAL_SNIFF_BUFFER_SIZE 8
  172. int ssl3_accept(SSL *s) {
  173. BUF_MEM *buf = NULL;
  174. unsigned long alg_a;
  175. void (*cb)(const SSL *ssl, int type, int val) = NULL;
  176. int ret = -1;
  177. int new_state, state, skip = 0;
  178. assert(s->handshake_func == ssl3_accept);
  179. assert(s->server);
  180. assert(!SSL_IS_DTLS(s));
  181. ERR_clear_error();
  182. ERR_clear_system_error();
  183. if (s->info_callback != NULL) {
  184. cb = s->info_callback;
  185. } else if (s->ctx->info_callback != NULL) {
  186. cb = s->ctx->info_callback;
  187. }
  188. s->in_handshake++;
  189. if (s->cert == NULL) {
  190. OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_NO_CERTIFICATE_SET);
  191. return -1;
  192. }
  193. for (;;) {
  194. state = s->state;
  195. switch (s->state) {
  196. case SSL_ST_RENEGOTIATE:
  197. /* This state is the renegotiate entry point. It sends a HelloRequest
  198. * and nothing else. */
  199. s->renegotiate = 1;
  200. if (cb != NULL) {
  201. cb(s, SSL_CB_HANDSHAKE_START, 1);
  202. }
  203. if (s->init_buf == NULL) {
  204. buf = BUF_MEM_new();
  205. if (!buf || !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
  206. ret = -1;
  207. goto end;
  208. }
  209. s->init_buf = buf;
  210. buf = NULL;
  211. }
  212. s->init_num = 0;
  213. if (!ssl3_setup_buffers(s)) {
  214. ret = -1;
  215. goto end;
  216. }
  217. if (!s->s3->send_connection_binding &&
  218. !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
  219. /* Server attempting to renegotiate with client that doesn't support
  220. * secure renegotiation. */
  221. OPENSSL_PUT_ERROR(SSL, ssl3_accept,
  222. SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
  223. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  224. ret = -1;
  225. goto end;
  226. }
  227. s->ctx->stats.sess_accept_renegotiate++;
  228. s->state = SSL3_ST_SW_HELLO_REQ_A;
  229. break;
  230. case SSL3_ST_SW_HELLO_REQ_A:
  231. case SSL3_ST_SW_HELLO_REQ_B:
  232. s->shutdown = 0;
  233. ret = ssl3_send_hello_request(s);
  234. if (ret <= 0) {
  235. goto end;
  236. }
  237. s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
  238. s->state = SSL3_ST_SW_FLUSH;
  239. s->init_num = 0;
  240. if (!ssl3_init_finished_mac(s)) {
  241. OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
  242. ret = -1;
  243. goto end;
  244. }
  245. break;
  246. case SSL3_ST_SW_HELLO_REQ_C:
  247. s->state = SSL_ST_OK;
  248. break;
  249. case SSL_ST_ACCEPT:
  250. case SSL_ST_BEFORE | SSL_ST_ACCEPT:
  251. /* This state is the entry point for the handshake itself (initial and
  252. * renegotiation). */
  253. if (cb != NULL) {
  254. cb(s, SSL_CB_HANDSHAKE_START, 1);
  255. }
  256. if (s->init_buf == NULL) {
  257. buf = BUF_MEM_new();
  258. if (!buf || !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
  259. ret = -1;
  260. goto end;
  261. }
  262. s->init_buf = buf;
  263. buf = NULL;
  264. }
  265. s->init_num = 0;
  266. if (!ssl3_init_finished_mac(s)) {
  267. OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
  268. ret = -1;
  269. goto end;
  270. }
  271. if (!s->s3->have_version) {
  272. /* This is the initial handshake. The record layer has not been
  273. * initialized yet. Sniff for a V2ClientHello before reading a
  274. * ClientHello normally. */
  275. assert(s->s3->rbuf.buf == NULL);
  276. assert(s->s3->wbuf.buf == NULL);
  277. s->state = SSL3_ST_SR_INITIAL_BYTES;
  278. } else {
  279. /* Enable a write buffer. This groups handshake messages within a
  280. * flight into a single write. */
  281. if (!ssl3_setup_buffers(s) || !ssl_init_wbio_buffer(s, 1)) {
  282. ret = -1;
  283. goto end;
  284. }
  285. s->state = SSL3_ST_SR_CLNT_HELLO_A;
  286. }
  287. s->ctx->stats.sess_accept++;
  288. break;
  289. case SSL3_ST_SR_INITIAL_BYTES:
  290. ret = ssl3_get_initial_bytes(s);
  291. if (ret <= 0) {
  292. goto end;
  293. }
  294. /* ssl3_get_initial_bytes sets s->state to one of
  295. * SSL3_ST_SR_V2_CLIENT_HELLO or SSL3_ST_SR_CLNT_HELLO_A on success. */
  296. break;
  297. case SSL3_ST_SR_V2_CLIENT_HELLO:
  298. ret = ssl3_get_v2_client_hello(s);
  299. if (ret <= 0) {
  300. goto end;
  301. }
  302. s->state = SSL3_ST_SR_CLNT_HELLO_A;
  303. break;
  304. case SSL3_ST_SR_CLNT_HELLO_A:
  305. case SSL3_ST_SR_CLNT_HELLO_B:
  306. case SSL3_ST_SR_CLNT_HELLO_C:
  307. case SSL3_ST_SR_CLNT_HELLO_D:
  308. s->shutdown = 0;
  309. ret = ssl3_get_client_hello(s);
  310. if (ret == PENDING_SESSION) {
  311. s->rwstate = SSL_PENDING_SESSION;
  312. goto end;
  313. }
  314. if (ret == CERTIFICATE_SELECTION_PENDING) {
  315. s->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
  316. goto end;
  317. }
  318. if (ret <= 0) {
  319. goto end;
  320. }
  321. s->renegotiate = 2;
  322. s->state = SSL3_ST_SW_SRVR_HELLO_A;
  323. s->init_num = 0;
  324. break;
  325. case SSL3_ST_SW_SRVR_HELLO_A:
  326. case SSL3_ST_SW_SRVR_HELLO_B:
  327. ret = ssl3_send_server_hello(s);
  328. if (ret <= 0) {
  329. goto end;
  330. }
  331. if (s->hit) {
  332. if (s->tlsext_ticket_expected) {
  333. s->state = SSL3_ST_SW_SESSION_TICKET_A;
  334. } else {
  335. s->state = SSL3_ST_SW_CHANGE_A;
  336. }
  337. } else {
  338. s->state = SSL3_ST_SW_CERT_A;
  339. }
  340. s->init_num = 0;
  341. break;
  342. case SSL3_ST_SW_CERT_A:
  343. case SSL3_ST_SW_CERT_B:
  344. if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
  345. ret = ssl3_send_server_certificate(s);
  346. if (ret <= 0) {
  347. goto end;
  348. }
  349. if (s->s3->tmp.certificate_status_expected) {
  350. s->state = SSL3_ST_SW_CERT_STATUS_A;
  351. } else {
  352. s->state = SSL3_ST_SW_KEY_EXCH_A;
  353. }
  354. } else {
  355. skip = 1;
  356. s->state = SSL3_ST_SW_KEY_EXCH_A;
  357. }
  358. s->init_num = 0;
  359. break;
  360. case SSL3_ST_SW_KEY_EXCH_A:
  361. case SSL3_ST_SW_KEY_EXCH_B:
  362. alg_a = s->s3->tmp.new_cipher->algorithm_auth;
  363. /* Send a ServerKeyExchange message if:
  364. * - The key exchange is ephemeral or anonymous
  365. * Diffie-Hellman.
  366. * - There is a PSK identity hint.
  367. *
  368. * TODO(davidben): This logic is currently duplicated in d1_srvr.c. Fix
  369. * this. In the meantime, keep them in sync. */
  370. if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher) ||
  371. ((alg_a & SSL_aPSK) && s->psk_identity_hint)) {
  372. ret = ssl3_send_server_key_exchange(s);
  373. if (ret <= 0)
  374. goto end;
  375. } else {
  376. skip = 1;
  377. }
  378. s->state = SSL3_ST_SW_CERT_REQ_A;
  379. s->init_num = 0;
  380. break;
  381. case SSL3_ST_SW_CERT_REQ_A:
  382. case SSL3_ST_SW_CERT_REQ_B:
  383. if (/* don't request cert unless asked for it: */
  384. !(s->verify_mode & SSL_VERIFY_PEER) ||
  385. /* Don't request a certificate if an obc was presented */
  386. ((s->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
  387. s->s3->tlsext_channel_id_valid) ||
  388. /* if SSL_VERIFY_CLIENT_ONCE is set,
  389. * don't request cert during re-negotiation: */
  390. ((s->session->peer != NULL) &&
  391. (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
  392. /* never request cert in anonymous ciphersuites
  393. * (see section "Certificate request" in SSL 3 drafts
  394. * and in RFC 2246): */
  395. ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
  396. /* ... except when the application insists on verification
  397. * (against the specs, but s3_clnt.c accepts this for SSL 3) */
  398. !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
  399. /* With normal PSK Certificates and
  400. * Certificate Requests are omitted */
  401. (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
  402. /* no cert request */
  403. skip = 1;
  404. s->s3->tmp.cert_request = 0;
  405. s->state = SSL3_ST_SW_SRVR_DONE_A;
  406. if (s->s3->handshake_buffer &&
  407. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  408. return -1;
  409. }
  410. } else {
  411. s->s3->tmp.cert_request = 1;
  412. ret = ssl3_send_certificate_request(s);
  413. if (ret <= 0) {
  414. goto end;
  415. }
  416. s->state = SSL3_ST_SW_SRVR_DONE_A;
  417. s->init_num = 0;
  418. }
  419. break;
  420. case SSL3_ST_SW_SRVR_DONE_A:
  421. case SSL3_ST_SW_SRVR_DONE_B:
  422. ret = ssl3_send_server_done(s);
  423. if (ret <= 0) {
  424. goto end;
  425. }
  426. s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
  427. s->state = SSL3_ST_SW_FLUSH;
  428. s->init_num = 0;
  429. break;
  430. case SSL3_ST_SW_FLUSH:
  431. /* This code originally checked to see if any data was pending using
  432. * BIO_CTRL_INFO and then flushed. This caused problems as documented
  433. * in PR#1939. The proposed fix doesn't completely resolve this issue
  434. * as buggy implementations of BIO_CTRL_PENDING still exist. So instead
  435. * we just flush unconditionally. */
  436. s->rwstate = SSL_WRITING;
  437. if (BIO_flush(s->wbio) <= 0) {
  438. ret = -1;
  439. goto end;
  440. }
  441. s->rwstate = SSL_NOTHING;
  442. s->state = s->s3->tmp.next_state;
  443. break;
  444. case SSL3_ST_SR_CERT_A:
  445. case SSL3_ST_SR_CERT_B:
  446. if (s->s3->tmp.cert_request) {
  447. ret = ssl3_get_client_certificate(s);
  448. if (ret <= 0) {
  449. goto end;
  450. }
  451. }
  452. s->init_num = 0;
  453. s->state = SSL3_ST_SR_KEY_EXCH_A;
  454. break;
  455. case SSL3_ST_SR_KEY_EXCH_A:
  456. case SSL3_ST_SR_KEY_EXCH_B:
  457. ret = ssl3_get_client_key_exchange(s);
  458. if (ret <= 0) {
  459. goto end;
  460. }
  461. s->state = SSL3_ST_SR_CERT_VRFY_A;
  462. s->init_num = 0;
  463. break;
  464. case SSL3_ST_SR_CERT_VRFY_A:
  465. case SSL3_ST_SR_CERT_VRFY_B:
  466. ret = ssl3_get_cert_verify(s);
  467. if (ret <= 0) {
  468. goto end;
  469. }
  470. s->state = SSL3_ST_SR_CHANGE;
  471. s->init_num = 0;
  472. break;
  473. case SSL3_ST_SR_CHANGE: {
  474. char next_proto_neg = 0;
  475. char channel_id = 0;
  476. next_proto_neg = s->s3->next_proto_neg_seen;
  477. channel_id = s->s3->tlsext_channel_id_valid;
  478. /* At this point, the next message must be entirely behind a
  479. * ChangeCipherSpec. */
  480. if (!ssl3_expect_change_cipher_spec(s)) {
  481. ret = -1;
  482. goto end;
  483. }
  484. if (next_proto_neg) {
  485. s->state = SSL3_ST_SR_NEXT_PROTO_A;
  486. } else if (channel_id) {
  487. s->state = SSL3_ST_SR_CHANNEL_ID_A;
  488. } else {
  489. s->state = SSL3_ST_SR_FINISHED_A;
  490. }
  491. break;
  492. }
  493. case SSL3_ST_SR_NEXT_PROTO_A:
  494. case SSL3_ST_SR_NEXT_PROTO_B:
  495. ret = ssl3_get_next_proto(s);
  496. if (ret <= 0) {
  497. goto end;
  498. }
  499. s->init_num = 0;
  500. if (s->s3->tlsext_channel_id_valid) {
  501. s->state = SSL3_ST_SR_CHANNEL_ID_A;
  502. } else {
  503. s->state = SSL3_ST_SR_FINISHED_A;
  504. }
  505. break;
  506. case SSL3_ST_SR_CHANNEL_ID_A:
  507. case SSL3_ST_SR_CHANNEL_ID_B:
  508. ret = ssl3_get_channel_id(s);
  509. if (ret <= 0) {
  510. goto end;
  511. }
  512. s->init_num = 0;
  513. s->state = SSL3_ST_SR_FINISHED_A;
  514. break;
  515. case SSL3_ST_SR_FINISHED_A:
  516. case SSL3_ST_SR_FINISHED_B:
  517. ret =
  518. ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A, SSL3_ST_SR_FINISHED_B);
  519. if (ret <= 0) {
  520. goto end;
  521. }
  522. if (s->hit) {
  523. s->state = SSL_ST_OK;
  524. } else if (s->tlsext_ticket_expected) {
  525. s->state = SSL3_ST_SW_SESSION_TICKET_A;
  526. } else {
  527. s->state = SSL3_ST_SW_CHANGE_A;
  528. }
  529. /* If this is a full handshake with ChannelID then record the hashshake
  530. * hashes in |s->session| in case we need them to verify a ChannelID
  531. * signature on a resumption of this session in the future. */
  532. if (!s->hit && s->s3->tlsext_channel_id_new) {
  533. ret = tls1_record_handshake_hashes_for_channel_id(s);
  534. if (ret <= 0) {
  535. goto end;
  536. }
  537. }
  538. s->init_num = 0;
  539. break;
  540. case SSL3_ST_SW_SESSION_TICKET_A:
  541. case SSL3_ST_SW_SESSION_TICKET_B:
  542. ret = ssl3_send_new_session_ticket(s);
  543. if (ret <= 0) {
  544. goto end;
  545. }
  546. s->state = SSL3_ST_SW_CHANGE_A;
  547. s->init_num = 0;
  548. break;
  549. case SSL3_ST_SW_CHANGE_A:
  550. case SSL3_ST_SW_CHANGE_B:
  551. s->session->cipher = s->s3->tmp.new_cipher;
  552. if (!s->enc_method->setup_key_block(s)) {
  553. ret = -1;
  554. goto end;
  555. }
  556. ret = ssl3_send_change_cipher_spec(s, SSL3_ST_SW_CHANGE_A,
  557. SSL3_ST_SW_CHANGE_B);
  558. if (ret <= 0) {
  559. goto end;
  560. }
  561. s->state = SSL3_ST_SW_FINISHED_A;
  562. s->init_num = 0;
  563. if (!s->enc_method->change_cipher_state(
  564. s, SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
  565. ret = -1;
  566. goto end;
  567. }
  568. break;
  569. case SSL3_ST_SW_FINISHED_A:
  570. case SSL3_ST_SW_FINISHED_B:
  571. ret =
  572. ssl3_send_finished(s, SSL3_ST_SW_FINISHED_A, SSL3_ST_SW_FINISHED_B,
  573. s->enc_method->server_finished_label,
  574. s->enc_method->server_finished_label_len);
  575. if (ret <= 0) {
  576. goto end;
  577. }
  578. s->state = SSL3_ST_SW_FLUSH;
  579. if (s->hit) {
  580. s->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
  581. } else {
  582. s->s3->tmp.next_state = SSL_ST_OK;
  583. }
  584. s->init_num = 0;
  585. break;
  586. case SSL_ST_OK:
  587. /* clean a few things up */
  588. ssl3_cleanup_key_block(s);
  589. BUF_MEM_free(s->init_buf);
  590. s->init_buf = NULL;
  591. /* remove buffering on output */
  592. ssl_free_wbio_buffer(s);
  593. s->init_num = 0;
  594. /* If we aren't retaining peer certificates then we can discard it
  595. * now. */
  596. if (s->session->peer && s->ctx->retain_only_sha256_of_client_certs) {
  597. X509_free(s->session->peer);
  598. s->session->peer = NULL;
  599. }
  600. if (s->renegotiate == 2) {
  601. /* skipped if we just sent a HelloRequest */
  602. s->renegotiate = 0;
  603. s->new_session = 0;
  604. ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
  605. s->ctx->stats.sess_accept_good++;
  606. if (cb != NULL) {
  607. cb(s, SSL_CB_HANDSHAKE_DONE, 1);
  608. }
  609. }
  610. ret = 1;
  611. goto end;
  612. default:
  613. OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNKNOWN_STATE);
  614. ret = -1;
  615. goto end;
  616. }
  617. if (!s->s3->tmp.reuse_message && !skip && cb != NULL && s->state != state) {
  618. new_state = s->state;
  619. s->state = state;
  620. cb(s, SSL_CB_ACCEPT_LOOP, 1);
  621. s->state = new_state;
  622. }
  623. skip = 0;
  624. }
  625. end:
  626. s->in_handshake--;
  627. if (buf != NULL) {
  628. BUF_MEM_free(buf);
  629. }
  630. if (cb != NULL) {
  631. cb(s, SSL_CB_ACCEPT_EXIT, ret);
  632. }
  633. return ret;
  634. }
  635. static int ssl3_read_sniff_buffer(SSL *s, size_t n) {
  636. if (s->s3->sniff_buffer == NULL) {
  637. s->s3->sniff_buffer = BUF_MEM_new();
  638. }
  639. if (s->s3->sniff_buffer == NULL || !BUF_MEM_grow(s->s3->sniff_buffer, n)) {
  640. return -1;
  641. }
  642. while (s->s3->sniff_buffer_len < n) {
  643. int ret;
  644. s->rwstate = SSL_READING;
  645. ret = BIO_read(s->rbio, s->s3->sniff_buffer->data + s->s3->sniff_buffer_len,
  646. n - s->s3->sniff_buffer_len);
  647. if (ret <= 0) {
  648. return ret;
  649. }
  650. s->rwstate = SSL_NOTHING;
  651. s->s3->sniff_buffer_len += ret;
  652. }
  653. return 1;
  654. }
  655. int ssl3_get_initial_bytes(SSL *s) {
  656. int ret;
  657. const uint8_t *p;
  658. /* Read the first 8 bytes. To recognize a ClientHello or V2ClientHello only
  659. * needs the first 6 bytes, but 8 is needed to recognize CONNECT below. */
  660. ret = ssl3_read_sniff_buffer(s, INITIAL_SNIFF_BUFFER_SIZE);
  661. if (ret <= 0) {
  662. return ret;
  663. }
  664. assert(s->s3->sniff_buffer_len >= INITIAL_SNIFF_BUFFER_SIZE);
  665. p = (const uint8_t *)s->s3->sniff_buffer->data;
  666. /* Some dedicated error codes for protocol mixups should the application wish
  667. * to interpret them differently. (These do not overlap with ClientHello or
  668. * V2ClientHello.) */
  669. if (strncmp("GET ", (const char *)p, 4) == 0 ||
  670. strncmp("POST ", (const char *)p, 5) == 0 ||
  671. strncmp("HEAD ", (const char *)p, 5) == 0 ||
  672. strncmp("PUT ", (const char *)p, 4) == 0) {
  673. OPENSSL_PUT_ERROR(SSL, ssl3_get_initial_bytes, SSL_R_HTTP_REQUEST);
  674. return -1;
  675. }
  676. if (strncmp("CONNECT ", (const char *)p, 8) == 0) {
  677. OPENSSL_PUT_ERROR(SSL, ssl3_get_initial_bytes, SSL_R_HTTPS_PROXY_REQUEST);
  678. return -1;
  679. }
  680. /* Determine if this is a ClientHello or V2ClientHello. */
  681. if ((p[0] & 0x80) && p[2] == SSL2_MT_CLIENT_HELLO &&
  682. p[3] >= SSL3_VERSION_MAJOR) {
  683. /* This is a V2ClientHello. */
  684. s->state = SSL3_ST_SR_V2_CLIENT_HELLO;
  685. return 1;
  686. }
  687. if (p[0] == SSL3_RT_HANDSHAKE && p[1] >= SSL3_VERSION_MAJOR &&
  688. p[5] == SSL3_MT_CLIENT_HELLO) {
  689. /* This is a ClientHello. Initialize the record layer with the already
  690. * consumed data and continue the handshake. */
  691. if (!ssl3_setup_buffers(s) || !ssl_init_wbio_buffer(s, 1)) {
  692. return -1;
  693. }
  694. assert(s->rstate == SSL_ST_READ_HEADER);
  695. memcpy(s->s3->rbuf.buf, p, s->s3->sniff_buffer_len);
  696. s->s3->rbuf.offset = 0;
  697. s->s3->rbuf.left = s->s3->sniff_buffer_len;
  698. s->packet_length = 0;
  699. BUF_MEM_free(s->s3->sniff_buffer);
  700. s->s3->sniff_buffer = NULL;
  701. s->s3->sniff_buffer_len = 0;
  702. s->state = SSL3_ST_SR_CLNT_HELLO_A;
  703. return 1;
  704. }
  705. OPENSSL_PUT_ERROR(SSL, ssl3_get_initial_bytes, SSL_R_UNKNOWN_PROTOCOL);
  706. return -1;
  707. }
  708. int ssl3_get_v2_client_hello(SSL *s) {
  709. const uint8_t *p;
  710. int ret;
  711. CBS v2_client_hello, cipher_specs, session_id, challenge;
  712. size_t msg_length, rand_len, len;
  713. uint8_t msg_type;
  714. uint16_t version, cipher_spec_length, session_id_length, challenge_length;
  715. CBB client_hello, hello_body, cipher_suites;
  716. uint8_t random[SSL3_RANDOM_SIZE];
  717. /* Read the remainder of the V2ClientHello. We have previously read 8 bytes
  718. * in ssl3_get_initial_bytes. */
  719. assert(s->s3->sniff_buffer_len >= INITIAL_SNIFF_BUFFER_SIZE);
  720. p = (const uint8_t *)s->s3->sniff_buffer->data;
  721. msg_length = ((p[0] & 0x7f) << 8) | p[1];
  722. if (msg_length > (1024 * 4)) {
  723. OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, SSL_R_RECORD_TOO_LARGE);
  724. return -1;
  725. }
  726. if (msg_length < INITIAL_SNIFF_BUFFER_SIZE - 2) {
  727. /* Reject lengths that are too short early. We have already read 8 bytes,
  728. * so we should not attempt to process an (invalid) V2ClientHello which
  729. * would be shorter than that. */
  730. OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello,
  731. SSL_R_RECORD_LENGTH_MISMATCH);
  732. return -1;
  733. }
  734. ret = ssl3_read_sniff_buffer(s, msg_length + 2);
  735. if (ret <= 0) {
  736. return ret;
  737. }
  738. assert(s->s3->sniff_buffer_len == msg_length + 2);
  739. CBS_init(&v2_client_hello, (const uint8_t *)s->s3->sniff_buffer->data + 2,
  740. msg_length);
  741. /* The V2ClientHello without the length is incorporated into the Finished
  742. * hash. */
  743. ssl3_finish_mac(s, CBS_data(&v2_client_hello), CBS_len(&v2_client_hello));
  744. if (s->msg_callback) {
  745. s->msg_callback(0, SSL2_VERSION, 0, CBS_data(&v2_client_hello),
  746. CBS_len(&v2_client_hello), s, s->msg_callback_arg);
  747. }
  748. if (!CBS_get_u8(&v2_client_hello, &msg_type) ||
  749. !CBS_get_u16(&v2_client_hello, &version) ||
  750. !CBS_get_u16(&v2_client_hello, &cipher_spec_length) ||
  751. !CBS_get_u16(&v2_client_hello, &session_id_length) ||
  752. !CBS_get_u16(&v2_client_hello, &challenge_length) ||
  753. !CBS_get_bytes(&v2_client_hello, &cipher_specs, cipher_spec_length) ||
  754. !CBS_get_bytes(&v2_client_hello, &session_id, session_id_length) ||
  755. !CBS_get_bytes(&v2_client_hello, &challenge, challenge_length) ||
  756. CBS_len(&v2_client_hello) != 0) {
  757. OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, SSL_R_DECODE_ERROR);
  758. return -1;
  759. }
  760. /* msg_type has already been checked. */
  761. assert(msg_type == SSL2_MT_CLIENT_HELLO);
  762. /* The client_random is the V2ClientHello challenge. Truncate or
  763. * left-pad with zeros as needed. */
  764. memset(random, 0, SSL3_RANDOM_SIZE);
  765. rand_len = CBS_len(&challenge);
  766. if (rand_len > SSL3_RANDOM_SIZE) {
  767. rand_len = SSL3_RANDOM_SIZE;
  768. }
  769. memcpy(random + (SSL3_RANDOM_SIZE - rand_len), CBS_data(&challenge),
  770. rand_len);
  771. /* Write out an equivalent SSLv3 ClientHello. */
  772. if (!CBB_init_fixed(&client_hello, (uint8_t *)s->init_buf->data,
  773. s->init_buf->max)) {
  774. OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, ERR_R_MALLOC_FAILURE);
  775. return -1;
  776. }
  777. if (!CBB_add_u8(&client_hello, SSL3_MT_CLIENT_HELLO) ||
  778. !CBB_add_u24_length_prefixed(&client_hello, &hello_body) ||
  779. !CBB_add_u16(&hello_body, version) ||
  780. !CBB_add_bytes(&hello_body, random, SSL3_RANDOM_SIZE) ||
  781. /* No session id. */
  782. !CBB_add_u8(&hello_body, 0) ||
  783. !CBB_add_u16_length_prefixed(&hello_body, &cipher_suites)) {
  784. CBB_cleanup(&client_hello);
  785. OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, ERR_R_INTERNAL_ERROR);
  786. return -1;
  787. }
  788. /* Copy the cipher suites. */
  789. while (CBS_len(&cipher_specs) > 0) {
  790. uint32_t cipher_spec;
  791. if (!CBS_get_u24(&cipher_specs, &cipher_spec)) {
  792. CBB_cleanup(&client_hello);
  793. OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, SSL_R_DECODE_ERROR);
  794. return -1;
  795. }
  796. /* Skip SSLv2 ciphers. */
  797. if ((cipher_spec & 0xff0000) != 0) {
  798. continue;
  799. }
  800. if (!CBB_add_u16(&cipher_suites, cipher_spec)) {
  801. CBB_cleanup(&client_hello);
  802. OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, ERR_R_INTERNAL_ERROR);
  803. return -1;
  804. }
  805. }
  806. /* Add the null compression scheme and finish. */
  807. if (!CBB_add_u8(&hello_body, 1) || !CBB_add_u8(&hello_body, 0) ||
  808. !CBB_finish(&client_hello, NULL, &len)) {
  809. CBB_cleanup(&client_hello);
  810. OPENSSL_PUT_ERROR(SSL, ssl3_get_v2_client_hello, ERR_R_INTERNAL_ERROR);
  811. return -1;
  812. }
  813. /* Mark the message for "re"-use by the version-specific method. */
  814. s->s3->tmp.reuse_message = 1;
  815. s->s3->tmp.message_type = SSL3_MT_CLIENT_HELLO;
  816. /* The handshake message header is 4 bytes. */
  817. s->s3->tmp.message_size = len - 4;
  818. /* Initialize the record layer. */
  819. if (!ssl3_setup_buffers(s) || !ssl_init_wbio_buffer(s, 1)) {
  820. return -1;
  821. }
  822. /* Drop the sniff buffer. */
  823. BUF_MEM_free(s->s3->sniff_buffer);
  824. s->s3->sniff_buffer = NULL;
  825. s->s3->sniff_buffer_len = 0;
  826. return 1;
  827. }
  828. int ssl3_send_hello_request(SSL *s) {
  829. if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
  830. ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
  831. s->state = SSL3_ST_SW_HELLO_REQ_B;
  832. }
  833. /* SSL3_ST_SW_HELLO_REQ_B */
  834. return ssl_do_write(s);
  835. }
  836. int ssl3_get_client_hello(SSL *s) {
  837. int i, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
  838. long n;
  839. const SSL_CIPHER *c;
  840. STACK_OF(SSL_CIPHER) *ciphers = NULL;
  841. struct ssl_early_callback_ctx early_ctx;
  842. CBS client_hello;
  843. uint16_t client_version;
  844. CBS client_random, session_id, cipher_suites, compression_methods;
  845. /* We do this so that we will respond with our native type. If we are TLSv1
  846. * and we get SSLv3, we will respond with TLSv1, This down switching should
  847. * be handled by a different method. If we are SSLv3, we will respond with
  848. * SSLv3, even if prompted with TLSv1. */
  849. switch (s->state) {
  850. case SSL3_ST_SR_CLNT_HELLO_A:
  851. case SSL3_ST_SR_CLNT_HELLO_B:
  852. n = s->method->ssl_get_message(
  853. s, SSL3_ST_SR_CLNT_HELLO_A, SSL3_ST_SR_CLNT_HELLO_B,
  854. SSL3_MT_CLIENT_HELLO, SSL3_RT_MAX_PLAIN_LENGTH,
  855. SSL_GET_MESSAGE_HASH_MESSAGE, &ok);
  856. if (!ok) {
  857. return n;
  858. }
  859. /* If we require cookies and this ClientHello doesn't contain one, just
  860. * return since we do not want to allocate any memory yet. So check
  861. * cookie length... */
  862. if (SSL_IS_DTLS(s) && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)) {
  863. uint8_t cookie_length;
  864. CBS_init(&client_hello, s->init_msg, n);
  865. if (!CBS_skip(&client_hello, 2 + SSL3_RANDOM_SIZE) ||
  866. !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
  867. !CBS_get_u8(&client_hello, &cookie_length)) {
  868. al = SSL_AD_DECODE_ERROR;
  869. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
  870. goto f_err;
  871. }
  872. if (cookie_length == 0) {
  873. return 1;
  874. }
  875. }
  876. s->state = SSL3_ST_SR_CLNT_HELLO_C;
  877. /* fallthrough */
  878. case SSL3_ST_SR_CLNT_HELLO_C:
  879. case SSL3_ST_SR_CLNT_HELLO_D:
  880. /* We have previously parsed the ClientHello message, and can't call
  881. * ssl_get_message again without hashing the message into the Finished
  882. * digest again. */
  883. n = s->init_num;
  884. memset(&early_ctx, 0, sizeof(early_ctx));
  885. early_ctx.ssl = s;
  886. early_ctx.client_hello = s->init_msg;
  887. early_ctx.client_hello_len = n;
  888. if (!ssl_early_callback_init(&early_ctx)) {
  889. al = SSL_AD_DECODE_ERROR;
  890. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
  891. SSL_R_CLIENTHELLO_PARSE_FAILED);
  892. goto f_err;
  893. }
  894. if (s->state == SSL3_ST_SR_CLNT_HELLO_C &&
  895. s->ctx->select_certificate_cb != NULL) {
  896. s->state = SSL3_ST_SR_CLNT_HELLO_D;
  897. switch (s->ctx->select_certificate_cb(&early_ctx)) {
  898. case 0:
  899. return CERTIFICATE_SELECTION_PENDING;
  900. case -1:
  901. /* Connection rejected. */
  902. al = SSL_AD_ACCESS_DENIED;
  903. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
  904. SSL_R_CONNECTION_REJECTED);
  905. goto f_err;
  906. default:
  907. /* fallthrough */;
  908. }
  909. }
  910. s->state = SSL3_ST_SR_CLNT_HELLO_D;
  911. break;
  912. default:
  913. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNKNOWN_STATE);
  914. return -1;
  915. }
  916. CBS_init(&client_hello, s->init_msg, n);
  917. if (!CBS_get_u16(&client_hello, &client_version) ||
  918. !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
  919. !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
  920. CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH) {
  921. al = SSL_AD_DECODE_ERROR;
  922. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
  923. goto f_err;
  924. }
  925. /* use version from inside client hello, not from record header (may differ:
  926. * see RFC 2246, Appendix E, second paragraph) */
  927. s->client_version = client_version;
  928. /* Load the client random. */
  929. memcpy(s->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
  930. if (SSL_IS_DTLS(s)) {
  931. CBS cookie;
  932. if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
  933. CBS_len(&cookie) > DTLS1_COOKIE_LENGTH) {
  934. al = SSL_AD_DECODE_ERROR;
  935. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
  936. goto f_err;
  937. }
  938. /* Verify the cookie if appropriate option is set. */
  939. if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) && CBS_len(&cookie) > 0) {
  940. if (s->ctx->app_verify_cookie_cb != NULL) {
  941. if (s->ctx->app_verify_cookie_cb(s, CBS_data(&cookie),
  942. CBS_len(&cookie)) == 0) {
  943. al = SSL_AD_HANDSHAKE_FAILURE;
  944. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
  945. goto f_err;
  946. }
  947. /* else cookie verification succeeded */
  948. } else if (!CBS_mem_equal(&cookie, s->d1->cookie, s->d1->cookie_len)) {
  949. /* default verification */
  950. al = SSL_AD_HANDSHAKE_FAILURE;
  951. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
  952. goto f_err;
  953. }
  954. /* Set to -2 so if successful we return 2 and don't send
  955. * HelloVerifyRequest. */
  956. ret = -2;
  957. }
  958. }
  959. if (!s->s3->have_version) {
  960. /* Select version to use */
  961. uint16_t version = ssl3_get_mutual_version(s, client_version);
  962. if (version == 0) {
  963. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNSUPPORTED_PROTOCOL);
  964. s->version = s->client_version;
  965. al = SSL_AD_PROTOCOL_VERSION;
  966. goto f_err;
  967. }
  968. s->version = version;
  969. s->enc_method = ssl3_get_enc_method(version);
  970. assert(s->enc_method != NULL);
  971. /* At this point, the connection's version is known and |s->version| is
  972. * fixed. Begin enforcing the record-layer version. */
  973. s->s3->have_version = 1;
  974. } else if (SSL_IS_DTLS(s) ? (s->client_version > s->version)
  975. : (s->client_version < s->version)) {
  976. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
  977. al = SSL_AD_PROTOCOL_VERSION;
  978. goto f_err;
  979. }
  980. s->hit = 0;
  981. /* Versions before 0.9.7 always allow clients to resume sessions in
  982. * renegotiation. 0.9.7 and later allow this by default, but optionally
  983. * ignore resumption requests with flag
  984. * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather than
  985. * a change to default behavior so that applications relying on this for
  986. * security won't even compile against older library versions).
  987. *
  988. * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
  989. * request renegotiation but not a new session (s->new_session remains
  990. * unset): for servers, this essentially just means that the
  991. * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be ignored. */
  992. if (s->new_session &&
  993. (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)) {
  994. if (!ssl_get_new_session(s, 1)) {
  995. goto err;
  996. }
  997. } else {
  998. i = ssl_get_prev_session(s, &early_ctx);
  999. if (i == PENDING_SESSION) {
  1000. ret = PENDING_SESSION;
  1001. goto err;
  1002. } else if (i == -1) {
  1003. goto err;
  1004. }
  1005. /* Only resume if the session's version matches the negotiated version:
  1006. * most clients do not accept a mismatch. */
  1007. if (i == 1 && s->version == s->session->ssl_version) {
  1008. s->hit = 1;
  1009. } else {
  1010. /* No session was found or it was unacceptable. */
  1011. if (!ssl_get_new_session(s, 1)) {
  1012. goto err;
  1013. }
  1014. }
  1015. }
  1016. if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
  1017. !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
  1018. CBS_len(&compression_methods) == 0) {
  1019. al = SSL_AD_DECODE_ERROR;
  1020. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
  1021. goto f_err;
  1022. }
  1023. /* TODO(davidben): Per spec, cipher_suites can never be empty (specified at
  1024. * the ClientHello structure level). This logic allows it to be empty if
  1025. * resuming a session. Can we always require non-empty? If a client sends
  1026. * empty cipher_suites because it's resuming a session, it could always fail
  1027. * to resume a session, so it's unlikely to actually work. */
  1028. if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0) {
  1029. /* We need a cipher if we are not resuming a session. */
  1030. al = SSL_AD_ILLEGAL_PARAMETER;
  1031. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_SPECIFIED);
  1032. goto f_err;
  1033. }
  1034. ciphers = ssl_bytes_to_cipher_list(s, &cipher_suites);
  1035. if (ciphers == NULL) {
  1036. goto err;
  1037. }
  1038. /* If it is a hit, check that the cipher is in the list. */
  1039. if (s->hit && CBS_len(&cipher_suites) > 0) {
  1040. size_t j;
  1041. int found_cipher = 0;
  1042. unsigned long id = s->session->cipher->id;
  1043. for (j = 0; j < sk_SSL_CIPHER_num(ciphers); j++) {
  1044. c = sk_SSL_CIPHER_value(ciphers, j);
  1045. if (c->id == id) {
  1046. found_cipher = 1;
  1047. break;
  1048. }
  1049. }
  1050. if (!found_cipher) {
  1051. /* we need to have the cipher in the cipher list if we are asked to reuse
  1052. * it */
  1053. al = SSL_AD_ILLEGAL_PARAMETER;
  1054. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
  1055. SSL_R_REQUIRED_CIPHER_MISSING);
  1056. goto f_err;
  1057. }
  1058. }
  1059. /* Only null compression is supported. */
  1060. if (memchr(CBS_data(&compression_methods), 0,
  1061. CBS_len(&compression_methods)) == NULL) {
  1062. al = SSL_AD_ILLEGAL_PARAMETER;
  1063. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello,
  1064. SSL_R_NO_COMPRESSION_SPECIFIED);
  1065. goto f_err;
  1066. }
  1067. /* TLS extensions. */
  1068. if (s->version >= SSL3_VERSION &&
  1069. !ssl_parse_clienthello_tlsext(s, &client_hello)) {
  1070. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_PARSE_TLSEXT);
  1071. goto err;
  1072. }
  1073. /* There should be nothing left over in the record. */
  1074. if (CBS_len(&client_hello) != 0) {
  1075. /* wrong packet length */
  1076. al = SSL_AD_DECODE_ERROR;
  1077. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_BAD_PACKET_LENGTH);
  1078. goto f_err;
  1079. }
  1080. /* Given ciphers and SSL_get_ciphers, we must pick a cipher */
  1081. if (!s->hit) {
  1082. if (ciphers == NULL) {
  1083. al = SSL_AD_ILLEGAL_PARAMETER;
  1084. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_PASSED);
  1085. goto f_err;
  1086. }
  1087. /* Let cert callback update server certificates if required */
  1088. if (s->cert->cert_cb) {
  1089. int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
  1090. if (rv == 0) {
  1091. al = SSL_AD_INTERNAL_ERROR;
  1092. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CERT_CB_ERROR);
  1093. goto f_err;
  1094. }
  1095. if (rv < 0) {
  1096. s->rwstate = SSL_X509_LOOKUP;
  1097. goto err;
  1098. }
  1099. s->rwstate = SSL_NOTHING;
  1100. }
  1101. c = ssl3_choose_cipher(s, ciphers, ssl_get_cipher_preferences(s));
  1102. if (c == NULL) {
  1103. al = SSL_AD_HANDSHAKE_FAILURE;
  1104. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
  1105. goto f_err;
  1106. }
  1107. s->s3->tmp.new_cipher = c;
  1108. } else {
  1109. /* Session-id reuse */
  1110. s->s3->tmp.new_cipher = s->session->cipher;
  1111. }
  1112. if ((!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) &&
  1113. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  1114. goto f_err;
  1115. }
  1116. /* we now have the following setup;
  1117. * client_random
  1118. * cipher_list - our prefered list of ciphers
  1119. * ciphers - the clients prefered list of ciphers
  1120. * compression - basically ignored right now
  1121. * ssl version is set - sslv3
  1122. * s->session - The ssl session has been setup.
  1123. * s->hit - session reuse flag
  1124. * s->tmp.new_cipher - the new cipher to use. */
  1125. if (ret < 0) {
  1126. ret = -ret;
  1127. }
  1128. if (0) {
  1129. f_err:
  1130. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1131. }
  1132. err:
  1133. if (ciphers != NULL) {
  1134. sk_SSL_CIPHER_free(ciphers);
  1135. }
  1136. return ret;
  1137. }
  1138. int ssl3_send_server_hello(SSL *s) {
  1139. uint8_t *buf;
  1140. uint8_t *p, *d;
  1141. int sl;
  1142. unsigned long l;
  1143. if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
  1144. /* We only accept ChannelIDs on connections with ECDHE in order to avoid a
  1145. * known attack while we fix ChannelID itself. */
  1146. if (s->s3->tlsext_channel_id_valid &&
  1147. (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kEECDH) == 0) {
  1148. s->s3->tlsext_channel_id_valid = 0;
  1149. }
  1150. /* If this is a resumption and the original handshake didn't support
  1151. * ChannelID then we didn't record the original handshake hashes in the
  1152. * session and so cannot resume with ChannelIDs. */
  1153. if (s->hit && s->s3->tlsext_channel_id_new &&
  1154. s->session->original_handshake_hash_len == 0) {
  1155. s->s3->tlsext_channel_id_valid = 0;
  1156. }
  1157. buf = (uint8_t *)s->init_buf->data;
  1158. /* Do the message type and length last */
  1159. d = p = ssl_handshake_start(s);
  1160. *(p++) = s->version >> 8;
  1161. *(p++) = s->version & 0xff;
  1162. /* Random stuff */
  1163. if (!ssl_fill_hello_random(s, 1, s->s3->server_random, SSL3_RANDOM_SIZE)) {
  1164. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
  1165. return -1;
  1166. }
  1167. memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
  1168. p += SSL3_RANDOM_SIZE;
  1169. /* There are several cases for the session ID to send
  1170. * back in the server hello:
  1171. * - For session reuse from the session cache, we send back the old session
  1172. * ID.
  1173. * - If stateless session reuse (using a session ticket) is successful, we
  1174. * send back the client's "session ID" (which doesn't actually identify
  1175. * the session).
  1176. * - If it is a new session, we send back the new session ID.
  1177. * - However, if we want the new session to be single-use, we send back a
  1178. * 0-length session ID.
  1179. * s->hit is non-zero in either case of session reuse, so the following
  1180. * won't overwrite an ID that we're supposed to send back. */
  1181. if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER) && !s->hit) {
  1182. s->session->session_id_length = 0;
  1183. }
  1184. sl = s->session->session_id_length;
  1185. if (sl > (int)sizeof(s->session->session_id)) {
  1186. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
  1187. return -1;
  1188. }
  1189. *(p++) = sl;
  1190. memcpy(p, s->session->session_id, sl);
  1191. p += sl;
  1192. /* put the cipher */
  1193. s2n(ssl3_get_cipher_value(s->s3->tmp.new_cipher), p);
  1194. /* put the compression method */
  1195. *(p++) = 0;
  1196. if (ssl_prepare_serverhello_tlsext(s) <= 0) {
  1197. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, SSL_R_SERVERHELLO_TLSEXT);
  1198. return -1;
  1199. }
  1200. p = ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH);
  1201. if (p == NULL) {
  1202. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
  1203. return -1;
  1204. }
  1205. /* do the header */
  1206. l = (p - d);
  1207. ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
  1208. s->state = SSL3_ST_SW_SRVR_HELLO_B;
  1209. }
  1210. /* SSL3_ST_SW_SRVR_HELLO_B */
  1211. return ssl_do_write(s);
  1212. }
  1213. int ssl3_send_server_done(SSL *s) {
  1214. if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
  1215. ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
  1216. s->state = SSL3_ST_SW_SRVR_DONE_B;
  1217. }
  1218. /* SSL3_ST_SW_SRVR_DONE_B */
  1219. return ssl_do_write(s);
  1220. }
  1221. int ssl3_send_server_key_exchange(SSL *s) {
  1222. DH *dh = NULL, *dhp;
  1223. EC_KEY *ecdh = NULL, *ecdhp;
  1224. uint8_t *encodedPoint = NULL;
  1225. int encodedlen = 0;
  1226. uint16_t curve_id = 0;
  1227. BN_CTX *bn_ctx = NULL;
  1228. const char *psk_identity_hint = NULL;
  1229. size_t psk_identity_hint_len = 0;
  1230. EVP_PKEY *pkey;
  1231. uint8_t *p, *d;
  1232. int al, i;
  1233. unsigned long alg_k;
  1234. unsigned long alg_a;
  1235. int n;
  1236. CERT *cert;
  1237. BIGNUM *r[4];
  1238. int nr[4], kn;
  1239. BUF_MEM *buf;
  1240. EVP_MD_CTX md_ctx;
  1241. EVP_MD_CTX_init(&md_ctx);
  1242. if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
  1243. alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
  1244. alg_a = s->s3->tmp.new_cipher->algorithm_auth;
  1245. cert = s->cert;
  1246. buf = s->init_buf;
  1247. r[0] = r[1] = r[2] = r[3] = NULL;
  1248. n = 0;
  1249. if (alg_a & SSL_aPSK) {
  1250. /* size for PSK identity hint */
  1251. psk_identity_hint = s->psk_identity_hint;
  1252. if (psk_identity_hint) {
  1253. psk_identity_hint_len = strlen(psk_identity_hint);
  1254. } else {
  1255. psk_identity_hint_len = 0;
  1256. }
  1257. n += 2 + psk_identity_hint_len;
  1258. }
  1259. if (alg_k & SSL_kEDH) {
  1260. dhp = cert->dh_tmp;
  1261. if (dhp == NULL && s->cert->dh_tmp_cb != NULL) {
  1262. dhp = s->cert->dh_tmp_cb(s, 0, 1024);
  1263. }
  1264. if (dhp == NULL) {
  1265. al = SSL_AD_HANDSHAKE_FAILURE;
  1266. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
  1267. SSL_R_MISSING_TMP_DH_KEY);
  1268. goto f_err;
  1269. }
  1270. if (s->s3->tmp.dh != NULL) {
  1271. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
  1272. ERR_R_INTERNAL_ERROR);
  1273. goto err;
  1274. }
  1275. dh = DHparams_dup(dhp);
  1276. if (dh == NULL) {
  1277. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
  1278. goto err;
  1279. }
  1280. s->s3->tmp.dh = dh;
  1281. if (dhp->pub_key == NULL || dhp->priv_key == NULL ||
  1282. (s->options & SSL_OP_SINGLE_DH_USE)) {
  1283. if (!DH_generate_key(dh)) {
  1284. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
  1285. goto err;
  1286. }
  1287. } else {
  1288. dh->pub_key = BN_dup(dhp->pub_key);
  1289. dh->priv_key = BN_dup(dhp->priv_key);
  1290. if (dh->pub_key == NULL || dh->priv_key == NULL) {
  1291. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
  1292. goto err;
  1293. }
  1294. }
  1295. r[0] = dh->p;
  1296. r[1] = dh->g;
  1297. r[2] = dh->pub_key;
  1298. } else if (alg_k & SSL_kEECDH) {
  1299. const EC_GROUP *group;
  1300. ecdhp = cert->ecdh_tmp;
  1301. if (s->cert->ecdh_tmp_auto) {
  1302. /* Get NID of appropriate shared curve */
  1303. int nid = tls1_get_shared_curve(s);
  1304. if (nid != NID_undef) {
  1305. ecdhp = EC_KEY_new_by_curve_name(nid);
  1306. }
  1307. } else if (ecdhp == NULL && s->cert->ecdh_tmp_cb) {
  1308. ecdhp = s->cert->ecdh_tmp_cb(s, 0, 1024);
  1309. }
  1310. if (ecdhp == NULL) {
  1311. al = SSL_AD_HANDSHAKE_FAILURE;
  1312. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
  1313. SSL_R_MISSING_TMP_ECDH_KEY);
  1314. goto f_err;
  1315. }
  1316. if (s->s3->tmp.ecdh != NULL) {
  1317. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
  1318. ERR_R_INTERNAL_ERROR);
  1319. goto err;
  1320. }
  1321. /* Duplicate the ECDH structure. */
  1322. if (ecdhp == NULL) {
  1323. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1324. goto err;
  1325. }
  1326. if (s->cert->ecdh_tmp_auto) {
  1327. ecdh = ecdhp;
  1328. } else {
  1329. ecdh = EC_KEY_dup(ecdhp);
  1330. if (ecdh == NULL) {
  1331. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1332. goto err;
  1333. }
  1334. }
  1335. s->s3->tmp.ecdh = ecdh;
  1336. if (EC_KEY_get0_public_key(ecdh) == NULL ||
  1337. EC_KEY_get0_private_key(ecdh) == NULL ||
  1338. (s->options & SSL_OP_SINGLE_ECDH_USE)) {
  1339. if (!EC_KEY_generate_key(ecdh)) {
  1340. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1341. goto err;
  1342. }
  1343. }
  1344. group = EC_KEY_get0_group(ecdh);
  1345. if (group == NULL ||
  1346. EC_KEY_get0_public_key(ecdh) == NULL ||
  1347. EC_KEY_get0_private_key(ecdh) == NULL) {
  1348. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1349. goto err;
  1350. }
  1351. /* We only support ephemeral ECDH keys over named (not generic) curves. */
  1352. if (!tls1_ec_nid2curve_id(&curve_id, EC_GROUP_get_curve_name(group))) {
  1353. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
  1354. SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
  1355. goto err;
  1356. }
  1357. /* Encode the public key. First check the size of encoding and allocate
  1358. * memory accordingly. */
  1359. encodedlen =
  1360. EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
  1361. POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
  1362. encodedPoint = (uint8_t *)OPENSSL_malloc(encodedlen * sizeof(uint8_t));
  1363. bn_ctx = BN_CTX_new();
  1364. if (encodedPoint == NULL || bn_ctx == NULL) {
  1365. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
  1366. ERR_R_MALLOC_FAILURE);
  1367. goto err;
  1368. }
  1369. encodedlen = EC_POINT_point2oct(group, EC_KEY_get0_public_key(ecdh),
  1370. POINT_CONVERSION_UNCOMPRESSED,
  1371. encodedPoint, encodedlen, bn_ctx);
  1372. if (encodedlen == 0) {
  1373. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1374. goto err;
  1375. }
  1376. BN_CTX_free(bn_ctx);
  1377. bn_ctx = NULL;
  1378. /* We only support named (not generic) curves in ECDH ephemeral key
  1379. * exchanges. In this situation, we need four additional bytes to encode
  1380. * the entire ServerECDHParams structure. */
  1381. n += 4 + encodedlen;
  1382. /* We'll generate the serverKeyExchange message explicitly so we can set
  1383. * these to NULLs */
  1384. r[0] = NULL;
  1385. r[1] = NULL;
  1386. r[2] = NULL;
  1387. r[3] = NULL;
  1388. } else if (!(alg_k & SSL_kPSK)) {
  1389. al = SSL_AD_HANDSHAKE_FAILURE;
  1390. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
  1391. SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
  1392. goto f_err;
  1393. }
  1394. for (i = 0; i < 4 && r[i] != NULL; i++) {
  1395. nr[i] = BN_num_bytes(r[i]);
  1396. n += 2 + nr[i];
  1397. }
  1398. if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
  1399. pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher);
  1400. if (pkey == NULL) {
  1401. al = SSL_AD_DECODE_ERROR;
  1402. goto f_err;
  1403. }
  1404. kn = EVP_PKEY_size(pkey);
  1405. } else {
  1406. pkey = NULL;
  1407. kn = 0;
  1408. }
  1409. if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
  1410. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_BUF);
  1411. goto err;
  1412. }
  1413. d = p = ssl_handshake_start(s);
  1414. for (i = 0; i < 4 && r[i] != NULL; i++) {
  1415. s2n(nr[i], p);
  1416. BN_bn2bin(r[i], p);
  1417. p += nr[i];
  1418. }
  1419. /* Note: ECDHE PSK ciphersuites use SSL_kEECDH and SSL_aPSK. When one of
  1420. * them is used, the server key exchange record needs to have both the
  1421. * psk_identity_hint and the ServerECDHParams. */
  1422. if (alg_a & SSL_aPSK) {
  1423. /* copy PSK identity hint (if provided) */
  1424. s2n(psk_identity_hint_len, p);
  1425. if (psk_identity_hint_len > 0) {
  1426. memcpy(p, psk_identity_hint, psk_identity_hint_len);
  1427. p += psk_identity_hint_len;
  1428. }
  1429. }
  1430. if (alg_k & SSL_kEECDH) {
  1431. /* We only support named (not generic) curves. In this situation, the
  1432. * serverKeyExchange message has:
  1433. * [1 byte CurveType], [2 byte CurveName]
  1434. * [1 byte length of encoded point], followed by
  1435. * the actual encoded point itself. */
  1436. *(p++) = NAMED_CURVE_TYPE;
  1437. *(p++) = (uint8_t)(curve_id >> 8);
  1438. *(p++) = (uint8_t)(curve_id & 0xff);
  1439. *(p++) = encodedlen;
  1440. memcpy(p, encodedPoint, encodedlen);
  1441. p += encodedlen;
  1442. OPENSSL_free(encodedPoint);
  1443. encodedPoint = NULL;
  1444. }
  1445. /* not anonymous */
  1446. if (pkey != NULL) {
  1447. /* n is the length of the params, they start at &(d[4]) and p points to
  1448. * the space at the end. */
  1449. const EVP_MD *md;
  1450. size_t sig_len = EVP_PKEY_size(pkey);
  1451. /* Determine signature algorithm. */
  1452. if (SSL_USE_SIGALGS(s)) {
  1453. md = tls1_choose_signing_digest(s, pkey);
  1454. if (!tls12_get_sigandhash(p, pkey, md)) {
  1455. /* Should never happen */
  1456. al = SSL_AD_INTERNAL_ERROR;
  1457. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange,
  1458. ERR_R_INTERNAL_ERROR);
  1459. goto f_err;
  1460. }
  1461. p += 2;
  1462. } else if (pkey->type == EVP_PKEY_RSA) {
  1463. md = EVP_md5_sha1();
  1464. } else {
  1465. md = EVP_sha1();
  1466. }
  1467. if (!EVP_DigestSignInit(&md_ctx, NULL, md, NULL, pkey) ||
  1468. !EVP_DigestSignUpdate(&md_ctx, s->s3->client_random,
  1469. SSL3_RANDOM_SIZE) ||
  1470. !EVP_DigestSignUpdate(&md_ctx, s->s3->server_random,
  1471. SSL3_RANDOM_SIZE) ||
  1472. !EVP_DigestSignUpdate(&md_ctx, d, n) ||
  1473. !EVP_DigestSignFinal(&md_ctx, &p[2], &sig_len)) {
  1474. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_EVP);
  1475. goto err;
  1476. }
  1477. s2n(sig_len, p);
  1478. n += sig_len + 2;
  1479. if (SSL_USE_SIGALGS(s)) {
  1480. n += 2;
  1481. }
  1482. }
  1483. ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
  1484. }
  1485. s->state = SSL3_ST_SW_KEY_EXCH_B;
  1486. EVP_MD_CTX_cleanup(&md_ctx);
  1487. return ssl_do_write(s);
  1488. f_err:
  1489. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1490. err:
  1491. if (encodedPoint != NULL) {
  1492. OPENSSL_free(encodedPoint);
  1493. }
  1494. BN_CTX_free(bn_ctx);
  1495. EVP_MD_CTX_cleanup(&md_ctx);
  1496. return -1;
  1497. }
  1498. int ssl3_send_certificate_request(SSL *s) {
  1499. uint8_t *p, *d;
  1500. size_t i;
  1501. int j, nl, off, n;
  1502. STACK_OF(X509_NAME) *sk = NULL;
  1503. X509_NAME *name;
  1504. BUF_MEM *buf;
  1505. if (s->state == SSL3_ST_SW_CERT_REQ_A) {
  1506. buf = s->init_buf;
  1507. d = p = ssl_handshake_start(s);
  1508. /* get the list of acceptable cert types */
  1509. p++;
  1510. n = ssl3_get_req_cert_type(s, p);
  1511. d[0] = n;
  1512. p += n;
  1513. n++;
  1514. if (SSL_USE_SIGALGS(s)) {
  1515. const uint8_t *psigs;
  1516. nl = tls12_get_psigalgs(s, &psigs);
  1517. s2n(nl, p);
  1518. memcpy(p, psigs, nl);
  1519. p += nl;
  1520. n += nl + 2;
  1521. }
  1522. off = n;
  1523. p += 2;
  1524. n += 2;
  1525. sk = SSL_get_client_CA_list(s);
  1526. nl = 0;
  1527. if (sk != NULL) {
  1528. for (i = 0; i < sk_X509_NAME_num(sk); i++) {
  1529. name = sk_X509_NAME_value(sk, i);
  1530. j = i2d_X509_NAME(name, NULL);
  1531. if (!BUF_MEM_grow_clean(buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
  1532. OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
  1533. goto err;
  1534. }
  1535. p = ssl_handshake_start(s) + n;
  1536. s2n(j, p);
  1537. i2d_X509_NAME(name, &p);
  1538. n += 2 + j;
  1539. nl += 2 + j;
  1540. }
  1541. }
  1542. /* else no CA names */
  1543. p = ssl_handshake_start(s) + off;
  1544. s2n(nl, p);
  1545. ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
  1546. s->state = SSL3_ST_SW_CERT_REQ_B;
  1547. }
  1548. /* SSL3_ST_SW_CERT_REQ_B */
  1549. return ssl_do_write(s);
  1550. err:
  1551. return -1;
  1552. }
  1553. int ssl3_get_client_key_exchange(SSL *s) {
  1554. int al, ok;
  1555. long n;
  1556. CBS client_key_exchange;
  1557. unsigned long alg_k;
  1558. unsigned long alg_a;
  1559. uint8_t *premaster_secret = NULL;
  1560. size_t premaster_secret_len = 0;
  1561. RSA *rsa = NULL;
  1562. uint8_t *decrypt_buf = NULL;
  1563. EVP_PKEY *pkey = NULL;
  1564. BIGNUM *pub = NULL;
  1565. DH *dh_srvr;
  1566. EC_KEY *srvr_ecdh = NULL;
  1567. EVP_PKEY *clnt_pub_pkey = NULL;
  1568. EC_POINT *clnt_ecpoint = NULL;
  1569. BN_CTX *bn_ctx = NULL;
  1570. unsigned int psk_len = 0;
  1571. uint8_t psk[PSK_MAX_PSK_LEN];
  1572. n = s->method->ssl_get_message(s, SSL3_ST_SR_KEY_EXCH_A,
  1573. SSL3_ST_SR_KEY_EXCH_B,
  1574. SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, /* ??? */
  1575. SSL_GET_MESSAGE_HASH_MESSAGE, &ok);
  1576. if (!ok) {
  1577. return n;
  1578. }
  1579. CBS_init(&client_key_exchange, s->init_msg, n);
  1580. alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
  1581. alg_a = s->s3->tmp.new_cipher->algorithm_auth;
  1582. /* If using a PSK key exchange, prepare the pre-shared key. */
  1583. if (alg_a & SSL_aPSK) {
  1584. CBS psk_identity;
  1585. /* If using PSK, the ClientKeyExchange contains a psk_identity. If PSK,
  1586. * then this is the only field in the message. */
  1587. if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
  1588. ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0)) {
  1589. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
  1590. al = SSL_AD_DECODE_ERROR;
  1591. goto f_err;
  1592. }
  1593. if (s->psk_server_callback == NULL) {
  1594. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1595. SSL_R_PSK_NO_SERVER_CB);
  1596. al = SSL_AD_INTERNAL_ERROR;
  1597. goto f_err;
  1598. }
  1599. if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
  1600. CBS_contains_zero_byte(&psk_identity)) {
  1601. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1602. SSL_R_DATA_LENGTH_TOO_LONG);
  1603. al = SSL_AD_ILLEGAL_PARAMETER;
  1604. goto f_err;
  1605. }
  1606. if (!CBS_strdup(&psk_identity, &s->session->psk_identity)) {
  1607. al = SSL_AD_INTERNAL_ERROR;
  1608. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1609. ERR_R_MALLOC_FAILURE);
  1610. goto f_err;
  1611. }
  1612. /* Look up the key for the identity. */
  1613. psk_len =
  1614. s->psk_server_callback(s, s->session->psk_identity, psk, sizeof(psk));
  1615. if (psk_len > PSK_MAX_PSK_LEN) {
  1616. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1617. ERR_R_INTERNAL_ERROR);
  1618. al = SSL_AD_INTERNAL_ERROR;
  1619. goto f_err;
  1620. } else if (psk_len == 0) {
  1621. /* PSK related to the given identity not found */
  1622. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1623. SSL_R_PSK_IDENTITY_NOT_FOUND);
  1624. al = SSL_AD_UNKNOWN_PSK_IDENTITY;
  1625. goto f_err;
  1626. }
  1627. }
  1628. /* Depending on the key exchange method, compute |premaster_secret| and
  1629. * |premaster_secret_len|. */
  1630. if (alg_k & SSL_kRSA) {
  1631. CBS encrypted_premaster_secret;
  1632. uint8_t rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
  1633. uint8_t good;
  1634. size_t rsa_size, decrypt_len, premaster_index, j;
  1635. pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
  1636. if (pkey == NULL || pkey->type != EVP_PKEY_RSA || pkey->pkey.rsa == NULL) {
  1637. al = SSL_AD_HANDSHAKE_FAILURE;
  1638. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1639. SSL_R_MISSING_RSA_CERTIFICATE);
  1640. goto f_err;
  1641. }
  1642. rsa = pkey->pkey.rsa;
  1643. /* TLS and [incidentally] DTLS{0xFEFF} */
  1644. if (s->version > SSL3_VERSION) {
  1645. CBS copy = client_key_exchange;
  1646. if (!CBS_get_u16_length_prefixed(&client_key_exchange,
  1647. &encrypted_premaster_secret) ||
  1648. CBS_len(&client_key_exchange) != 0) {
  1649. if (!(s->options & SSL_OP_TLS_D5_BUG)) {
  1650. al = SSL_AD_DECODE_ERROR;
  1651. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1652. SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
  1653. goto f_err;
  1654. } else {
  1655. encrypted_premaster_secret = copy;
  1656. }
  1657. }
  1658. } else {
  1659. encrypted_premaster_secret = client_key_exchange;
  1660. }
  1661. /* Reject overly short RSA keys because we want to be sure that the buffer
  1662. * size makes it safe to iterate over the entire size of a premaster secret
  1663. * (SSL_MAX_MASTER_KEY_LENGTH). The actual expected size is larger due to
  1664. * RSA padding, but the bound is sufficient to be safe. */
  1665. rsa_size = RSA_size(rsa);
  1666. if (rsa_size < SSL_MAX_MASTER_KEY_LENGTH) {
  1667. al = SSL_AD_DECRYPT_ERROR;
  1668. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1669. SSL_R_DECRYPTION_FAILED);
  1670. goto f_err;
  1671. }
  1672. /* We must not leak whether a decryption failure occurs because of
  1673. * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
  1674. * section 7.4.7.1). The code follows that advice of the TLS RFC and
  1675. * generates a random premaster secret for the case that the decrypt fails.
  1676. * See https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
  1677. if (!RAND_bytes(rand_premaster_secret, sizeof(rand_premaster_secret))) {
  1678. goto err;
  1679. }
  1680. /* Allocate a buffer large enough for an RSA decryption. */
  1681. decrypt_buf = OPENSSL_malloc(rsa_size);
  1682. if (decrypt_buf == NULL) {
  1683. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1684. ERR_R_MALLOC_FAILURE);
  1685. goto err;
  1686. }
  1687. /* Decrypt with no padding. PKCS#1 padding will be removed as part of the
  1688. * timing-sensitive code below. */
  1689. if (!RSA_decrypt(rsa, &decrypt_len, decrypt_buf, rsa_size,
  1690. CBS_data(&encrypted_premaster_secret),
  1691. CBS_len(&encrypted_premaster_secret), RSA_NO_PADDING)) {
  1692. goto err;
  1693. }
  1694. if (decrypt_len != rsa_size) {
  1695. /* This should never happen, but do a check so we do not read
  1696. * uninitialized memory. */
  1697. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1698. ERR_R_INTERNAL_ERROR);
  1699. goto err;
  1700. }
  1701. /* Remove the PKCS#1 padding and adjust |decrypt_len| as appropriate.
  1702. * |good| will be 0xff if the premaster is acceptable and zero otherwise.
  1703. * */
  1704. good =
  1705. constant_time_eq_int_8(RSA_message_index_PKCS1_type_2(
  1706. decrypt_buf, decrypt_len, &premaster_index),
  1707. 1);
  1708. decrypt_len = decrypt_len - premaster_index;
  1709. /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. */
  1710. good &= constant_time_eq_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
  1711. /* Copy over the unpadded premaster. Whatever the value of
  1712. * |decrypt_good_mask|, copy as if the premaster were the right length. It
  1713. * is important the memory access pattern be constant. */
  1714. premaster_secret =
  1715. BUF_memdup(decrypt_buf + (rsa_size - SSL_MAX_MASTER_KEY_LENGTH),
  1716. SSL_MAX_MASTER_KEY_LENGTH);
  1717. if (premaster_secret == NULL) {
  1718. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1719. ERR_R_MALLOC_FAILURE);
  1720. goto err;
  1721. }
  1722. OPENSSL_free(decrypt_buf);
  1723. decrypt_buf = NULL;
  1724. /* If the version in the decrypted pre-master secret is correct then
  1725. * version_good will be 0xff, otherwise it'll be zero. The
  1726. * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
  1727. * (http://eprint.iacr.org/2003/052/) exploits the version number check as
  1728. * a "bad version oracle". Thus version checks are done in constant time
  1729. * and are treated like any other decryption error. */
  1730. good &= constant_time_eq_8(premaster_secret[0],
  1731. (unsigned)(s->client_version >> 8));
  1732. good &= constant_time_eq_8(premaster_secret[1],
  1733. (unsigned)(s->client_version & 0xff));
  1734. /* Now copy rand_premaster_secret over premaster_secret using
  1735. * decrypt_good_mask. */
  1736. for (j = 0; j < sizeof(rand_premaster_secret); j++) {
  1737. premaster_secret[j] = constant_time_select_8(good, premaster_secret[j],
  1738. rand_premaster_secret[j]);
  1739. }
  1740. premaster_secret_len = sizeof(rand_premaster_secret);
  1741. } else if (alg_k & SSL_kEDH) {
  1742. CBS dh_Yc;
  1743. int dh_len;
  1744. if (!CBS_get_u16_length_prefixed(&client_key_exchange, &dh_Yc) ||
  1745. CBS_len(&dh_Yc) == 0 || CBS_len(&client_key_exchange) != 0) {
  1746. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1747. SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
  1748. al = SSL_R_DECODE_ERROR;
  1749. goto f_err;
  1750. }
  1751. if (s->s3->tmp.dh == NULL) {
  1752. al = SSL_AD_HANDSHAKE_FAILURE;
  1753. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1754. SSL_R_MISSING_TMP_DH_KEY);
  1755. goto f_err;
  1756. }
  1757. dh_srvr = s->s3->tmp.dh;
  1758. pub = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL);
  1759. if (pub == NULL) {
  1760. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_BN_LIB);
  1761. goto err;
  1762. }
  1763. /* Allocate a buffer for the premaster secret. */
  1764. premaster_secret = OPENSSL_malloc(DH_size(dh_srvr));
  1765. if (premaster_secret == NULL) {
  1766. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1767. ERR_R_MALLOC_FAILURE);
  1768. goto err;
  1769. }
  1770. dh_len = DH_compute_key(premaster_secret, pub, dh_srvr);
  1771. if (dh_len <= 0) {
  1772. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_DH_LIB);
  1773. BN_clear_free(pub);
  1774. goto err;
  1775. }
  1776. DH_free(s->s3->tmp.dh);
  1777. s->s3->tmp.dh = NULL;
  1778. BN_clear_free(pub);
  1779. pub = NULL;
  1780. premaster_secret_len = dh_len;
  1781. } else if (alg_k & SSL_kEECDH) {
  1782. int field_size = 0, ecdh_len;
  1783. const EC_KEY *tkey;
  1784. const EC_GROUP *group;
  1785. const BIGNUM *priv_key;
  1786. CBS ecdh_Yc;
  1787. /* initialize structures for server's ECDH key pair */
  1788. srvr_ecdh = EC_KEY_new();
  1789. if (srvr_ecdh == NULL) {
  1790. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1791. ERR_R_MALLOC_FAILURE);
  1792. goto err;
  1793. }
  1794. /* Use the ephermeral values we saved when generating the ServerKeyExchange
  1795. * msg. */
  1796. tkey = s->s3->tmp.ecdh;
  1797. group = EC_KEY_get0_group(tkey);
  1798. priv_key = EC_KEY_get0_private_key(tkey);
  1799. if (!EC_KEY_set_group(srvr_ecdh, group) ||
  1800. !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
  1801. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
  1802. goto err;
  1803. }
  1804. /* Let's get client's public key */
  1805. clnt_ecpoint = EC_POINT_new(group);
  1806. if (clnt_ecpoint == NULL) {
  1807. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1808. ERR_R_MALLOC_FAILURE);
  1809. goto err;
  1810. }
  1811. /* Get client's public key from encoded point in the ClientKeyExchange
  1812. * message. */
  1813. if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ecdh_Yc) ||
  1814. CBS_len(&client_key_exchange) != 0) {
  1815. al = SSL_AD_DECODE_ERROR;
  1816. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
  1817. goto f_err;
  1818. }
  1819. bn_ctx = BN_CTX_new();
  1820. if (bn_ctx == NULL) {
  1821. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1822. ERR_R_MALLOC_FAILURE);
  1823. goto err;
  1824. }
  1825. if (!EC_POINT_oct2point(group, clnt_ecpoint, CBS_data(&ecdh_Yc),
  1826. CBS_len(&ecdh_Yc), bn_ctx)) {
  1827. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
  1828. goto err;
  1829. }
  1830. /* Allocate a buffer for both the secret and the PSK. */
  1831. field_size = EC_GROUP_get_degree(group);
  1832. if (field_size <= 0) {
  1833. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
  1834. goto err;
  1835. }
  1836. ecdh_len = (field_size + 7) / 8;
  1837. premaster_secret = OPENSSL_malloc(ecdh_len);
  1838. if (premaster_secret == NULL) {
  1839. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1840. ERR_R_MALLOC_FAILURE);
  1841. goto err;
  1842. }
  1843. /* Compute the shared pre-master secret */
  1844. ecdh_len = ECDH_compute_key(premaster_secret, ecdh_len, clnt_ecpoint,
  1845. srvr_ecdh, NULL);
  1846. if (ecdh_len <= 0) {
  1847. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
  1848. goto err;
  1849. }
  1850. EVP_PKEY_free(clnt_pub_pkey);
  1851. clnt_pub_pkey = NULL;
  1852. EC_POINT_free(clnt_ecpoint);
  1853. clnt_ecpoint = NULL;
  1854. EC_KEY_free(srvr_ecdh);
  1855. srvr_ecdh = NULL;
  1856. BN_CTX_free(bn_ctx);
  1857. bn_ctx = NULL;
  1858. EC_KEY_free(s->s3->tmp.ecdh);
  1859. s->s3->tmp.ecdh = NULL;
  1860. premaster_secret_len = ecdh_len;
  1861. } else if (alg_k & SSL_kPSK) {
  1862. /* For plain PSK, other_secret is a block of 0s with the same length as the
  1863. * pre-shared key. */
  1864. premaster_secret_len = psk_len;
  1865. premaster_secret = OPENSSL_malloc(premaster_secret_len);
  1866. if (premaster_secret == NULL) {
  1867. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1868. ERR_R_MALLOC_FAILURE);
  1869. goto err;
  1870. }
  1871. memset(premaster_secret, 0, premaster_secret_len);
  1872. } else {
  1873. al = SSL_AD_HANDSHAKE_FAILURE;
  1874. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1875. SSL_R_UNKNOWN_CIPHER_TYPE);
  1876. goto f_err;
  1877. }
  1878. /* For a PSK cipher suite, the actual pre-master secret is combined with the
  1879. * pre-shared key. */
  1880. if (alg_a & SSL_aPSK) {
  1881. CBB new_premaster, child;
  1882. uint8_t *new_data;
  1883. size_t new_len;
  1884. if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len)) {
  1885. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1886. ERR_R_MALLOC_FAILURE);
  1887. goto err;
  1888. }
  1889. if (!CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1890. !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
  1891. !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1892. !CBB_add_bytes(&child, psk, psk_len) ||
  1893. !CBB_finish(&new_premaster, &new_data, &new_len)) {
  1894. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange,
  1895. ERR_R_INTERNAL_ERROR);
  1896. CBB_cleanup(&new_premaster);
  1897. goto err;
  1898. }
  1899. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1900. OPENSSL_free(premaster_secret);
  1901. premaster_secret = new_data;
  1902. premaster_secret_len = new_len;
  1903. }
  1904. /* Compute the master secret */
  1905. s->session->master_key_length = s->enc_method->generate_master_secret(
  1906. s, s->session->master_key, premaster_secret, premaster_secret_len);
  1907. if (s->session->master_key_length == 0) {
  1908. goto err;
  1909. }
  1910. s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
  1911. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1912. OPENSSL_free(premaster_secret);
  1913. return 1;
  1914. f_err:
  1915. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1916. err:
  1917. if (premaster_secret) {
  1918. if (premaster_secret_len) {
  1919. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1920. }
  1921. OPENSSL_free(premaster_secret);
  1922. }
  1923. if (decrypt_buf) {
  1924. OPENSSL_free(decrypt_buf);
  1925. }
  1926. EVP_PKEY_free(clnt_pub_pkey);
  1927. EC_POINT_free(clnt_ecpoint);
  1928. if (srvr_ecdh != NULL) {
  1929. EC_KEY_free(srvr_ecdh);
  1930. }
  1931. BN_CTX_free(bn_ctx);
  1932. return -1;
  1933. }
  1934. int ssl3_get_cert_verify(SSL *s) {
  1935. int al, ok, ret = 0;
  1936. long n;
  1937. CBS certificate_verify, signature;
  1938. X509 *peer = s->session->peer;
  1939. EVP_PKEY *pkey = NULL;
  1940. const EVP_MD *md = NULL;
  1941. uint8_t digest[EVP_MAX_MD_SIZE];
  1942. size_t digest_length;
  1943. EVP_PKEY_CTX *pctx = NULL;
  1944. /* Only RSA and ECDSA client certificates are supported, so a
  1945. * CertificateVerify is required if and only if there's a client certificate.
  1946. * */
  1947. if (peer == NULL) {
  1948. if (s->s3->handshake_buffer &&
  1949. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  1950. return -1;
  1951. }
  1952. return 1;
  1953. }
  1954. n = s->method->ssl_get_message(
  1955. s, SSL3_ST_SR_CERT_VRFY_A, SSL3_ST_SR_CERT_VRFY_B,
  1956. SSL3_MT_CERTIFICATE_VERIFY, SSL3_RT_MAX_PLAIN_LENGTH,
  1957. SSL_GET_MESSAGE_DONT_HASH_MESSAGE, &ok);
  1958. if (!ok) {
  1959. return n;
  1960. }
  1961. /* Filter out unsupported certificate types. */
  1962. pkey = X509_get_pubkey(peer);
  1963. if (!(X509_certificate_type(peer, pkey) & EVP_PKT_SIGN) ||
  1964. (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_EC)) {
  1965. al = SSL_AD_UNSUPPORTED_CERTIFICATE;
  1966. OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify,
  1967. SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
  1968. goto f_err;
  1969. }
  1970. CBS_init(&certificate_verify, s->init_msg, n);
  1971. /* Determine the digest type if needbe. */
  1972. if (SSL_USE_SIGALGS(s) &&
  1973. !tls12_check_peer_sigalg(&md, &al, s, &certificate_verify, pkey)) {
  1974. goto f_err;
  1975. }
  1976. /* Compute the digest. */
  1977. if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey)) {
  1978. goto err;
  1979. }
  1980. /* The handshake buffer is no longer necessary, and we may hash the current
  1981. * message.*/
  1982. if (s->s3->handshake_buffer &&
  1983. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  1984. goto err;
  1985. }
  1986. ssl3_hash_current_message(s);
  1987. /* Parse and verify the signature. */
  1988. if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
  1989. CBS_len(&certificate_verify) != 0) {
  1990. al = SSL_AD_DECODE_ERROR;
  1991. OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_DECODE_ERROR);
  1992. goto f_err;
  1993. }
  1994. pctx = EVP_PKEY_CTX_new(pkey, NULL);
  1995. if (pctx == NULL) {
  1996. goto err;
  1997. }
  1998. if (!EVP_PKEY_verify_init(pctx) ||
  1999. !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
  2000. !EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature), digest,
  2001. digest_length)) {
  2002. al = SSL_AD_DECRYPT_ERROR;
  2003. OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_SIGNATURE);
  2004. goto f_err;
  2005. }
  2006. ret = 1;
  2007. if (0) {
  2008. f_err:
  2009. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  2010. }
  2011. err:
  2012. EVP_PKEY_CTX_free(pctx);
  2013. EVP_PKEY_free(pkey);
  2014. return ret;
  2015. }
  2016. int ssl3_get_client_certificate(SSL *s) {
  2017. int i, ok, al, ret = -1;
  2018. X509 *x = NULL;
  2019. unsigned long n;
  2020. STACK_OF(X509) *sk = NULL;
  2021. SHA256_CTX sha256;
  2022. CBS certificate_msg, certificate_list;
  2023. int is_first_certificate = 1;
  2024. n = s->method->ssl_get_message(s, SSL3_ST_SR_CERT_A, SSL3_ST_SR_CERT_B, -1,
  2025. s->max_cert_list, SSL_GET_MESSAGE_HASH_MESSAGE,
  2026. &ok);
  2027. if (!ok) {
  2028. return n;
  2029. }
  2030. if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
  2031. if ((s->verify_mode & SSL_VERIFY_PEER) &&
  2032. (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  2033. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
  2034. SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  2035. al = SSL_AD_HANDSHAKE_FAILURE;
  2036. goto f_err;
  2037. }
  2038. /* If tls asked for a client cert, the client must return a 0 list */
  2039. if (s->version > SSL3_VERSION && s->s3->tmp.cert_request) {
  2040. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
  2041. SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
  2042. al = SSL_AD_UNEXPECTED_MESSAGE;
  2043. goto f_err;
  2044. }
  2045. s->s3->tmp.reuse_message = 1;
  2046. return 1;
  2047. }
  2048. if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
  2049. al = SSL_AD_UNEXPECTED_MESSAGE;
  2050. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
  2051. SSL_R_WRONG_MESSAGE_TYPE);
  2052. goto f_err;
  2053. }
  2054. CBS_init(&certificate_msg, s->init_msg, n);
  2055. sk = sk_X509_new_null();
  2056. if (sk == NULL) {
  2057. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
  2058. goto err;
  2059. }
  2060. if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
  2061. CBS_len(&certificate_msg) != 0) {
  2062. al = SSL_AD_DECODE_ERROR;
  2063. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
  2064. goto f_err;
  2065. }
  2066. while (CBS_len(&certificate_list) > 0) {
  2067. CBS certificate;
  2068. const uint8_t *data;
  2069. if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
  2070. al = SSL_AD_DECODE_ERROR;
  2071. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
  2072. goto f_err;
  2073. }
  2074. if (is_first_certificate && s->ctx->retain_only_sha256_of_client_certs) {
  2075. /* If this is the first certificate, and we don't want to keep peer
  2076. * certificates in memory, then we hash it right away. */
  2077. SHA256_Init(&sha256);
  2078. SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
  2079. SHA256_Final(s->session->peer_sha256, &sha256);
  2080. s->session->peer_sha256_valid = 1;
  2081. }
  2082. is_first_certificate = 0;
  2083. data = CBS_data(&certificate);
  2084. x = d2i_X509(NULL, &data, CBS_len(&certificate));
  2085. if (x == NULL) {
  2086. al = SSL_AD_BAD_CERTIFICATE;
  2087. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_ASN1_LIB);
  2088. goto f_err;
  2089. }
  2090. if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
  2091. al = SSL_AD_DECODE_ERROR;
  2092. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
  2093. SSL_R_CERT_LENGTH_MISMATCH);
  2094. goto f_err;
  2095. }
  2096. if (!sk_X509_push(sk, x)) {
  2097. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
  2098. goto err;
  2099. }
  2100. x = NULL;
  2101. }
  2102. if (sk_X509_num(sk) <= 0) {
  2103. /* TLS does not mind 0 certs returned */
  2104. if (s->version == SSL3_VERSION) {
  2105. al = SSL_AD_HANDSHAKE_FAILURE;
  2106. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
  2107. SSL_R_NO_CERTIFICATES_RETURNED);
  2108. goto f_err;
  2109. }
  2110. /* Fail for TLS only if we required a certificate */
  2111. else if ((s->verify_mode & SSL_VERIFY_PEER) &&
  2112. (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
  2113. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
  2114. SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  2115. al = SSL_AD_HANDSHAKE_FAILURE;
  2116. goto f_err;
  2117. }
  2118. /* No client certificate so digest cached records */
  2119. if (s->s3->handshake_buffer &&
  2120. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  2121. al = SSL_AD_INTERNAL_ERROR;
  2122. goto f_err;
  2123. }
  2124. } else {
  2125. i = ssl_verify_cert_chain(s, sk);
  2126. if (i <= 0) {
  2127. al = ssl_verify_alarm_type(s->verify_result);
  2128. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate,
  2129. SSL_R_CERTIFICATE_VERIFY_FAILED);
  2130. goto f_err;
  2131. }
  2132. }
  2133. if (s->session->peer != NULL) {
  2134. /* This should not be needed */
  2135. X509_free(s->session->peer);
  2136. }
  2137. s->session->peer = sk_X509_shift(sk);
  2138. s->session->verify_result = s->verify_result;
  2139. /* With the current implementation, sess_cert will always be NULL when we
  2140. * arrive here. */
  2141. if (s->session->sess_cert == NULL) {
  2142. s->session->sess_cert = ssl_sess_cert_new();
  2143. if (s->session->sess_cert == NULL) {
  2144. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
  2145. goto err;
  2146. }
  2147. }
  2148. if (s->session->sess_cert->cert_chain != NULL) {
  2149. sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
  2150. }
  2151. s->session->sess_cert->cert_chain = sk;
  2152. /* Inconsistency alert: cert_chain does *not* include the peer's own
  2153. * certificate, while we do include it in s3_clnt.c */
  2154. sk = NULL;
  2155. ret = 1;
  2156. if (0) {
  2157. f_err:
  2158. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  2159. }
  2160. err:
  2161. if (x != NULL) {
  2162. X509_free(x);
  2163. }
  2164. if (sk != NULL) {
  2165. sk_X509_pop_free(sk, X509_free);
  2166. }
  2167. return ret;
  2168. }
  2169. int ssl3_send_server_certificate(SSL *s) {
  2170. CERT_PKEY *cpk;
  2171. if (s->state == SSL3_ST_SW_CERT_A) {
  2172. cpk = ssl_get_server_send_pkey(s);
  2173. if (cpk == NULL) {
  2174. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_certificate,
  2175. ERR_R_INTERNAL_ERROR);
  2176. return 0;
  2177. }
  2178. ssl3_output_cert_chain(s, cpk);
  2179. s->state = SSL3_ST_SW_CERT_B;
  2180. }
  2181. /* SSL3_ST_SW_CERT_B */
  2182. return ssl_do_write(s);
  2183. }
  2184. /* send a new session ticket (not necessarily for a new session) */
  2185. int ssl3_send_new_session_ticket(SSL *s) {
  2186. if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
  2187. uint8_t *session;
  2188. size_t session_len;
  2189. uint8_t *p, *macstart;
  2190. int len;
  2191. unsigned int hlen;
  2192. EVP_CIPHER_CTX ctx;
  2193. HMAC_CTX hctx;
  2194. SSL_CTX *tctx = s->initial_ctx;
  2195. uint8_t iv[EVP_MAX_IV_LENGTH];
  2196. uint8_t key_name[16];
  2197. /* The maximum overhead of encrypting the session is 16 (key name) + IV +
  2198. * one block of encryption overhead + HMAC. */
  2199. const size_t max_ticket_overhead =
  2200. 16 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
  2201. /* Serialize the SSL_SESSION to be encoded into the ticket. */
  2202. if (!SSL_SESSION_to_bytes_for_ticket(s->session, &session, &session_len)) {
  2203. return -1;
  2204. }
  2205. /* If the session is too long, emit a dummy value rather than abort the
  2206. * connection. */
  2207. if (session_len > 0xFFFF - max_ticket_overhead) {
  2208. static const char kTicketPlaceholder[] = "TICKET TOO LARGE";
  2209. const size_t placeholder_len = strlen(kTicketPlaceholder);
  2210. OPENSSL_free(session);
  2211. p = ssl_handshake_start(s);
  2212. /* Emit ticket_lifetime_hint. */
  2213. l2n(0, p);
  2214. /* Emit ticket. */
  2215. s2n(placeholder_len, p);
  2216. memcpy(p, kTicketPlaceholder, placeholder_len);
  2217. p += placeholder_len;
  2218. len = p - ssl_handshake_start(s);
  2219. ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
  2220. s->state = SSL3_ST_SW_SESSION_TICKET_B;
  2221. return ssl_do_write(s);
  2222. }
  2223. /* Grow buffer if need be: the length calculation is as follows:
  2224. * handshake_header_length + 4 (ticket lifetime hint) + 2 (ticket length) +
  2225. * max_ticket_overhead + * session_length */
  2226. if (!BUF_MEM_grow(s->init_buf, SSL_HM_HEADER_LENGTH(s) + 6 +
  2227. max_ticket_overhead + session_len)) {
  2228. OPENSSL_free(session);
  2229. return -1;
  2230. }
  2231. p = ssl_handshake_start(s);
  2232. EVP_CIPHER_CTX_init(&ctx);
  2233. HMAC_CTX_init(&hctx);
  2234. /* Initialize HMAC and cipher contexts. If callback present it does all the
  2235. * work otherwise use generated values from parent ctx. */
  2236. if (tctx->tlsext_ticket_key_cb) {
  2237. if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx, &hctx, 1) < 0) {
  2238. OPENSSL_free(session);
  2239. EVP_CIPHER_CTX_cleanup(&ctx);
  2240. HMAC_CTX_cleanup(&hctx);
  2241. return -1;
  2242. }
  2243. } else {
  2244. if (!RAND_bytes(iv, 16) ||
  2245. !EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
  2246. tctx->tlsext_tick_aes_key, iv) ||
  2247. !HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16, tlsext_tick_md(),
  2248. NULL)) {
  2249. OPENSSL_free(session);
  2250. EVP_CIPHER_CTX_cleanup(&ctx);
  2251. HMAC_CTX_cleanup(&hctx);
  2252. return -1;
  2253. }
  2254. memcpy(key_name, tctx->tlsext_tick_key_name, 16);
  2255. }
  2256. /* Ticket lifetime hint (advisory only): We leave this unspecified for
  2257. * resumed session (for simplicity), and guess that tickets for new
  2258. * sessions will live as long as their sessions. */
  2259. l2n(s->hit ? 0 : s->session->timeout, p);
  2260. /* Skip ticket length for now */
  2261. p += 2;
  2262. /* Output key name */
  2263. macstart = p;
  2264. memcpy(p, key_name, 16);
  2265. p += 16;
  2266. /* output IV */
  2267. memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
  2268. p += EVP_CIPHER_CTX_iv_length(&ctx);
  2269. /* Encrypt session data */
  2270. EVP_EncryptUpdate(&ctx, p, &len, session, session_len);
  2271. p += len;
  2272. EVP_EncryptFinal_ex(&ctx, p, &len);
  2273. p += len;
  2274. EVP_CIPHER_CTX_cleanup(&ctx);
  2275. HMAC_Update(&hctx, macstart, p - macstart);
  2276. HMAC_Final(&hctx, p, &hlen);
  2277. HMAC_CTX_cleanup(&hctx);
  2278. p += hlen;
  2279. /* Now write out lengths: p points to end of data written */
  2280. /* Total length */
  2281. len = p - ssl_handshake_start(s);
  2282. /* Skip ticket lifetime hint */
  2283. p = ssl_handshake_start(s) + 4;
  2284. s2n(len - 6, p);
  2285. ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
  2286. s->state = SSL3_ST_SW_SESSION_TICKET_B;
  2287. OPENSSL_free(session);
  2288. }
  2289. /* SSL3_ST_SW_SESSION_TICKET_B */
  2290. return ssl_do_write(s);
  2291. }
  2292. /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
  2293. * sets the next_proto member in s if found */
  2294. int ssl3_get_next_proto(SSL *s) {
  2295. int ok;
  2296. long n;
  2297. CBS next_protocol, selected_protocol, padding;
  2298. /* Clients cannot send a NextProtocol message if we didn't see the extension
  2299. * in their ClientHello */
  2300. if (!s->s3->next_proto_neg_seen) {
  2301. OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto,
  2302. SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
  2303. return -1;
  2304. }
  2305. n = s->method->ssl_get_message(s, SSL3_ST_SR_NEXT_PROTO_A,
  2306. SSL3_ST_SR_NEXT_PROTO_B, SSL3_MT_NEXT_PROTO,
  2307. 514, /* See the payload format below */
  2308. SSL_GET_MESSAGE_HASH_MESSAGE, &ok);
  2309. if (!ok) {
  2310. return n;
  2311. }
  2312. /* s->state doesn't reflect whether ChangeCipherSpec has been received in
  2313. * this handshake, but s->s3->change_cipher_spec does (will be reset by
  2314. * ssl3_get_finished).
  2315. *
  2316. * TODO(davidben): Is this check now redundant with
  2317. * SSL3_FLAGS_EXPECT_CCS? */
  2318. if (!s->s3->change_cipher_spec) {
  2319. OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto,
  2320. SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
  2321. return -1;
  2322. }
  2323. CBS_init(&next_protocol, s->init_msg, n);
  2324. /* The payload looks like:
  2325. * uint8 proto_len;
  2326. * uint8 proto[proto_len];
  2327. * uint8 padding_len;
  2328. * uint8 padding[padding_len]; */
  2329. if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
  2330. !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
  2331. CBS_len(&next_protocol) != 0 ||
  2332. !CBS_stow(&selected_protocol, &s->next_proto_negotiated,
  2333. &s->next_proto_negotiated_len)) {
  2334. return 0;
  2335. }
  2336. return 1;
  2337. }
  2338. /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
  2339. int ssl3_get_channel_id(SSL *s) {
  2340. int ret = -1, ok;
  2341. long n;
  2342. EVP_MD_CTX md_ctx;
  2343. uint8_t channel_id_hash[SHA256_DIGEST_LENGTH];
  2344. unsigned int channel_id_hash_len;
  2345. const uint8_t *p;
  2346. uint16_t extension_type, expected_extension_type;
  2347. EC_GROUP *p256 = NULL;
  2348. EC_KEY *key = NULL;
  2349. EC_POINT *point = NULL;
  2350. ECDSA_SIG sig;
  2351. BIGNUM x, y;
  2352. CBS encrypted_extensions, extension;
  2353. n = s->method->ssl_get_message(
  2354. s, SSL3_ST_SR_CHANNEL_ID_A, SSL3_ST_SR_CHANNEL_ID_B,
  2355. SSL3_MT_ENCRYPTED_EXTENSIONS, 2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
  2356. SSL_GET_MESSAGE_DONT_HASH_MESSAGE, &ok);
  2357. if (!ok) {
  2358. return n;
  2359. }
  2360. /* Before incorporating the EncryptedExtensions message to the handshake
  2361. * hash, compute the hash that should have been signed. */
  2362. channel_id_hash_len = sizeof(channel_id_hash);
  2363. EVP_MD_CTX_init(&md_ctx);
  2364. if (!EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL) ||
  2365. !tls1_channel_id_hash(&md_ctx, s) ||
  2366. !EVP_DigestFinal(&md_ctx, channel_id_hash, &channel_id_hash_len)) {
  2367. EVP_MD_CTX_cleanup(&md_ctx);
  2368. return -1;
  2369. }
  2370. EVP_MD_CTX_cleanup(&md_ctx);
  2371. assert(channel_id_hash_len == SHA256_DIGEST_LENGTH);
  2372. ssl3_hash_current_message(s);
  2373. /* s->state doesn't reflect whether ChangeCipherSpec has been received in
  2374. * this handshake, but s->s3->change_cipher_spec does (will be reset by
  2375. * ssl3_get_finished).
  2376. *
  2377. * TODO(davidben): Is this check now redundant with SSL3_FLAGS_EXPECT_CCS? */
  2378. if (!s->s3->change_cipher_spec) {
  2379. OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id,
  2380. SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS);
  2381. return -1;
  2382. }
  2383. CBS_init(&encrypted_extensions, s->init_msg, n);
  2384. /* EncryptedExtensions could include multiple extensions, but the only
  2385. * extension that could be negotiated is ChannelID, so there can only be one
  2386. * entry.
  2387. *
  2388. * The payload looks like:
  2389. * uint16 extension_type
  2390. * uint16 extension_len;
  2391. * uint8 x[32];
  2392. * uint8 y[32];
  2393. * uint8 r[32];
  2394. * uint8 s[32]; */
  2395. expected_extension_type = TLSEXT_TYPE_channel_id;
  2396. if (s->s3->tlsext_channel_id_new) {
  2397. expected_extension_type = TLSEXT_TYPE_channel_id_new;
  2398. }
  2399. if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
  2400. !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
  2401. CBS_len(&encrypted_extensions) != 0 ||
  2402. extension_type != expected_extension_type ||
  2403. CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE) {
  2404. OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_INVALID_MESSAGE);
  2405. return -1;
  2406. }
  2407. p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
  2408. if (!p256) {
  2409. OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_NO_P256_SUPPORT);
  2410. return -1;
  2411. }
  2412. BN_init(&x);
  2413. BN_init(&y);
  2414. sig.r = BN_new();
  2415. sig.s = BN_new();
  2416. p = CBS_data(&extension);
  2417. if (BN_bin2bn(p + 0, 32, &x) == NULL ||
  2418. BN_bin2bn(p + 32, 32, &y) == NULL ||
  2419. BN_bin2bn(p + 64, 32, sig.r) == NULL ||
  2420. BN_bin2bn(p + 96, 32, sig.s) == NULL) {
  2421. goto err;
  2422. }
  2423. point = EC_POINT_new(p256);
  2424. if (!point || !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL)) {
  2425. goto err;
  2426. }
  2427. key = EC_KEY_new();
  2428. if (!key || !EC_KEY_set_group(key, p256) ||
  2429. !EC_KEY_set_public_key(key, point)) {
  2430. goto err;
  2431. }
  2432. /* We stored the handshake hash in |tlsext_channel_id| the first time that we
  2433. * were called. */
  2434. if (!ECDSA_do_verify(channel_id_hash, channel_id_hash_len, &sig, key)) {
  2435. OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id,
  2436. SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
  2437. s->s3->tlsext_channel_id_valid = 0;
  2438. goto err;
  2439. }
  2440. memcpy(s->s3->tlsext_channel_id, p, 64);
  2441. ret = 1;
  2442. err:
  2443. BN_free(&x);
  2444. BN_free(&y);
  2445. BN_free(sig.r);
  2446. BN_free(sig.s);
  2447. if (key) {
  2448. EC_KEY_free(key);
  2449. }
  2450. if (point) {
  2451. EC_POINT_free(point);
  2452. }
  2453. if (p256) {
  2454. EC_GROUP_free(p256);
  2455. }
  2456. return ret;
  2457. }