No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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