Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

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