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

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