Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

2213 rader
66 KiB

  1. /* ssl/s3_clnt.c */
  2. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young (eay@cryptsoft.com).
  7. * The implementation was written so as to conform with Netscapes SSL.
  8. *
  9. * This library is free for commercial and non-commercial use as long as
  10. * the following conditions are aheared to. The following conditions
  11. * apply to all code found in this distribution, be it the RC4, RSA,
  12. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  13. * included with this distribution is covered by the same copyright terms
  14. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  15. *
  16. * Copyright remains Eric Young's, and as such any Copyright notices in
  17. * the code are not to be removed.
  18. * If this package is used in a product, Eric Young should be given attribution
  19. * as the author of the parts of the library used.
  20. * This can be in the form of a textual message at program startup or
  21. * in documentation (online or textual) provided with the package.
  22. *
  23. * Redistribution and use in source and binary forms, with or without
  24. * modification, are permitted provided that the following conditions
  25. * are met:
  26. * 1. Redistributions of source code must retain the copyright
  27. * notice, this list of conditions and the following disclaimer.
  28. * 2. Redistributions in binary form must reproduce the above copyright
  29. * notice, this list of conditions and the following disclaimer in the
  30. * documentation and/or other materials provided with the distribution.
  31. * 3. All advertising materials mentioning features or use of this software
  32. * must display the following acknowledgement:
  33. * "This product includes cryptographic software written by
  34. * Eric Young (eay@cryptsoft.com)"
  35. * The word 'cryptographic' can be left out if the rouines from the library
  36. * being used are not cryptographic related :-).
  37. * 4. If you include any Windows specific code (or a derivative thereof) from
  38. * the apps directory (application code) you must include an acknowledgement:
  39. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  40. *
  41. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  42. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  43. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  44. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  45. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  46. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  47. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  48. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  49. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  50. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  51. * SUCH DAMAGE.
  52. *
  53. * The licence and distribution terms for any publically available version or
  54. * derivative of this code cannot be changed. i.e. this code cannot simply be
  55. * copied and put under another distribution licence
  56. * [including the GNU Public Licence.]
  57. */
  58. /* ====================================================================
  59. * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
  60. *
  61. * Redistribution and use in source and binary forms, with or without
  62. * modification, are permitted provided that the following conditions
  63. * are met:
  64. *
  65. * 1. Redistributions of source code must retain the above copyright
  66. * notice, this list of conditions and the following disclaimer.
  67. *
  68. * 2. Redistributions in binary form must reproduce the above copyright
  69. * notice, this list of conditions and the following disclaimer in
  70. * the documentation and/or other materials provided with the
  71. * distribution.
  72. *
  73. * 3. All advertising materials mentioning features or use of this
  74. * software must display the following acknowledgment:
  75. * "This product includes software developed by the OpenSSL Project
  76. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  77. *
  78. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  79. * endorse or promote products derived from this software without
  80. * prior written permission. For written permission, please contact
  81. * openssl-core@openssl.org.
  82. *
  83. * 5. Products derived from this software may not be called "OpenSSL"
  84. * nor may "OpenSSL" appear in their names without prior written
  85. * permission of the OpenSSL Project.
  86. *
  87. * 6. Redistributions of any form whatsoever must retain the following
  88. * acknowledgment:
  89. * "This product includes software developed by the OpenSSL Project
  90. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  91. *
  92. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  93. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  94. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  95. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  96. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  97. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  98. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  99. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  100. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  101. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  102. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  103. * OF THE POSSIBILITY OF SUCH DAMAGE.
  104. * ====================================================================
  105. *
  106. * This product includes cryptographic software written by Eric Young
  107. * (eay@cryptsoft.com). This product includes software written by Tim
  108. * Hudson (tjh@cryptsoft.com).
  109. *
  110. */
  111. /* ====================================================================
  112. * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  113. *
  114. * Portions of the attached software ("Contribution") are developed by
  115. * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
  116. *
  117. * The Contribution is licensed pursuant to the OpenSSL open source
  118. * license provided above.
  119. *
  120. * ECC cipher suite support in OpenSSL originally written by
  121. * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
  122. *
  123. */
  124. /* ====================================================================
  125. * Copyright 2005 Nokia. All rights reserved.
  126. *
  127. * The portions of the attached software ("Contribution") is developed by
  128. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  129. * license.
  130. *
  131. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  132. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  133. * support (see RFC 4279) to OpenSSL.
  134. *
  135. * No patent licenses or other rights except those expressly stated in
  136. * the OpenSSL open source license shall be deemed granted or received
  137. * expressly, by implication, estoppel, or otherwise.
  138. *
  139. * No assurances are provided by Nokia that the Contribution does not
  140. * infringe the patent or other intellectual property rights of any third
  141. * party or that the license provides you with all the necessary rights
  142. * to make use of the Contribution.
  143. *
  144. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  145. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  146. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  147. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  148. * OTHERWISE.
  149. */
  150. #include <openssl/ssl.h>
  151. #include <assert.h>
  152. #include <stdio.h>
  153. #include <string.h>
  154. #include <openssl/bn.h>
  155. #include <openssl/buf.h>
  156. #include <openssl/bytestring.h>
  157. #include <openssl/dh.h>
  158. #include <openssl/ec_key.h>
  159. #include <openssl/ecdsa.h>
  160. #include <openssl/err.h>
  161. #include <openssl/evp.h>
  162. #include <openssl/md5.h>
  163. #include <openssl/mem.h>
  164. #include <openssl/obj.h>
  165. #include <openssl/rand.h>
  166. #include <openssl/x509.h>
  167. #include <openssl/x509v3.h>
  168. #include "internal.h"
  169. #include "../crypto/dh/internal.h"
  170. int ssl3_connect(SSL *s) {
  171. BUF_MEM *buf = NULL;
  172. void (*cb)(const SSL *ssl, int type, int val) = NULL;
  173. int ret = -1;
  174. int new_state, state, skip = 0;
  175. assert(s->handshake_func == ssl3_connect);
  176. assert(!s->server);
  177. assert(!SSL_IS_DTLS(s));
  178. ERR_clear_error();
  179. ERR_clear_system_error();
  180. if (s->info_callback != NULL) {
  181. cb = s->info_callback;
  182. } else if (s->ctx->info_callback != NULL) {
  183. cb = s->ctx->info_callback;
  184. }
  185. s->in_handshake++;
  186. for (;;) {
  187. state = s->state;
  188. switch (s->state) {
  189. case SSL_ST_CONNECT:
  190. if (cb != NULL) {
  191. cb(s, SSL_CB_HANDSHAKE_START, 1);
  192. }
  193. if (s->init_buf == NULL) {
  194. buf = BUF_MEM_new();
  195. if (buf == NULL ||
  196. !BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
  197. ret = -1;
  198. goto end;
  199. }
  200. s->init_buf = buf;
  201. buf = NULL;
  202. }
  203. if (!ssl_init_wbio_buffer(s, 0)) {
  204. ret = -1;
  205. goto end;
  206. }
  207. /* don't push the buffering BIO quite yet */
  208. if (!ssl3_init_handshake_buffer(s)) {
  209. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  210. ret = -1;
  211. goto end;
  212. }
  213. s->state = SSL3_ST_CW_CLNT_HELLO_A;
  214. s->init_num = 0;
  215. break;
  216. case SSL3_ST_CW_CLNT_HELLO_A:
  217. case SSL3_ST_CW_CLNT_HELLO_B:
  218. s->shutdown = 0;
  219. ret = ssl3_send_client_hello(s);
  220. if (ret <= 0) {
  221. goto end;
  222. }
  223. s->state = SSL3_ST_CR_SRVR_HELLO_A;
  224. s->init_num = 0;
  225. /* turn on buffering for the next lot of output */
  226. if (s->bbio != s->wbio) {
  227. s->wbio = BIO_push(s->bbio, s->wbio);
  228. }
  229. break;
  230. case SSL3_ST_CR_SRVR_HELLO_A:
  231. case SSL3_ST_CR_SRVR_HELLO_B:
  232. ret = ssl3_get_server_hello(s);
  233. if (ret <= 0) {
  234. goto end;
  235. }
  236. if (s->hit) {
  237. s->state = SSL3_ST_CR_CHANGE;
  238. if (s->tlsext_ticket_expected) {
  239. /* receive renewed session ticket */
  240. s->state = SSL3_ST_CR_SESSION_TICKET_A;
  241. }
  242. } else {
  243. s->state = SSL3_ST_CR_CERT_A;
  244. }
  245. s->init_num = 0;
  246. break;
  247. case SSL3_ST_CR_CERT_A:
  248. case SSL3_ST_CR_CERT_B:
  249. if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
  250. ret = ssl3_get_server_certificate(s);
  251. if (ret <= 0) {
  252. goto end;
  253. }
  254. if (s->s3->tmp.certificate_status_expected) {
  255. s->state = SSL3_ST_CR_CERT_STATUS_A;
  256. } else {
  257. s->state = SSL3_ST_VERIFY_SERVER_CERT;
  258. }
  259. } else {
  260. skip = 1;
  261. s->state = SSL3_ST_CR_KEY_EXCH_A;
  262. }
  263. s->init_num = 0;
  264. break;
  265. case SSL3_ST_VERIFY_SERVER_CERT:
  266. ret = ssl3_verify_server_cert(s);
  267. if (ret <= 0) {
  268. goto end;
  269. }
  270. s->state = SSL3_ST_CR_KEY_EXCH_A;
  271. s->init_num = 0;
  272. break;
  273. case SSL3_ST_CR_KEY_EXCH_A:
  274. case SSL3_ST_CR_KEY_EXCH_B:
  275. ret = ssl3_get_server_key_exchange(s);
  276. if (ret <= 0) {
  277. goto end;
  278. }
  279. s->state = SSL3_ST_CR_CERT_REQ_A;
  280. s->init_num = 0;
  281. break;
  282. case SSL3_ST_CR_CERT_REQ_A:
  283. case SSL3_ST_CR_CERT_REQ_B:
  284. ret = ssl3_get_certificate_request(s);
  285. if (ret <= 0) {
  286. goto end;
  287. }
  288. s->state = SSL3_ST_CR_SRVR_DONE_A;
  289. s->init_num = 0;
  290. break;
  291. case SSL3_ST_CR_SRVR_DONE_A:
  292. case SSL3_ST_CR_SRVR_DONE_B:
  293. ret = ssl3_get_server_done(s);
  294. if (ret <= 0) {
  295. goto end;
  296. }
  297. if (s->s3->tmp.cert_req) {
  298. s->state = SSL3_ST_CW_CERT_A;
  299. } else {
  300. s->state = SSL3_ST_CW_KEY_EXCH_A;
  301. }
  302. s->init_num = 0;
  303. break;
  304. case SSL3_ST_CW_CERT_A:
  305. case SSL3_ST_CW_CERT_B:
  306. case SSL3_ST_CW_CERT_C:
  307. case SSL3_ST_CW_CERT_D:
  308. ret = ssl3_send_client_certificate(s);
  309. if (ret <= 0) {
  310. goto end;
  311. }
  312. s->state = SSL3_ST_CW_KEY_EXCH_A;
  313. s->init_num = 0;
  314. break;
  315. case SSL3_ST_CW_KEY_EXCH_A:
  316. case SSL3_ST_CW_KEY_EXCH_B:
  317. ret = ssl3_send_client_key_exchange(s);
  318. if (ret <= 0) {
  319. goto end;
  320. }
  321. /* For TLS, cert_req is set to 2, so a cert chain
  322. * of nothing is sent, but no verify packet is sent */
  323. if (s->s3->tmp.cert_req == 1) {
  324. s->state = SSL3_ST_CW_CERT_VRFY_A;
  325. } else {
  326. s->state = SSL3_ST_CW_CHANGE_A;
  327. s->s3->change_cipher_spec = 0;
  328. }
  329. s->init_num = 0;
  330. break;
  331. case SSL3_ST_CW_CERT_VRFY_A:
  332. case SSL3_ST_CW_CERT_VRFY_B:
  333. case SSL3_ST_CW_CERT_VRFY_C:
  334. ret = ssl3_send_cert_verify(s);
  335. if (ret <= 0) {
  336. goto end;
  337. }
  338. s->state = SSL3_ST_CW_CHANGE_A;
  339. s->init_num = 0;
  340. s->s3->change_cipher_spec = 0;
  341. break;
  342. case SSL3_ST_CW_CHANGE_A:
  343. case SSL3_ST_CW_CHANGE_B:
  344. ret = ssl3_send_change_cipher_spec(s, SSL3_ST_CW_CHANGE_A,
  345. SSL3_ST_CW_CHANGE_B);
  346. if (ret <= 0) {
  347. goto end;
  348. }
  349. s->state = SSL3_ST_CW_FINISHED_A;
  350. if (s->s3->tlsext_channel_id_valid) {
  351. s->state = SSL3_ST_CW_CHANNEL_ID_A;
  352. }
  353. if (s->s3->next_proto_neg_seen) {
  354. s->state = SSL3_ST_CW_NEXT_PROTO_A;
  355. }
  356. s->init_num = 0;
  357. s->session->cipher = s->s3->tmp.new_cipher;
  358. if (!s->enc_method->setup_key_block(s) ||
  359. !s->enc_method->change_cipher_state(
  360. s, SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
  361. ret = -1;
  362. goto end;
  363. }
  364. break;
  365. case SSL3_ST_CW_NEXT_PROTO_A:
  366. case SSL3_ST_CW_NEXT_PROTO_B:
  367. ret = ssl3_send_next_proto(s);
  368. if (ret <= 0) {
  369. goto end;
  370. }
  371. if (s->s3->tlsext_channel_id_valid) {
  372. s->state = SSL3_ST_CW_CHANNEL_ID_A;
  373. } else {
  374. s->state = SSL3_ST_CW_FINISHED_A;
  375. }
  376. break;
  377. case SSL3_ST_CW_CHANNEL_ID_A:
  378. case SSL3_ST_CW_CHANNEL_ID_B:
  379. ret = ssl3_send_channel_id(s);
  380. if (ret <= 0) {
  381. goto end;
  382. }
  383. s->state = SSL3_ST_CW_FINISHED_A;
  384. break;
  385. case SSL3_ST_CW_FINISHED_A:
  386. case SSL3_ST_CW_FINISHED_B:
  387. ret =
  388. ssl3_send_finished(s, SSL3_ST_CW_FINISHED_A, SSL3_ST_CW_FINISHED_B,
  389. s->enc_method->client_finished_label,
  390. s->enc_method->client_finished_label_len);
  391. if (ret <= 0) {
  392. goto end;
  393. }
  394. s->state = SSL3_ST_CW_FLUSH;
  395. if (s->hit) {
  396. s->s3->tmp.next_state = SSL_ST_OK;
  397. } else {
  398. /* This is a non-resumption handshake. If it involves ChannelID, then
  399. * record the handshake hashes at this point in the session so that
  400. * any resumption of this session with ChannelID can sign those
  401. * hashes. */
  402. ret = tls1_record_handshake_hashes_for_channel_id(s);
  403. if (ret <= 0) {
  404. goto end;
  405. }
  406. if ((SSL_get_mode(s) & SSL_MODE_ENABLE_FALSE_START) &&
  407. ssl3_can_false_start(s) &&
  408. /* No False Start on renegotiation (would complicate the state
  409. * machine). */
  410. !s->s3->initial_handshake_complete) {
  411. s->s3->tmp.next_state = SSL3_ST_FALSE_START;
  412. } else {
  413. /* Allow NewSessionTicket if ticket expected */
  414. if (s->tlsext_ticket_expected) {
  415. s->s3->tmp.next_state = SSL3_ST_CR_SESSION_TICKET_A;
  416. } else {
  417. s->s3->tmp.next_state = SSL3_ST_CR_CHANGE;
  418. }
  419. }
  420. }
  421. s->init_num = 0;
  422. break;
  423. case SSL3_ST_CR_SESSION_TICKET_A:
  424. case SSL3_ST_CR_SESSION_TICKET_B:
  425. ret = ssl3_get_new_session_ticket(s);
  426. if (ret <= 0) {
  427. goto end;
  428. }
  429. s->state = SSL3_ST_CR_CHANGE;
  430. s->init_num = 0;
  431. break;
  432. case SSL3_ST_CR_CERT_STATUS_A:
  433. case SSL3_ST_CR_CERT_STATUS_B:
  434. ret = ssl3_get_cert_status(s);
  435. if (ret <= 0) {
  436. goto end;
  437. }
  438. s->state = SSL3_ST_VERIFY_SERVER_CERT;
  439. s->init_num = 0;
  440. break;
  441. case SSL3_ST_CR_CHANGE:
  442. /* At this point, the next message must be entirely behind a
  443. * ChangeCipherSpec. */
  444. if (!ssl3_expect_change_cipher_spec(s)) {
  445. ret = -1;
  446. goto end;
  447. }
  448. s->state = SSL3_ST_CR_FINISHED_A;
  449. break;
  450. case SSL3_ST_CR_FINISHED_A:
  451. case SSL3_ST_CR_FINISHED_B:
  452. ret =
  453. ssl3_get_finished(s, SSL3_ST_CR_FINISHED_A, SSL3_ST_CR_FINISHED_B);
  454. if (ret <= 0) {
  455. goto end;
  456. }
  457. if (s->hit) {
  458. s->state = SSL3_ST_CW_CHANGE_A;
  459. } else {
  460. s->state = SSL_ST_OK;
  461. }
  462. s->init_num = 0;
  463. break;
  464. case SSL3_ST_CW_FLUSH:
  465. s->rwstate = SSL_WRITING;
  466. if (BIO_flush(s->wbio) <= 0) {
  467. ret = -1;
  468. goto end;
  469. }
  470. s->rwstate = SSL_NOTHING;
  471. s->state = s->s3->tmp.next_state;
  472. break;
  473. case SSL3_ST_FALSE_START:
  474. /* Allow NewSessionTicket if ticket expected */
  475. if (s->tlsext_ticket_expected) {
  476. s->state = SSL3_ST_CR_SESSION_TICKET_A;
  477. } else {
  478. s->state = SSL3_ST_CR_CHANGE;
  479. }
  480. s->s3->tmp.in_false_start = 1;
  481. ssl_free_wbio_buffer(s);
  482. ret = 1;
  483. goto end;
  484. case SSL_ST_OK:
  485. /* clean a few things up */
  486. ssl3_cleanup_key_block(s);
  487. BUF_MEM_free(s->init_buf);
  488. s->init_buf = NULL;
  489. /* Remove write buffering now. */
  490. ssl_free_wbio_buffer(s);
  491. const int is_initial_handshake = !s->s3->initial_handshake_complete;
  492. s->init_num = 0;
  493. s->s3->tmp.in_false_start = 0;
  494. s->s3->initial_handshake_complete = 1;
  495. if (is_initial_handshake) {
  496. /* Renegotiations do not participate in session resumption. */
  497. ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
  498. }
  499. ret = 1;
  500. /* s->server=0; */
  501. if (cb != NULL) {
  502. cb(s, SSL_CB_HANDSHAKE_DONE, 1);
  503. }
  504. goto end;
  505. default:
  506. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_STATE);
  507. ret = -1;
  508. goto end;
  509. }
  510. if (!s->s3->tmp.reuse_message && !skip) {
  511. if (cb != NULL && s->state != state) {
  512. new_state = s->state;
  513. s->state = state;
  514. cb(s, SSL_CB_CONNECT_LOOP, 1);
  515. s->state = new_state;
  516. }
  517. }
  518. skip = 0;
  519. }
  520. end:
  521. s->in_handshake--;
  522. BUF_MEM_free(buf);
  523. if (cb != NULL) {
  524. cb(s, SSL_CB_CONNECT_EXIT, ret);
  525. }
  526. return ret;
  527. }
  528. int ssl3_send_client_hello(SSL *s) {
  529. uint8_t *buf, *p, *d;
  530. int i;
  531. unsigned long l;
  532. buf = (uint8_t *)s->init_buf->data;
  533. if (s->state == SSL3_ST_CW_CLNT_HELLO_A) {
  534. if (!s->s3->have_version) {
  535. uint16_t max_version = ssl3_get_max_client_version(s);
  536. /* Disabling all versions is silly: return an error. */
  537. if (max_version == 0) {
  538. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
  539. goto err;
  540. }
  541. s->version = max_version;
  542. s->client_version = max_version;
  543. }
  544. /* If the configured session was created at a version higher than our
  545. * maximum version, drop it. */
  546. if (s->session &&
  547. (s->session->session_id_length == 0 || s->session->not_resumable ||
  548. (!SSL_IS_DTLS(s) && s->session->ssl_version > s->version) ||
  549. (SSL_IS_DTLS(s) && s->session->ssl_version < s->version))) {
  550. SSL_set_session(s, NULL);
  551. }
  552. /* else use the pre-loaded session */
  553. p = s->s3->client_random;
  554. /* If resending the ClientHello in DTLS after a HelloVerifyRequest, don't
  555. * renegerate the client_random. The random must be reused. */
  556. if ((!SSL_IS_DTLS(s) || !s->d1->send_cookie) &&
  557. !ssl_fill_hello_random(p, sizeof(s->s3->client_random),
  558. 0 /* client */)) {
  559. goto err;
  560. }
  561. /* Do the message type and length last. Note: the final argument to
  562. * ssl_add_clienthello_tlsext below depends on the size of this prefix. */
  563. d = p = ssl_handshake_start(s);
  564. /* version indicates the negotiated version: for example from an SSLv2/v3
  565. * compatible client hello). The client_version field is the maximum
  566. * version we permit and it is also used in RSA encrypted premaster
  567. * secrets. Some servers can choke if we initially report a higher version
  568. * then renegotiate to a lower one in the premaster secret. This didn't
  569. * happen with TLS 1.0 as most servers supported it but it can with TLS 1.1
  570. * or later if the server only supports 1.0.
  571. *
  572. * Possible scenario with previous logic:
  573. * 1. Client hello indicates TLS 1.2
  574. * 2. Server hello says TLS 1.0
  575. * 3. RSA encrypted premaster secret uses 1.2.
  576. * 4. Handhaked proceeds using TLS 1.0.
  577. * 5. Server sends hello request to renegotiate.
  578. * 6. Client hello indicates TLS v1.0 as we now
  579. * know that is maximum server supports.
  580. * 7. Server chokes on RSA encrypted premaster secret
  581. * containing version 1.0.
  582. *
  583. * For interoperability it should be OK to always use the maximum version
  584. * we support in client hello and then rely on the checking of version to
  585. * ensure the servers isn't being inconsistent: for example initially
  586. * negotiating with TLS 1.0 and renegotiating with TLS 1.2. We do this by
  587. * using client_version in client hello and not resetting it to the
  588. * negotiated version. */
  589. *(p++) = s->client_version >> 8;
  590. *(p++) = s->client_version & 0xff;
  591. /* Random stuff */
  592. memcpy(p, s->s3->client_random, SSL3_RANDOM_SIZE);
  593. p += SSL3_RANDOM_SIZE;
  594. /* Session ID */
  595. if (s->s3->initial_handshake_complete || s->session == NULL) {
  596. /* Renegotiations do not participate in session resumption. */
  597. i = 0;
  598. } else {
  599. i = s->session->session_id_length;
  600. }
  601. *(p++) = i;
  602. if (i != 0) {
  603. if (i > (int)sizeof(s->session->session_id)) {
  604. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  605. goto err;
  606. }
  607. memcpy(p, s->session->session_id, i);
  608. p += i;
  609. }
  610. /* cookie stuff for DTLS */
  611. if (SSL_IS_DTLS(s)) {
  612. if (s->d1->cookie_len > sizeof(s->d1->cookie)) {
  613. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  614. goto err;
  615. }
  616. *(p++) = s->d1->cookie_len;
  617. memcpy(p, s->d1->cookie, s->d1->cookie_len);
  618. p += s->d1->cookie_len;
  619. }
  620. /* Ciphers supported */
  621. i = ssl_cipher_list_to_bytes(s, SSL_get_ciphers(s), &p[2]);
  622. if (i == 0) {
  623. OPENSSL_PUT_ERROR(SSL, SSL_R_NO_CIPHERS_AVAILABLE);
  624. goto err;
  625. }
  626. s2n(i, p);
  627. p += i;
  628. /* COMPRESSION */
  629. *(p++) = 1;
  630. *(p++) = 0; /* Add the NULL method */
  631. /* TLS extensions*/
  632. p = ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
  633. p - buf);
  634. if (p == NULL) {
  635. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  636. goto err;
  637. }
  638. l = p - d;
  639. if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l)) {
  640. goto err;
  641. }
  642. s->state = SSL3_ST_CW_CLNT_HELLO_B;
  643. }
  644. /* SSL3_ST_CW_CLNT_HELLO_B */
  645. return ssl_do_write(s);
  646. err:
  647. return -1;
  648. }
  649. int ssl3_get_server_hello(SSL *s) {
  650. STACK_OF(SSL_CIPHER) *sk;
  651. const SSL_CIPHER *c;
  652. CERT *ct = s->cert;
  653. int al = SSL_AD_INTERNAL_ERROR, ok;
  654. long n;
  655. CBS server_hello, server_random, session_id;
  656. uint16_t server_version, cipher_suite;
  657. uint8_t compression_method;
  658. uint32_t mask_ssl;
  659. n = s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A,
  660. SSL3_ST_CR_SRVR_HELLO_B, SSL3_MT_SERVER_HELLO,
  661. 20000, /* ?? */
  662. ssl_hash_message, &ok);
  663. if (!ok) {
  664. uint32_t err = ERR_peek_error();
  665. if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
  666. ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
  667. /* Add a dedicated error code to the queue for a handshake_failure alert
  668. * in response to ClientHello. This matches NSS's client behavior and
  669. * gives a better error on a (probable) failure to negotiate initial
  670. * parameters. Note: this error code comes after the original one.
  671. *
  672. * See https://crbug.com/446505. */
  673. OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
  674. }
  675. return n;
  676. }
  677. CBS_init(&server_hello, s->init_msg, n);
  678. if (!CBS_get_u16(&server_hello, &server_version) ||
  679. !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
  680. !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
  681. CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
  682. !CBS_get_u16(&server_hello, &cipher_suite) ||
  683. !CBS_get_u8(&server_hello, &compression_method)) {
  684. al = SSL_AD_DECODE_ERROR;
  685. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  686. goto f_err;
  687. }
  688. assert(s->s3->have_version == s->s3->initial_handshake_complete);
  689. if (!s->s3->have_version) {
  690. if (!ssl3_is_version_enabled(s, server_version)) {
  691. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
  692. s->version = server_version;
  693. /* Mark the version as fixed so the record-layer version is not clamped
  694. * to TLS 1.0. */
  695. s->s3->have_version = 1;
  696. al = SSL_AD_PROTOCOL_VERSION;
  697. goto f_err;
  698. }
  699. s->version = server_version;
  700. s->enc_method = ssl3_get_enc_method(server_version);
  701. assert(s->enc_method != NULL);
  702. /* At this point, the connection's version is known and s->version is
  703. * fixed. Begin enforcing the record-layer version. */
  704. s->s3->have_version = 1;
  705. } else if (server_version != s->version) {
  706. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
  707. al = SSL_AD_PROTOCOL_VERSION;
  708. goto f_err;
  709. }
  710. /* Copy over the server random. */
  711. memcpy(s->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
  712. assert(s->session == NULL || s->session->session_id_length > 0);
  713. if (!s->s3->initial_handshake_complete && s->session != NULL &&
  714. CBS_mem_equal(&session_id, s->session->session_id,
  715. s->session->session_id_length)) {
  716. if (s->sid_ctx_length != s->session->sid_ctx_length ||
  717. memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
  718. /* actually a client application bug */
  719. al = SSL_AD_ILLEGAL_PARAMETER;
  720. OPENSSL_PUT_ERROR(SSL,
  721. SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
  722. goto f_err;
  723. }
  724. s->hit = 1;
  725. } else {
  726. /* The session wasn't resumed. Create a fresh SSL_SESSION to
  727. * fill out. */
  728. s->hit = 0;
  729. if (!ssl_get_new_session(s, 0)) {
  730. goto f_err;
  731. }
  732. /* Note: session_id could be empty. */
  733. s->session->session_id_length = CBS_len(&session_id);
  734. memcpy(s->session->session_id, CBS_data(&session_id), CBS_len(&session_id));
  735. }
  736. c = SSL_get_cipher_by_value(cipher_suite);
  737. if (c == NULL) {
  738. /* unknown cipher */
  739. al = SSL_AD_ILLEGAL_PARAMETER;
  740. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
  741. goto f_err;
  742. }
  743. /* ct->mask_ssl was computed from client capabilities. Now
  744. * that the final version is known, compute a new mask_ssl. */
  745. if (!SSL_USE_TLS1_2_CIPHERS(s)) {
  746. mask_ssl = SSL_TLSV1_2;
  747. } else {
  748. mask_ssl = 0;
  749. }
  750. /* If the cipher is disabled then we didn't sent it in the ClientHello, so if
  751. * the server selected it, it's an error. */
  752. if ((c->algorithm_ssl & mask_ssl) ||
  753. (c->algorithm_mkey & ct->mask_k) ||
  754. (c->algorithm_auth & ct->mask_a)) {
  755. al = SSL_AD_ILLEGAL_PARAMETER;
  756. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
  757. goto f_err;
  758. }
  759. sk = ssl_get_ciphers_by_id(s);
  760. if (!sk_SSL_CIPHER_find(sk, NULL, c)) {
  761. /* we did not say we would use this cipher */
  762. al = SSL_AD_ILLEGAL_PARAMETER;
  763. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
  764. goto f_err;
  765. }
  766. if (s->hit) {
  767. if (s->session->cipher != c) {
  768. al = SSL_AD_ILLEGAL_PARAMETER;
  769. OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
  770. goto f_err;
  771. }
  772. if (s->session->ssl_version != s->version) {
  773. al = SSL_AD_ILLEGAL_PARAMETER;
  774. OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
  775. goto f_err;
  776. }
  777. }
  778. s->s3->tmp.new_cipher = c;
  779. /* Now that the cipher is known, initialize the handshake hash. */
  780. if (!ssl3_init_handshake_hash(s)) {
  781. goto f_err;
  782. }
  783. /* If doing a full handshake with TLS 1.2, the server may request a client
  784. * certificate which requires hashing the handshake transcript under a
  785. * different hash. Otherwise, the handshake buffer may be released. */
  786. if (!SSL_USE_SIGALGS(s) || s->hit) {
  787. ssl3_free_handshake_buffer(s);
  788. }
  789. /* Only the NULL compression algorithm is supported. */
  790. if (compression_method != 0) {
  791. al = SSL_AD_ILLEGAL_PARAMETER;
  792. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
  793. goto f_err;
  794. }
  795. /* TLS extensions */
  796. if (!ssl_parse_serverhello_tlsext(s, &server_hello)) {
  797. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  798. goto err;
  799. }
  800. /* There should be nothing left over in the record. */
  801. if (CBS_len(&server_hello) != 0) {
  802. /* wrong packet length */
  803. al = SSL_AD_DECODE_ERROR;
  804. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
  805. goto f_err;
  806. }
  807. if (s->hit &&
  808. s->s3->tmp.extended_master_secret != s->session->extended_master_secret) {
  809. al = SSL_AD_HANDSHAKE_FAILURE;
  810. if (s->session->extended_master_secret) {
  811. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
  812. } else {
  813. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
  814. }
  815. goto f_err;
  816. }
  817. return 1;
  818. f_err:
  819. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  820. err:
  821. return -1;
  822. }
  823. /* ssl3_check_certificate_for_cipher returns one if |leaf| is a suitable server
  824. * certificate type for |cipher|. Otherwise, it returns zero and pushes an error
  825. * on the error queue. */
  826. static int ssl3_check_certificate_for_cipher(X509 *leaf,
  827. const SSL_CIPHER *cipher) {
  828. int ret = 0;
  829. EVP_PKEY *pkey = X509_get_pubkey(leaf);
  830. if (pkey == NULL) {
  831. goto err;
  832. }
  833. /* Check the certificate's type matches the cipher. */
  834. int expected_type = ssl_cipher_get_key_type(cipher);
  835. assert(expected_type != EVP_PKEY_NONE);
  836. if (pkey->type != expected_type) {
  837. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CERTIFICATE_TYPE);
  838. goto err;
  839. }
  840. /* TODO(davidben): This behavior is preserved from upstream. Should key usages
  841. * be checked in other cases as well? */
  842. if (cipher->algorithm_auth & SSL_aECDSA) {
  843. /* This call populates the ex_flags field correctly */
  844. X509_check_purpose(leaf, -1, 0);
  845. if ((leaf->ex_flags & EXFLAG_KUSAGE) &&
  846. !(leaf->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE)) {
  847. OPENSSL_PUT_ERROR(SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
  848. goto err;
  849. }
  850. }
  851. ret = 1;
  852. err:
  853. EVP_PKEY_free(pkey);
  854. return ret;
  855. }
  856. int ssl3_get_server_certificate(SSL *s) {
  857. int al, ok, ret = -1;
  858. unsigned long n;
  859. X509 *x = NULL;
  860. STACK_OF(X509) *sk = NULL;
  861. EVP_PKEY *pkey = NULL;
  862. CBS cbs, certificate_list;
  863. const uint8_t *data;
  864. n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B,
  865. SSL3_MT_CERTIFICATE, (long)s->max_cert_list,
  866. ssl_hash_message, &ok);
  867. if (!ok) {
  868. return n;
  869. }
  870. CBS_init(&cbs, s->init_msg, n);
  871. sk = sk_X509_new_null();
  872. if (sk == NULL) {
  873. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  874. goto err;
  875. }
  876. if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
  877. CBS_len(&certificate_list) == 0 ||
  878. CBS_len(&cbs) != 0) {
  879. al = SSL_AD_DECODE_ERROR;
  880. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  881. goto f_err;
  882. }
  883. while (CBS_len(&certificate_list) > 0) {
  884. CBS certificate;
  885. if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
  886. al = SSL_AD_DECODE_ERROR;
  887. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  888. goto f_err;
  889. }
  890. data = CBS_data(&certificate);
  891. x = d2i_X509(NULL, &data, CBS_len(&certificate));
  892. if (x == NULL) {
  893. al = SSL_AD_BAD_CERTIFICATE;
  894. OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
  895. goto f_err;
  896. }
  897. if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
  898. al = SSL_AD_DECODE_ERROR;
  899. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  900. goto f_err;
  901. }
  902. if (!sk_X509_push(sk, x)) {
  903. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  904. goto err;
  905. }
  906. x = NULL;
  907. }
  908. X509 *leaf = sk_X509_value(sk, 0);
  909. if (!ssl3_check_certificate_for_cipher(leaf, s->s3->tmp.new_cipher)) {
  910. al = SSL_AD_ILLEGAL_PARAMETER;
  911. goto f_err;
  912. }
  913. /* NOTE: Unlike the server half, the client's copy of |cert_chain| includes
  914. * the leaf. */
  915. sk_X509_pop_free(s->session->cert_chain, X509_free);
  916. s->session->cert_chain = sk;
  917. sk = NULL;
  918. X509_free(s->session->peer);
  919. s->session->peer = X509_up_ref(leaf);
  920. s->session->verify_result = s->verify_result;
  921. ret = 1;
  922. if (0) {
  923. f_err:
  924. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  925. }
  926. err:
  927. EVP_PKEY_free(pkey);
  928. X509_free(x);
  929. sk_X509_pop_free(sk, X509_free);
  930. return ret;
  931. }
  932. int ssl3_get_server_key_exchange(SSL *s) {
  933. EVP_MD_CTX md_ctx;
  934. int al, ok;
  935. long n, alg_k, alg_a;
  936. EVP_PKEY *pkey = NULL;
  937. const EVP_MD *md = NULL;
  938. RSA *rsa = NULL;
  939. DH *dh = NULL;
  940. EC_KEY *ecdh = NULL;
  941. BN_CTX *bn_ctx = NULL;
  942. EC_POINT *srvr_ecpoint = NULL;
  943. CBS server_key_exchange, server_key_exchange_orig, parameter;
  944. /* use same message size as in ssl3_get_certificate_request() as
  945. * ServerKeyExchange message may be skipped */
  946. n = s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
  947. SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list,
  948. ssl_hash_message, &ok);
  949. if (!ok) {
  950. return n;
  951. }
  952. if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
  953. if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher)) {
  954. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  955. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  956. return -1;
  957. }
  958. /* In plain PSK ciphersuite, ServerKeyExchange may be omitted to send no
  959. * identity hint. */
  960. if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK) {
  961. /* TODO(davidben): This should be reset in one place with the rest of the
  962. * handshake state. */
  963. OPENSSL_free(s->s3->tmp.peer_psk_identity_hint);
  964. s->s3->tmp.peer_psk_identity_hint = NULL;
  965. }
  966. s->s3->tmp.reuse_message = 1;
  967. return 1;
  968. }
  969. /* Retain a copy of the original CBS to compute the signature over. */
  970. CBS_init(&server_key_exchange, s->init_msg, n);
  971. server_key_exchange_orig = server_key_exchange;
  972. alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
  973. alg_a = s->s3->tmp.new_cipher->algorithm_auth;
  974. EVP_MD_CTX_init(&md_ctx);
  975. if (alg_a & SSL_aPSK) {
  976. CBS psk_identity_hint;
  977. /* Each of the PSK key exchanges begins with a psk_identity_hint. */
  978. if (!CBS_get_u16_length_prefixed(&server_key_exchange,
  979. &psk_identity_hint)) {
  980. al = SSL_AD_DECODE_ERROR;
  981. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  982. goto f_err;
  983. }
  984. /* Store PSK identity hint for later use, hint is used in
  985. * ssl3_send_client_key_exchange. Assume that the maximum length of a PSK
  986. * identity hint can be as long as the maximum length of a PSK identity.
  987. * Also do not allow NULL characters; identities are saved as C strings.
  988. *
  989. * TODO(davidben): Should invalid hints be ignored? It's a hint rather than
  990. * a specific identity. */
  991. if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
  992. CBS_contains_zero_byte(&psk_identity_hint)) {
  993. al = SSL_AD_HANDSHAKE_FAILURE;
  994. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  995. goto f_err;
  996. }
  997. /* Save the identity hint as a C string. */
  998. if (!CBS_strdup(&psk_identity_hint, &s->s3->tmp.peer_psk_identity_hint)) {
  999. al = SSL_AD_INTERNAL_ERROR;
  1000. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1001. goto f_err;
  1002. }
  1003. }
  1004. if (alg_k & SSL_kDHE) {
  1005. CBS dh_p, dh_g, dh_Ys;
  1006. if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
  1007. CBS_len(&dh_p) == 0 ||
  1008. !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
  1009. CBS_len(&dh_g) == 0 ||
  1010. !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
  1011. CBS_len(&dh_Ys) == 0) {
  1012. al = SSL_AD_DECODE_ERROR;
  1013. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1014. goto f_err;
  1015. }
  1016. dh = DH_new();
  1017. if (dh == NULL) {
  1018. OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
  1019. goto err;
  1020. }
  1021. if ((dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL)) == NULL ||
  1022. (dh->g = BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL)) == NULL ||
  1023. (dh->pub_key = BN_bin2bn(CBS_data(&dh_Ys), CBS_len(&dh_Ys), NULL)) ==
  1024. NULL) {
  1025. OPENSSL_PUT_ERROR(SSL, ERR_R_BN_LIB);
  1026. goto err;
  1027. }
  1028. s->session->key_exchange_info = DH_num_bits(dh);
  1029. if (s->session->key_exchange_info < 1024) {
  1030. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_DH_P_LENGTH);
  1031. goto err;
  1032. }
  1033. DH_free(s->s3->tmp.peer_dh_tmp);
  1034. s->s3->tmp.peer_dh_tmp = dh;
  1035. dh = NULL;
  1036. } else if (alg_k & SSL_kECDHE) {
  1037. uint16_t curve_id;
  1038. int curve_nid = 0;
  1039. const EC_GROUP *group;
  1040. CBS point;
  1041. /* Extract elliptic curve parameters and the server's ephemeral ECDH public
  1042. * key. Check curve is one of our preferences, if not server has sent an
  1043. * invalid curve. */
  1044. if (!tls1_check_curve(s, &server_key_exchange, &curve_id)) {
  1045. al = SSL_AD_DECODE_ERROR;
  1046. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
  1047. goto f_err;
  1048. }
  1049. curve_nid = tls1_ec_curve_id2nid(curve_id);
  1050. if (curve_nid == 0) {
  1051. al = SSL_AD_INTERNAL_ERROR;
  1052. OPENSSL_PUT_ERROR(SSL, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
  1053. goto f_err;
  1054. }
  1055. ecdh = EC_KEY_new_by_curve_name(curve_nid);
  1056. s->session->key_exchange_info = curve_id;
  1057. if (ecdh == NULL) {
  1058. OPENSSL_PUT_ERROR(SSL, ERR_R_EC_LIB);
  1059. goto err;
  1060. }
  1061. group = EC_KEY_get0_group(ecdh);
  1062. /* Next, get the encoded ECPoint */
  1063. if (!CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
  1064. al = SSL_AD_DECODE_ERROR;
  1065. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1066. goto f_err;
  1067. }
  1068. if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
  1069. ((bn_ctx = BN_CTX_new()) == NULL)) {
  1070. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1071. goto err;
  1072. }
  1073. if (!EC_POINT_oct2point(group, srvr_ecpoint, CBS_data(&point),
  1074. CBS_len(&point), bn_ctx)) {
  1075. al = SSL_AD_DECODE_ERROR;
  1076. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT);
  1077. goto f_err;
  1078. }
  1079. EC_KEY_set_public_key(ecdh, srvr_ecpoint);
  1080. EC_KEY_free(s->s3->tmp.peer_ecdh_tmp);
  1081. s->s3->tmp.peer_ecdh_tmp = ecdh;
  1082. ecdh = NULL;
  1083. BN_CTX_free(bn_ctx);
  1084. bn_ctx = NULL;
  1085. EC_POINT_free(srvr_ecpoint);
  1086. srvr_ecpoint = NULL;
  1087. } else if (!(alg_k & SSL_kPSK)) {
  1088. al = SSL_AD_UNEXPECTED_MESSAGE;
  1089. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  1090. goto f_err;
  1091. }
  1092. /* At this point, |server_key_exchange| contains the signature, if any, while
  1093. * |server_key_exchange_orig| contains the entire message. From that, derive
  1094. * a CBS containing just the parameter. */
  1095. CBS_init(&parameter, CBS_data(&server_key_exchange_orig),
  1096. CBS_len(&server_key_exchange_orig) - CBS_len(&server_key_exchange));
  1097. /* ServerKeyExchange should be signed by the server's public key. */
  1098. if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
  1099. pkey = X509_get_pubkey(s->session->peer);
  1100. if (pkey == NULL) {
  1101. goto err;
  1102. }
  1103. if (SSL_USE_SIGALGS(s)) {
  1104. if (!tls12_check_peer_sigalg(&md, &al, s, &server_key_exchange, pkey)) {
  1105. goto f_err;
  1106. }
  1107. } else if (pkey->type == EVP_PKEY_RSA) {
  1108. md = EVP_md5_sha1();
  1109. } else {
  1110. md = EVP_sha1();
  1111. }
  1112. /* The last field in |server_key_exchange| is the signature. */
  1113. CBS signature;
  1114. if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
  1115. CBS_len(&server_key_exchange) != 0) {
  1116. al = SSL_AD_DECODE_ERROR;
  1117. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1118. goto f_err;
  1119. }
  1120. if (!EVP_DigestVerifyInit(&md_ctx, NULL, md, NULL, pkey) ||
  1121. !EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random,
  1122. SSL3_RANDOM_SIZE) ||
  1123. !EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random,
  1124. SSL3_RANDOM_SIZE) ||
  1125. !EVP_DigestVerifyUpdate(&md_ctx, CBS_data(&parameter),
  1126. CBS_len(&parameter)) ||
  1127. !EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
  1128. CBS_len(&signature))) {
  1129. /* bad signature */
  1130. al = SSL_AD_DECRYPT_ERROR;
  1131. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
  1132. goto f_err;
  1133. }
  1134. } else {
  1135. /* PSK ciphers are the only supported certificate-less ciphers. */
  1136. assert(alg_a == SSL_aPSK);
  1137. if (CBS_len(&server_key_exchange) > 0) {
  1138. al = SSL_AD_DECODE_ERROR;
  1139. OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
  1140. goto f_err;
  1141. }
  1142. }
  1143. EVP_PKEY_free(pkey);
  1144. EVP_MD_CTX_cleanup(&md_ctx);
  1145. return 1;
  1146. f_err:
  1147. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1148. err:
  1149. EVP_PKEY_free(pkey);
  1150. RSA_free(rsa);
  1151. DH_free(dh);
  1152. BN_CTX_free(bn_ctx);
  1153. EC_POINT_free(srvr_ecpoint);
  1154. EC_KEY_free(ecdh);
  1155. EVP_MD_CTX_cleanup(&md_ctx);
  1156. return -1;
  1157. }
  1158. static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b) {
  1159. return X509_NAME_cmp(*a, *b);
  1160. }
  1161. int ssl3_get_certificate_request(SSL *s) {
  1162. int ok, ret = 0;
  1163. unsigned long n;
  1164. X509_NAME *xn = NULL;
  1165. STACK_OF(X509_NAME) *ca_sk = NULL;
  1166. CBS cbs;
  1167. CBS certificate_types;
  1168. CBS certificate_authorities;
  1169. const uint8_t *data;
  1170. n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A,
  1171. SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list,
  1172. ssl_hash_message, &ok);
  1173. if (!ok) {
  1174. return n;
  1175. }
  1176. s->s3->tmp.cert_req = 0;
  1177. if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
  1178. s->s3->tmp.reuse_message = 1;
  1179. /* If we get here we don't need the handshake buffer as we won't be doing
  1180. * client auth. */
  1181. ssl3_free_handshake_buffer(s);
  1182. return 1;
  1183. }
  1184. if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
  1185. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  1186. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_MESSAGE_TYPE);
  1187. goto err;
  1188. }
  1189. CBS_init(&cbs, s->init_msg, n);
  1190. ca_sk = sk_X509_NAME_new(ca_dn_cmp);
  1191. if (ca_sk == NULL) {
  1192. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1193. goto err;
  1194. }
  1195. /* get the certificate types */
  1196. if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types)) {
  1197. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1198. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1199. goto err;
  1200. }
  1201. if (!CBS_stow(&certificate_types, &s->s3->tmp.certificate_types,
  1202. &s->s3->tmp.num_certificate_types)) {
  1203. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1204. goto err;
  1205. }
  1206. if (SSL_USE_SIGALGS(s)) {
  1207. CBS supported_signature_algorithms;
  1208. if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms) ||
  1209. !tls1_parse_peer_sigalgs(s, &supported_signature_algorithms)) {
  1210. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1211. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1212. goto err;
  1213. }
  1214. }
  1215. /* get the CA RDNs */
  1216. if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities)) {
  1217. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1218. OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
  1219. goto err;
  1220. }
  1221. while (CBS_len(&certificate_authorities) > 0) {
  1222. CBS distinguished_name;
  1223. if (!CBS_get_u16_length_prefixed(&certificate_authorities,
  1224. &distinguished_name)) {
  1225. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1226. OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_TOO_LONG);
  1227. goto err;
  1228. }
  1229. data = CBS_data(&distinguished_name);
  1230. xn = d2i_X509_NAME(NULL, &data, CBS_len(&distinguished_name));
  1231. if (xn == NULL) {
  1232. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1233. OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
  1234. goto err;
  1235. }
  1236. if (!CBS_skip(&distinguished_name, data - CBS_data(&distinguished_name))) {
  1237. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1238. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1239. goto err;
  1240. }
  1241. if (CBS_len(&distinguished_name) != 0) {
  1242. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1243. OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_LENGTH_MISMATCH);
  1244. goto err;
  1245. }
  1246. if (!sk_X509_NAME_push(ca_sk, xn)) {
  1247. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1248. goto err;
  1249. }
  1250. }
  1251. /* we should setup a certificate to return.... */
  1252. s->s3->tmp.cert_req = 1;
  1253. sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
  1254. s->s3->tmp.ca_names = ca_sk;
  1255. ca_sk = NULL;
  1256. ret = 1;
  1257. err:
  1258. sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
  1259. return ret;
  1260. }
  1261. int ssl3_get_new_session_ticket(SSL *s) {
  1262. int ok, al;
  1263. long n;
  1264. CBS new_session_ticket, ticket;
  1265. n = s->method->ssl_get_message(
  1266. s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B,
  1267. SSL3_MT_NEWSESSION_TICKET, 16384, ssl_hash_message, &ok);
  1268. if (!ok) {
  1269. return n;
  1270. }
  1271. if (s->hit) {
  1272. /* The server is sending a new ticket for an existing session. Sessions are
  1273. * immutable once established, so duplicate all but the ticket of the
  1274. * existing session. */
  1275. uint8_t *bytes;
  1276. size_t bytes_len;
  1277. if (!SSL_SESSION_to_bytes_for_ticket(s->session, &bytes, &bytes_len)) {
  1278. goto err;
  1279. }
  1280. SSL_SESSION *new_session = SSL_SESSION_from_bytes(bytes, bytes_len);
  1281. OPENSSL_free(bytes);
  1282. if (new_session == NULL) {
  1283. /* This should never happen. */
  1284. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1285. goto err;
  1286. }
  1287. SSL_SESSION_free(s->session);
  1288. s->session = new_session;
  1289. }
  1290. CBS_init(&new_session_ticket, s->init_msg, n);
  1291. if (!CBS_get_u32(&new_session_ticket,
  1292. &s->session->tlsext_tick_lifetime_hint) ||
  1293. !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
  1294. CBS_len(&new_session_ticket) != 0) {
  1295. al = SSL_AD_DECODE_ERROR;
  1296. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1297. goto f_err;
  1298. }
  1299. if (!CBS_stow(&ticket, &s->session->tlsext_tick,
  1300. &s->session->tlsext_ticklen)) {
  1301. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1302. goto err;
  1303. }
  1304. /* Generate a session ID for this session based on the session ticket. We use
  1305. * the session ID mechanism for detecting ticket resumption. This also fits in
  1306. * with assumptions elsewhere in OpenSSL.*/
  1307. if (!EVP_Digest(CBS_data(&ticket), CBS_len(&ticket), s->session->session_id,
  1308. &s->session->session_id_length, EVP_sha256(), NULL)) {
  1309. goto err;
  1310. }
  1311. return 1;
  1312. f_err:
  1313. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1314. err:
  1315. return -1;
  1316. }
  1317. int ssl3_get_cert_status(SSL *s) {
  1318. int ok, al;
  1319. long n;
  1320. CBS certificate_status, ocsp_response;
  1321. uint8_t status_type;
  1322. n = s->method->ssl_get_message(
  1323. s, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B,
  1324. -1, 16384, ssl_hash_message, &ok);
  1325. if (!ok) {
  1326. return n;
  1327. }
  1328. if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_STATUS) {
  1329. /* A server may send status_request in ServerHello and then change
  1330. * its mind about sending CertificateStatus. */
  1331. s->s3->tmp.reuse_message = 1;
  1332. return 1;
  1333. }
  1334. CBS_init(&certificate_status, s->init_msg, n);
  1335. if (!CBS_get_u8(&certificate_status, &status_type) ||
  1336. status_type != TLSEXT_STATUSTYPE_ocsp ||
  1337. !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
  1338. CBS_len(&ocsp_response) == 0 ||
  1339. CBS_len(&certificate_status) != 0) {
  1340. al = SSL_AD_DECODE_ERROR;
  1341. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1342. goto f_err;
  1343. }
  1344. if (!CBS_stow(&ocsp_response, &s->session->ocsp_response,
  1345. &s->session->ocsp_response_length)) {
  1346. al = SSL_AD_INTERNAL_ERROR;
  1347. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1348. goto f_err;
  1349. }
  1350. return 1;
  1351. f_err:
  1352. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1353. return -1;
  1354. }
  1355. int ssl3_get_server_done(SSL *s) {
  1356. int ok;
  1357. long n;
  1358. n = s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
  1359. SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
  1360. 30, /* should be very small, like 0 :-) */
  1361. ssl_hash_message, &ok);
  1362. if (!ok) {
  1363. return n;
  1364. }
  1365. if (n > 0) {
  1366. /* should contain no data */
  1367. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1368. OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
  1369. return -1;
  1370. }
  1371. return 1;
  1372. }
  1373. int ssl3_send_client_key_exchange(SSL *s) {
  1374. uint8_t *p;
  1375. int n = 0;
  1376. uint32_t alg_k;
  1377. uint32_t alg_a;
  1378. uint8_t *q;
  1379. EVP_PKEY *pkey = NULL;
  1380. EC_KEY *clnt_ecdh = NULL;
  1381. const EC_POINT *srvr_ecpoint = NULL;
  1382. EVP_PKEY *srvr_pub_pkey = NULL;
  1383. uint8_t *encodedPoint = NULL;
  1384. int encoded_pt_len = 0;
  1385. BN_CTX *bn_ctx = NULL;
  1386. unsigned int psk_len = 0;
  1387. uint8_t psk[PSK_MAX_PSK_LEN];
  1388. uint8_t *pms = NULL;
  1389. size_t pms_len = 0;
  1390. if (s->state == SSL3_ST_CW_KEY_EXCH_A) {
  1391. p = ssl_handshake_start(s);
  1392. alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
  1393. alg_a = s->s3->tmp.new_cipher->algorithm_auth;
  1394. /* If using a PSK key exchange, prepare the pre-shared key. */
  1395. if (alg_a & SSL_aPSK) {
  1396. char identity[PSK_MAX_IDENTITY_LEN + 1];
  1397. size_t identity_len;
  1398. if (s->psk_client_callback == NULL) {
  1399. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
  1400. goto err;
  1401. }
  1402. memset(identity, 0, sizeof(identity));
  1403. psk_len =
  1404. s->psk_client_callback(s, s->s3->tmp.peer_psk_identity_hint, identity,
  1405. sizeof(identity), psk, sizeof(psk));
  1406. if (psk_len > PSK_MAX_PSK_LEN) {
  1407. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1408. goto err;
  1409. } else if (psk_len == 0) {
  1410. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
  1411. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1412. goto err;
  1413. }
  1414. identity_len = OPENSSL_strnlen(identity, sizeof(identity));
  1415. if (identity_len > PSK_MAX_IDENTITY_LEN) {
  1416. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1417. goto err;
  1418. }
  1419. OPENSSL_free(s->session->psk_identity);
  1420. s->session->psk_identity = BUF_strdup(identity);
  1421. if (s->session->psk_identity == NULL) {
  1422. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1423. goto err;
  1424. }
  1425. /* Write out psk_identity. */
  1426. s2n(identity_len, p);
  1427. memcpy(p, identity, identity_len);
  1428. p += identity_len;
  1429. n = 2 + identity_len;
  1430. }
  1431. /* Depending on the key exchange method, compute |pms| and |pms_len|. */
  1432. if (alg_k & SSL_kRSA) {
  1433. RSA *rsa;
  1434. size_t enc_pms_len;
  1435. pms_len = SSL_MAX_MASTER_KEY_LENGTH;
  1436. pms = OPENSSL_malloc(pms_len);
  1437. if (pms == NULL) {
  1438. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1439. goto err;
  1440. }
  1441. pkey = X509_get_pubkey(s->session->peer);
  1442. if (pkey == NULL ||
  1443. pkey->type != EVP_PKEY_RSA ||
  1444. pkey->pkey.rsa == NULL) {
  1445. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1446. EVP_PKEY_free(pkey);
  1447. goto err;
  1448. }
  1449. s->session->key_exchange_info = EVP_PKEY_bits(pkey);
  1450. rsa = pkey->pkey.rsa;
  1451. EVP_PKEY_free(pkey);
  1452. pms[0] = s->client_version >> 8;
  1453. pms[1] = s->client_version & 0xff;
  1454. if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
  1455. goto err;
  1456. }
  1457. s->session->master_key_length = SSL_MAX_MASTER_KEY_LENGTH;
  1458. q = p;
  1459. /* In TLS and beyond, reserve space for the length prefix. */
  1460. if (s->version > SSL3_VERSION) {
  1461. p += 2;
  1462. n += 2;
  1463. }
  1464. if (!RSA_encrypt(rsa, &enc_pms_len, p, RSA_size(rsa), pms, pms_len,
  1465. RSA_PKCS1_PADDING)) {
  1466. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_RSA_ENCRYPT);
  1467. goto err;
  1468. }
  1469. n += enc_pms_len;
  1470. /* Log the premaster secret, if logging is enabled. */
  1471. if (!ssl_ctx_log_rsa_client_key_exchange(s->ctx, p, enc_pms_len, pms,
  1472. pms_len)) {
  1473. goto err;
  1474. }
  1475. /* Fill in the length prefix. */
  1476. if (s->version > SSL3_VERSION) {
  1477. s2n(enc_pms_len, q);
  1478. }
  1479. } else if (alg_k & SSL_kDHE) {
  1480. DH *dh_srvr, *dh_clnt;
  1481. int dh_len;
  1482. size_t pub_len;
  1483. if (s->s3->tmp.peer_dh_tmp == NULL) {
  1484. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1485. goto err;
  1486. }
  1487. dh_srvr = s->s3->tmp.peer_dh_tmp;
  1488. /* generate a new random key */
  1489. dh_clnt = DHparams_dup(dh_srvr);
  1490. if (dh_clnt == NULL) {
  1491. OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
  1492. goto err;
  1493. }
  1494. if (!DH_generate_key(dh_clnt)) {
  1495. OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
  1496. DH_free(dh_clnt);
  1497. goto err;
  1498. }
  1499. pms_len = DH_size(dh_clnt);
  1500. pms = OPENSSL_malloc(pms_len);
  1501. if (pms == NULL) {
  1502. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1503. DH_free(dh_clnt);
  1504. goto err;
  1505. }
  1506. dh_len = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
  1507. if (dh_len <= 0) {
  1508. OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
  1509. DH_free(dh_clnt);
  1510. goto err;
  1511. }
  1512. pms_len = dh_len;
  1513. /* send off the data */
  1514. pub_len = BN_num_bytes(dh_clnt->pub_key);
  1515. s2n(pub_len, p);
  1516. BN_bn2bin(dh_clnt->pub_key, p);
  1517. n += 2 + pub_len;
  1518. DH_free(dh_clnt);
  1519. } else if (alg_k & SSL_kECDHE) {
  1520. const EC_GROUP *srvr_group = NULL;
  1521. EC_KEY *tkey;
  1522. int field_size = 0, ecdh_len;
  1523. if (s->s3->tmp.peer_ecdh_tmp == NULL) {
  1524. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1525. goto err;
  1526. }
  1527. tkey = s->s3->tmp.peer_ecdh_tmp;
  1528. srvr_group = EC_KEY_get0_group(tkey);
  1529. srvr_ecpoint = EC_KEY_get0_public_key(tkey);
  1530. if (srvr_group == NULL || srvr_ecpoint == NULL) {
  1531. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1532. goto err;
  1533. }
  1534. clnt_ecdh = EC_KEY_new();
  1535. if (clnt_ecdh == NULL) {
  1536. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1537. goto err;
  1538. }
  1539. if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
  1540. OPENSSL_PUT_ERROR(SSL, ERR_R_EC_LIB);
  1541. goto err;
  1542. }
  1543. /* Generate a new ECDH key pair */
  1544. if (!EC_KEY_generate_key(clnt_ecdh)) {
  1545. OPENSSL_PUT_ERROR(SSL, ERR_R_ECDH_LIB);
  1546. goto err;
  1547. }
  1548. field_size = EC_GROUP_get_degree(srvr_group);
  1549. if (field_size <= 0) {
  1550. OPENSSL_PUT_ERROR(SSL, ERR_R_ECDH_LIB);
  1551. goto err;
  1552. }
  1553. pms_len = (field_size + 7) / 8;
  1554. pms = OPENSSL_malloc(pms_len);
  1555. if (pms == NULL) {
  1556. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1557. goto err;
  1558. }
  1559. ecdh_len = ECDH_compute_key(pms, pms_len, srvr_ecpoint, clnt_ecdh, NULL);
  1560. if (ecdh_len <= 0) {
  1561. OPENSSL_PUT_ERROR(SSL, ERR_R_ECDH_LIB);
  1562. goto err;
  1563. }
  1564. pms_len = ecdh_len;
  1565. /* First check the size of encoding and allocate memory accordingly. */
  1566. encoded_pt_len =
  1567. EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh),
  1568. POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
  1569. encodedPoint =
  1570. (uint8_t *)OPENSSL_malloc(encoded_pt_len * sizeof(uint8_t));
  1571. bn_ctx = BN_CTX_new();
  1572. if (encodedPoint == NULL || bn_ctx == NULL) {
  1573. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1574. goto err;
  1575. }
  1576. /* Encode the public key */
  1577. encoded_pt_len = EC_POINT_point2oct(
  1578. srvr_group, EC_KEY_get0_public_key(clnt_ecdh),
  1579. POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx);
  1580. *p = encoded_pt_len; /* length of encoded point */
  1581. /* Encoded point will be copied here */
  1582. p += 1;
  1583. n += 1;
  1584. /* copy the point */
  1585. memcpy(p, encodedPoint, encoded_pt_len);
  1586. /* increment n to account for length field */
  1587. n += encoded_pt_len;
  1588. /* Free allocated memory */
  1589. BN_CTX_free(bn_ctx);
  1590. bn_ctx = NULL;
  1591. OPENSSL_free(encodedPoint);
  1592. encodedPoint = NULL;
  1593. EC_KEY_free(clnt_ecdh);
  1594. clnt_ecdh = NULL;
  1595. EVP_PKEY_free(srvr_pub_pkey);
  1596. srvr_pub_pkey = NULL;
  1597. } else if (alg_k & SSL_kPSK) {
  1598. /* For plain PSK, other_secret is a block of 0s with the same length as
  1599. * the pre-shared key. */
  1600. pms_len = psk_len;
  1601. pms = OPENSSL_malloc(pms_len);
  1602. if (pms == NULL) {
  1603. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1604. goto err;
  1605. }
  1606. memset(pms, 0, pms_len);
  1607. } else {
  1608. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1609. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1610. goto err;
  1611. }
  1612. /* For a PSK cipher suite, other_secret is combined with the pre-shared
  1613. * key. */
  1614. if (alg_a & SSL_aPSK) {
  1615. CBB cbb, child;
  1616. uint8_t *new_pms;
  1617. size_t new_pms_len;
  1618. CBB_zero(&cbb);
  1619. if (!CBB_init(&cbb, 2 + psk_len + 2 + pms_len) ||
  1620. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1621. !CBB_add_bytes(&child, pms, pms_len) ||
  1622. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1623. !CBB_add_bytes(&child, psk, psk_len) ||
  1624. !CBB_finish(&cbb, &new_pms, &new_pms_len)) {
  1625. CBB_cleanup(&cbb);
  1626. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1627. goto err;
  1628. }
  1629. OPENSSL_cleanse(pms, pms_len);
  1630. OPENSSL_free(pms);
  1631. pms = new_pms;
  1632. pms_len = new_pms_len;
  1633. }
  1634. /* The message must be added to the finished hash before calculating the
  1635. * master secret. */
  1636. if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
  1637. goto err;
  1638. }
  1639. s->state = SSL3_ST_CW_KEY_EXCH_B;
  1640. s->session->master_key_length = s->enc_method->generate_master_secret(
  1641. s, s->session->master_key, pms, pms_len);
  1642. if (s->session->master_key_length == 0) {
  1643. goto err;
  1644. }
  1645. s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
  1646. OPENSSL_cleanse(pms, pms_len);
  1647. OPENSSL_free(pms);
  1648. }
  1649. /* SSL3_ST_CW_KEY_EXCH_B */
  1650. return s->method->do_write(s);
  1651. err:
  1652. BN_CTX_free(bn_ctx);
  1653. OPENSSL_free(encodedPoint);
  1654. EC_KEY_free(clnt_ecdh);
  1655. EVP_PKEY_free(srvr_pub_pkey);
  1656. if (pms) {
  1657. OPENSSL_cleanse(pms, pms_len);
  1658. OPENSSL_free(pms);
  1659. }
  1660. return -1;
  1661. }
  1662. int ssl3_send_cert_verify(SSL *s) {
  1663. if (s->state == SSL3_ST_CW_CERT_VRFY_A ||
  1664. s->state == SSL3_ST_CW_CERT_VRFY_B) {
  1665. enum ssl_private_key_result_t sign_result;
  1666. uint8_t *p = ssl_handshake_start(s);
  1667. size_t signature_length = 0;
  1668. unsigned long n = 0;
  1669. assert(ssl_has_private_key(s));
  1670. if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
  1671. uint8_t *buf = (uint8_t *)s->init_buf->data;
  1672. const EVP_MD *md = NULL;
  1673. uint8_t digest[EVP_MAX_MD_SIZE];
  1674. size_t digest_length;
  1675. /* Write out the digest type if need be. */
  1676. if (SSL_USE_SIGALGS(s)) {
  1677. md = tls1_choose_signing_digest(s);
  1678. if (!tls12_get_sigandhash(s, p, md)) {
  1679. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1680. return -1;
  1681. }
  1682. p += 2;
  1683. n += 2;
  1684. }
  1685. /* Compute the digest. */
  1686. const int pkey_type = ssl_private_key_type(s);
  1687. if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey_type)) {
  1688. return -1;
  1689. }
  1690. /* The handshake buffer is no longer necessary. */
  1691. ssl3_free_handshake_buffer(s);
  1692. /* Sign the digest. */
  1693. signature_length = ssl_private_key_max_signature_len(s);
  1694. if (p + 2 + signature_length > buf + SSL3_RT_MAX_PLAIN_LENGTH) {
  1695. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  1696. return -1;
  1697. }
  1698. s->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1699. sign_result = ssl_private_key_sign(s, &p[2], &signature_length,
  1700. signature_length, md, digest,
  1701. digest_length);
  1702. } else {
  1703. if (SSL_USE_SIGALGS(s)) {
  1704. /* The digest has already been selected and written. */
  1705. p += 2;
  1706. n += 2;
  1707. }
  1708. signature_length = ssl_private_key_max_signature_len(s);
  1709. s->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1710. sign_result = ssl_private_key_sign_complete(s, &p[2], &signature_length,
  1711. signature_length);
  1712. }
  1713. if (sign_result == ssl_private_key_retry) {
  1714. s->state = SSL3_ST_CW_CERT_VRFY_B;
  1715. return -1;
  1716. }
  1717. s->rwstate = SSL_NOTHING;
  1718. if (sign_result != ssl_private_key_success) {
  1719. return -1;
  1720. }
  1721. s2n(signature_length, p);
  1722. n += signature_length + 2;
  1723. if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
  1724. return -1;
  1725. }
  1726. s->state = SSL3_ST_CW_CERT_VRFY_C;
  1727. }
  1728. return ssl_do_write(s);
  1729. }
  1730. /* ssl3_has_client_certificate returns true if a client certificate is
  1731. * configured. */
  1732. static int ssl3_has_client_certificate(SSL *ssl) {
  1733. return ssl->cert && ssl->cert->x509 && ssl_has_private_key(ssl);
  1734. }
  1735. int ssl3_send_client_certificate(SSL *s) {
  1736. X509 *x509 = NULL;
  1737. EVP_PKEY *pkey = NULL;
  1738. int i;
  1739. if (s->state == SSL3_ST_CW_CERT_A) {
  1740. /* Let cert callback update client certificates if required */
  1741. if (s->cert->cert_cb) {
  1742. i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
  1743. if (i < 0) {
  1744. s->rwstate = SSL_X509_LOOKUP;
  1745. return -1;
  1746. }
  1747. if (i == 0) {
  1748. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1749. return 0;
  1750. }
  1751. s->rwstate = SSL_NOTHING;
  1752. }
  1753. if (ssl3_has_client_certificate(s)) {
  1754. s->state = SSL3_ST_CW_CERT_C;
  1755. } else {
  1756. s->state = SSL3_ST_CW_CERT_B;
  1757. }
  1758. }
  1759. /* We need to get a client cert */
  1760. if (s->state == SSL3_ST_CW_CERT_B) {
  1761. /* If we get an error, we need to:
  1762. * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
  1763. * We then get retried later */
  1764. i = ssl_do_client_cert_cb(s, &x509, &pkey);
  1765. if (i < 0) {
  1766. s->rwstate = SSL_X509_LOOKUP;
  1767. return -1;
  1768. }
  1769. s->rwstate = SSL_NOTHING;
  1770. if (i == 1 && pkey != NULL && x509 != NULL) {
  1771. s->state = SSL3_ST_CW_CERT_B;
  1772. if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey)) {
  1773. i = 0;
  1774. }
  1775. } else if (i == 1) {
  1776. i = 0;
  1777. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
  1778. }
  1779. X509_free(x509);
  1780. EVP_PKEY_free(pkey);
  1781. if (i && !ssl3_has_client_certificate(s)) {
  1782. i = 0;
  1783. }
  1784. if (i == 0) {
  1785. if (s->version == SSL3_VERSION) {
  1786. s->s3->tmp.cert_req = 0;
  1787. ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
  1788. return 1;
  1789. } else {
  1790. s->s3->tmp.cert_req = 2;
  1791. /* There is no client certificate, so the handshake buffer may be
  1792. * released. */
  1793. ssl3_free_handshake_buffer(s);
  1794. }
  1795. }
  1796. /* Ok, we have a cert */
  1797. s->state = SSL3_ST_CW_CERT_C;
  1798. }
  1799. if (s->state == SSL3_ST_CW_CERT_C) {
  1800. if (s->s3->tmp.cert_req == 2) {
  1801. /* Send an empty Certificate message. */
  1802. uint8_t *p = ssl_handshake_start(s);
  1803. l2n3(0, p);
  1804. if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE, 3)) {
  1805. return -1;
  1806. }
  1807. } else if (!ssl3_output_cert_chain(s)) {
  1808. return -1;
  1809. }
  1810. s->state = SSL3_ST_CW_CERT_D;
  1811. }
  1812. /* SSL3_ST_CW_CERT_D */
  1813. return ssl_do_write(s);
  1814. }
  1815. int ssl3_send_next_proto(SSL *s) {
  1816. unsigned int len, padding_len;
  1817. uint8_t *d, *p;
  1818. if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
  1819. len = s->next_proto_negotiated_len;
  1820. padding_len = 32 - ((len + 2) % 32);
  1821. d = p = ssl_handshake_start(s);
  1822. *(p++) = len;
  1823. memcpy(p, s->next_proto_negotiated, len);
  1824. p += len;
  1825. *(p++) = padding_len;
  1826. memset(p, 0, padding_len);
  1827. p += padding_len;
  1828. if (!ssl_set_handshake_header(s, SSL3_MT_NEXT_PROTO, p - d)) {
  1829. return -1;
  1830. }
  1831. s->state = SSL3_ST_CW_NEXT_PROTO_B;
  1832. }
  1833. return ssl_do_write(s);
  1834. }
  1835. int ssl3_send_channel_id(SSL *s) {
  1836. uint8_t *d;
  1837. int ret = -1, public_key_len;
  1838. EVP_MD_CTX md_ctx;
  1839. ECDSA_SIG *sig = NULL;
  1840. uint8_t *public_key = NULL, *derp, *der_sig = NULL;
  1841. if (s->state != SSL3_ST_CW_CHANNEL_ID_A) {
  1842. return ssl_do_write(s);
  1843. }
  1844. if (!s->tlsext_channel_id_private && s->ctx->channel_id_cb) {
  1845. EVP_PKEY *key = NULL;
  1846. s->ctx->channel_id_cb(s, &key);
  1847. if (key != NULL) {
  1848. s->tlsext_channel_id_private = key;
  1849. }
  1850. }
  1851. if (!s->tlsext_channel_id_private) {
  1852. s->rwstate = SSL_CHANNEL_ID_LOOKUP;
  1853. return -1;
  1854. }
  1855. s->rwstate = SSL_NOTHING;
  1856. if (EVP_PKEY_id(s->tlsext_channel_id_private) != EVP_PKEY_EC) {
  1857. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1858. return -1;
  1859. }
  1860. EC_KEY *ec_key = s->tlsext_channel_id_private->pkey.ec;
  1861. d = ssl_handshake_start(s);
  1862. s2n(TLSEXT_TYPE_channel_id, d);
  1863. s2n(TLSEXT_CHANNEL_ID_SIZE, d);
  1864. EVP_MD_CTX_init(&md_ctx);
  1865. public_key_len = i2o_ECPublicKey(ec_key, NULL);
  1866. if (public_key_len <= 0) {
  1867. OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY);
  1868. goto err;
  1869. }
  1870. /* i2o_ECPublicKey will produce an ANSI X9.62 public key which, for a
  1871. * P-256 key, is 0x04 (meaning uncompressed) followed by the x and y
  1872. * field elements as 32-byte, big-endian numbers. */
  1873. if (public_key_len != 65) {
  1874. OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_NOT_P256);
  1875. goto err;
  1876. }
  1877. public_key = OPENSSL_malloc(public_key_len);
  1878. if (!public_key) {
  1879. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1880. goto err;
  1881. }
  1882. derp = public_key;
  1883. i2o_ECPublicKey(ec_key, &derp);
  1884. uint8_t digest[EVP_MAX_MD_SIZE];
  1885. size_t digest_len;
  1886. if (!tls1_channel_id_hash(s, digest, &digest_len)) {
  1887. goto err;
  1888. }
  1889. sig = ECDSA_do_sign(digest, digest_len, ec_key);
  1890. if (sig == NULL) {
  1891. goto err;
  1892. }
  1893. /* The first byte of public_key will be 0x4, denoting an uncompressed key. */
  1894. memcpy(d, public_key + 1, 64);
  1895. d += 64;
  1896. if (!BN_bn2bin_padded(d, 32, sig->r) ||
  1897. !BN_bn2bin_padded(d + 32, 32, sig->s)) {
  1898. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1899. goto err;
  1900. }
  1901. if (!ssl_set_handshake_header(s, SSL3_MT_ENCRYPTED_EXTENSIONS,
  1902. 2 + 2 + TLSEXT_CHANNEL_ID_SIZE)) {
  1903. goto err;
  1904. }
  1905. s->state = SSL3_ST_CW_CHANNEL_ID_B;
  1906. ret = ssl_do_write(s);
  1907. err:
  1908. EVP_MD_CTX_cleanup(&md_ctx);
  1909. OPENSSL_free(public_key);
  1910. OPENSSL_free(der_sig);
  1911. ECDSA_SIG_free(sig);
  1912. return ret;
  1913. }
  1914. int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey) {
  1915. int i = 0;
  1916. if (s->ctx->client_cert_cb) {
  1917. i = s->ctx->client_cert_cb(s, px509, ppkey);
  1918. }
  1919. return i;
  1920. }
  1921. int ssl3_verify_server_cert(SSL *s) {
  1922. int ret = ssl_verify_cert_chain(s, s->session->cert_chain);
  1923. if (s->verify_mode != SSL_VERIFY_NONE && ret <= 0) {
  1924. int al = ssl_verify_alarm_type(s->verify_result);
  1925. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1926. OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
  1927. } else {
  1928. ret = 1;
  1929. ERR_clear_error(); /* but we keep s->verify_result */
  1930. }
  1931. return ret;
  1932. }