Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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