You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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