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.
 
 
 
 
 
 

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