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

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