You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2264 line
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. p = ssl_add_clienthello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
  624. p - buf);
  625. if (p == NULL) {
  626. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  627. goto err;
  628. }
  629. l = p - d;
  630. if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_HELLO, l)) {
  631. goto err;
  632. }
  633. s->state = SSL3_ST_CW_CLNT_HELLO_B;
  634. }
  635. /* SSL3_ST_CW_CLNT_HELLO_B */
  636. return ssl_do_write(s);
  637. err:
  638. return -1;
  639. }
  640. int ssl3_get_server_hello(SSL *s) {
  641. STACK_OF(SSL_CIPHER) *sk;
  642. const SSL_CIPHER *c;
  643. CERT *ct = s->cert;
  644. int al = SSL_AD_INTERNAL_ERROR, ok;
  645. long n;
  646. CBS server_hello, server_random, session_id;
  647. uint16_t server_version, cipher_suite;
  648. uint8_t compression_method;
  649. uint32_t mask_ssl;
  650. n = s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_HELLO_A,
  651. SSL3_ST_CR_SRVR_HELLO_B, SSL3_MT_SERVER_HELLO,
  652. 20000, /* ?? */
  653. ssl_hash_message, &ok);
  654. if (!ok) {
  655. uint32_t err = ERR_peek_error();
  656. if (ERR_GET_LIB(err) == ERR_LIB_SSL &&
  657. ERR_GET_REASON(err) == SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE) {
  658. /* Add a dedicated error code to the queue for a handshake_failure alert
  659. * in response to ClientHello. This matches NSS's client behavior and
  660. * gives a better error on a (probable) failure to negotiate initial
  661. * parameters. Note: this error code comes after the original one.
  662. *
  663. * See https://crbug.com/446505. */
  664. OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_FAILURE_ON_CLIENT_HELLO);
  665. }
  666. return n;
  667. }
  668. CBS_init(&server_hello, s->init_msg, n);
  669. if (!CBS_get_u16(&server_hello, &server_version) ||
  670. !CBS_get_bytes(&server_hello, &server_random, SSL3_RANDOM_SIZE) ||
  671. !CBS_get_u8_length_prefixed(&server_hello, &session_id) ||
  672. CBS_len(&session_id) > SSL3_SESSION_ID_SIZE ||
  673. !CBS_get_u16(&server_hello, &cipher_suite) ||
  674. !CBS_get_u8(&server_hello, &compression_method)) {
  675. al = SSL_AD_DECODE_ERROR;
  676. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  677. goto f_err;
  678. }
  679. assert(s->s3->have_version == s->s3->initial_handshake_complete);
  680. if (!s->s3->have_version) {
  681. if (!ssl3_is_version_enabled(s, server_version)) {
  682. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_PROTOCOL);
  683. s->version = server_version;
  684. /* Mark the version as fixed so the record-layer version is not clamped
  685. * to TLS 1.0. */
  686. s->s3->have_version = 1;
  687. al = SSL_AD_PROTOCOL_VERSION;
  688. goto f_err;
  689. }
  690. s->version = server_version;
  691. s->enc_method = ssl3_get_enc_method(server_version);
  692. assert(s->enc_method != NULL);
  693. /* At this point, the connection's version is known and s->version is
  694. * fixed. Begin enforcing the record-layer version. */
  695. s->s3->have_version = 1;
  696. } else if (server_version != s->version) {
  697. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
  698. al = SSL_AD_PROTOCOL_VERSION;
  699. goto f_err;
  700. }
  701. /* Copy over the server random. */
  702. memcpy(s->s3->server_random, CBS_data(&server_random), SSL3_RANDOM_SIZE);
  703. assert(s->session == NULL || s->session->session_id_length > 0);
  704. if (!s->s3->initial_handshake_complete && s->session != NULL &&
  705. CBS_mem_equal(&session_id, s->session->session_id,
  706. s->session->session_id_length)) {
  707. if (s->sid_ctx_length != s->session->sid_ctx_length ||
  708. memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
  709. /* actually a client application bug */
  710. al = SSL_AD_ILLEGAL_PARAMETER;
  711. OPENSSL_PUT_ERROR(SSL,
  712. SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
  713. goto f_err;
  714. }
  715. s->hit = 1;
  716. } else {
  717. /* The session wasn't resumed. Create a fresh SSL_SESSION to
  718. * fill out. */
  719. s->hit = 0;
  720. if (!ssl_get_new_session(s, 0)) {
  721. goto f_err;
  722. }
  723. /* Note: session_id could be empty. */
  724. s->session->session_id_length = CBS_len(&session_id);
  725. memcpy(s->session->session_id, CBS_data(&session_id), CBS_len(&session_id));
  726. }
  727. c = SSL_get_cipher_by_value(cipher_suite);
  728. if (c == NULL) {
  729. /* unknown cipher */
  730. al = SSL_AD_ILLEGAL_PARAMETER;
  731. OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CIPHER_RETURNED);
  732. goto f_err;
  733. }
  734. /* ct->mask_ssl was computed from client capabilities. Now
  735. * that the final version is known, compute a new mask_ssl. */
  736. if (!SSL_USE_TLS1_2_CIPHERS(s)) {
  737. mask_ssl = SSL_TLSV1_2;
  738. } else {
  739. mask_ssl = 0;
  740. }
  741. /* If the cipher is disabled then we didn't sent it in the ClientHello, so if
  742. * the server selected it, it's an error. */
  743. if ((c->algorithm_ssl & mask_ssl) ||
  744. (c->algorithm_mkey & ct->mask_k) ||
  745. (c->algorithm_auth & ct->mask_a)) {
  746. al = SSL_AD_ILLEGAL_PARAMETER;
  747. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
  748. goto f_err;
  749. }
  750. sk = ssl_get_ciphers_by_id(s);
  751. if (!sk_SSL_CIPHER_find(sk, NULL, c)) {
  752. /* we did not say we would use this cipher */
  753. al = SSL_AD_ILLEGAL_PARAMETER;
  754. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CIPHER_RETURNED);
  755. goto f_err;
  756. }
  757. if (s->hit) {
  758. if (s->session->cipher != c) {
  759. al = SSL_AD_ILLEGAL_PARAMETER;
  760. OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
  761. goto f_err;
  762. }
  763. if (s->session->ssl_version != s->version) {
  764. al = SSL_AD_ILLEGAL_PARAMETER;
  765. OPENSSL_PUT_ERROR(SSL, SSL_R_OLD_SESSION_VERSION_NOT_RETURNED);
  766. goto f_err;
  767. }
  768. }
  769. s->s3->tmp.new_cipher = c;
  770. /* If doing a full handshake with TLS 1.2, the server may request a client
  771. * certificate which requires hashing the handshake transcript under a
  772. * different hash. Otherwise, release the handshake buffer. */
  773. if ((!SSL_USE_SIGALGS(s) || s->hit) &&
  774. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  775. goto f_err;
  776. }
  777. /* Only the NULL compression algorithm is supported. */
  778. if (compression_method != 0) {
  779. al = SSL_AD_ILLEGAL_PARAMETER;
  780. OPENSSL_PUT_ERROR(SSL, SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
  781. goto f_err;
  782. }
  783. /* TLS extensions */
  784. if (!ssl_parse_serverhello_tlsext(s, &server_hello)) {
  785. OPENSSL_PUT_ERROR(SSL, SSL_R_PARSE_TLSEXT);
  786. goto err;
  787. }
  788. /* There should be nothing left over in the record. */
  789. if (CBS_len(&server_hello) != 0) {
  790. /* wrong packet length */
  791. al = SSL_AD_DECODE_ERROR;
  792. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_PACKET_LENGTH);
  793. goto f_err;
  794. }
  795. if (s->hit &&
  796. s->s3->tmp.extended_master_secret != s->session->extended_master_secret) {
  797. al = SSL_AD_HANDSHAKE_FAILURE;
  798. if (s->session->extended_master_secret) {
  799. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_EMS_SESSION_WITHOUT_EMS_EXTENSION);
  800. } else {
  801. OPENSSL_PUT_ERROR(SSL, SSL_R_RESUMED_NON_EMS_SESSION_WITH_EMS_EXTENSION);
  802. }
  803. goto f_err;
  804. }
  805. return 1;
  806. f_err:
  807. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  808. err:
  809. return -1;
  810. }
  811. /* ssl3_check_certificate_for_cipher returns one if |leaf| is a suitable server
  812. * certificate type for |cipher|. Otherwise, it returns zero and pushes an error
  813. * on the error queue. */
  814. static int ssl3_check_certificate_for_cipher(X509 *leaf,
  815. const SSL_CIPHER *cipher) {
  816. int ret = 0;
  817. EVP_PKEY *pkey = X509_get_pubkey(leaf);
  818. if (pkey == NULL) {
  819. goto err;
  820. }
  821. /* Check the certificate's type matches the cipher. */
  822. int expected_type = ssl_cipher_get_key_type(cipher);
  823. assert(expected_type != EVP_PKEY_NONE);
  824. if (pkey->type != expected_type) {
  825. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CERTIFICATE_TYPE);
  826. goto err;
  827. }
  828. /* TODO(davidben): This behavior is preserved from upstream. Should key usages
  829. * be checked in other cases as well? */
  830. if (cipher->algorithm_auth & SSL_aECDSA) {
  831. /* This call populates the ex_flags field correctly */
  832. X509_check_purpose(leaf, -1, 0);
  833. if ((leaf->ex_flags & EXFLAG_KUSAGE) &&
  834. !(leaf->ex_kusage & X509v3_KU_DIGITAL_SIGNATURE)) {
  835. OPENSSL_PUT_ERROR(SSL, SSL_R_ECC_CERT_NOT_FOR_SIGNING);
  836. goto err;
  837. }
  838. }
  839. ret = 1;
  840. err:
  841. EVP_PKEY_free(pkey);
  842. return ret;
  843. }
  844. int ssl3_get_server_certificate(SSL *s) {
  845. int al, i, ok, ret = -1;
  846. unsigned long n;
  847. X509 *x = NULL;
  848. STACK_OF(X509) *sk = NULL;
  849. SESS_CERT *sc;
  850. EVP_PKEY *pkey = NULL;
  851. CBS cbs, certificate_list;
  852. const uint8_t *data;
  853. n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_A, SSL3_ST_CR_CERT_B,
  854. SSL3_MT_CERTIFICATE, (long)s->max_cert_list,
  855. ssl_hash_message, &ok);
  856. if (!ok) {
  857. return n;
  858. }
  859. CBS_init(&cbs, s->init_msg, n);
  860. sk = sk_X509_new_null();
  861. if (sk == NULL) {
  862. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  863. goto err;
  864. }
  865. if (!CBS_get_u24_length_prefixed(&cbs, &certificate_list) ||
  866. CBS_len(&certificate_list) == 0 ||
  867. CBS_len(&cbs) != 0) {
  868. al = SSL_AD_DECODE_ERROR;
  869. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  870. goto f_err;
  871. }
  872. while (CBS_len(&certificate_list) > 0) {
  873. CBS certificate;
  874. if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate)) {
  875. al = SSL_AD_DECODE_ERROR;
  876. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  877. goto f_err;
  878. }
  879. data = CBS_data(&certificate);
  880. x = d2i_X509(NULL, &data, CBS_len(&certificate));
  881. if (x == NULL) {
  882. al = SSL_AD_BAD_CERTIFICATE;
  883. OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
  884. goto f_err;
  885. }
  886. if (data != CBS_data(&certificate) + CBS_len(&certificate)) {
  887. al = SSL_AD_DECODE_ERROR;
  888. OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
  889. goto f_err;
  890. }
  891. if (!sk_X509_push(sk, x)) {
  892. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  893. goto err;
  894. }
  895. x = NULL;
  896. }
  897. i = ssl_verify_cert_chain(s, sk);
  898. if (s->verify_mode != SSL_VERIFY_NONE && i <= 0) {
  899. al = ssl_verify_alarm_type(s->verify_result);
  900. OPENSSL_PUT_ERROR(SSL, SSL_R_CERTIFICATE_VERIFY_FAILED);
  901. goto f_err;
  902. }
  903. ERR_clear_error(); /* but we keep s->verify_result */
  904. X509 *leaf = sk_X509_value(sk, 0);
  905. if (!ssl3_check_certificate_for_cipher(leaf, s->s3->tmp.new_cipher)) {
  906. al = SSL_AD_ILLEGAL_PARAMETER;
  907. goto f_err;
  908. }
  909. sc = ssl_sess_cert_new();
  910. if (sc == NULL) {
  911. goto err;
  912. }
  913. ssl_sess_cert_free(s->session->sess_cert);
  914. s->session->sess_cert = sc;
  915. /* NOTE: Unlike the server half, the client's copy of |cert_chain| includes
  916. * the leaf. */
  917. sc->cert_chain = sk;
  918. sk = NULL;
  919. X509_free(sc->peer_cert);
  920. sc->peer_cert = X509_up_ref(leaf);
  921. X509_free(s->session->peer);
  922. s->session->peer = X509_up_ref(leaf);
  923. s->session->verify_result = s->verify_result;
  924. ret = 1;
  925. if (0) {
  926. f_err:
  927. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  928. }
  929. err:
  930. EVP_PKEY_free(pkey);
  931. X509_free(x);
  932. sk_X509_pop_free(sk, X509_free);
  933. return ret;
  934. }
  935. int ssl3_get_server_key_exchange(SSL *s) {
  936. EVP_MD_CTX md_ctx;
  937. int al, ok;
  938. long n, alg_k, alg_a;
  939. EVP_PKEY *pkey = NULL;
  940. const EVP_MD *md = NULL;
  941. RSA *rsa = NULL;
  942. DH *dh = NULL;
  943. EC_KEY *ecdh = NULL;
  944. BN_CTX *bn_ctx = NULL;
  945. EC_POINT *srvr_ecpoint = NULL;
  946. CBS server_key_exchange, server_key_exchange_orig, parameter;
  947. /* use same message size as in ssl3_get_certificate_request() as
  948. * ServerKeyExchange message may be skipped */
  949. n = s->method->ssl_get_message(s, SSL3_ST_CR_KEY_EXCH_A,
  950. SSL3_ST_CR_KEY_EXCH_B, -1, s->max_cert_list,
  951. ssl_hash_message, &ok);
  952. if (!ok) {
  953. return n;
  954. }
  955. if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE) {
  956. if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher)) {
  957. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  958. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  959. return -1;
  960. }
  961. /* In plain PSK ciphersuite, ServerKeyExchange can be
  962. omitted if no identity hint is sent. Set session->sess_cert anyway to
  963. avoid problems later.*/
  964. if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aPSK) {
  965. /* PSK ciphersuites that also send a Certificate would have already
  966. * initialized |sess_cert|. */
  967. if (s->session->sess_cert == NULL) {
  968. s->session->sess_cert = ssl_sess_cert_new();
  969. if (s->session->sess_cert == NULL) {
  970. return -1;
  971. }
  972. }
  973. /* TODO(davidben): This should be reset in one place with the rest of the
  974. * handshake state. */
  975. OPENSSL_free(s->s3->tmp.peer_psk_identity_hint);
  976. s->s3->tmp.peer_psk_identity_hint = NULL;
  977. }
  978. s->s3->tmp.reuse_message = 1;
  979. return 1;
  980. }
  981. /* Retain a copy of the original CBS to compute the signature over. */
  982. CBS_init(&server_key_exchange, s->init_msg, n);
  983. server_key_exchange_orig = server_key_exchange;
  984. if (s->session->sess_cert != NULL) {
  985. DH_free(s->session->sess_cert->peer_dh_tmp);
  986. s->session->sess_cert->peer_dh_tmp = NULL;
  987. EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
  988. s->session->sess_cert->peer_ecdh_tmp = NULL;
  989. } else {
  990. s->session->sess_cert = ssl_sess_cert_new();
  991. if (s->session->sess_cert == NULL) {
  992. return -1;
  993. }
  994. }
  995. alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
  996. alg_a = s->s3->tmp.new_cipher->algorithm_auth;
  997. EVP_MD_CTX_init(&md_ctx);
  998. if (alg_a & SSL_aPSK) {
  999. CBS psk_identity_hint;
  1000. /* Each of the PSK key exchanges begins with a psk_identity_hint. */
  1001. if (!CBS_get_u16_length_prefixed(&server_key_exchange,
  1002. &psk_identity_hint)) {
  1003. al = SSL_AD_DECODE_ERROR;
  1004. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1005. goto f_err;
  1006. }
  1007. /* Store PSK identity hint for later use, hint is used in
  1008. * ssl3_send_client_key_exchange. Assume that the maximum length of a PSK
  1009. * identity hint can be as long as the maximum length of a PSK identity.
  1010. * Also do not allow NULL characters; identities are saved as C strings.
  1011. *
  1012. * TODO(davidben): Should invalid hints be ignored? It's a hint rather than
  1013. * a specific identity. */
  1014. if (CBS_len(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN ||
  1015. CBS_contains_zero_byte(&psk_identity_hint)) {
  1016. al = SSL_AD_HANDSHAKE_FAILURE;
  1017. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  1018. goto f_err;
  1019. }
  1020. /* Save the identity hint as a C string. */
  1021. if (!CBS_strdup(&psk_identity_hint, &s->s3->tmp.peer_psk_identity_hint)) {
  1022. al = SSL_AD_INTERNAL_ERROR;
  1023. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1024. goto f_err;
  1025. }
  1026. }
  1027. if (alg_k & SSL_kDHE) {
  1028. CBS dh_p, dh_g, dh_Ys;
  1029. if (!CBS_get_u16_length_prefixed(&server_key_exchange, &dh_p) ||
  1030. CBS_len(&dh_p) == 0 ||
  1031. !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_g) ||
  1032. CBS_len(&dh_g) == 0 ||
  1033. !CBS_get_u16_length_prefixed(&server_key_exchange, &dh_Ys) ||
  1034. CBS_len(&dh_Ys) == 0) {
  1035. al = SSL_AD_DECODE_ERROR;
  1036. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1037. goto f_err;
  1038. }
  1039. dh = DH_new();
  1040. if (dh == NULL) {
  1041. OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
  1042. goto err;
  1043. }
  1044. if ((dh->p = BN_bin2bn(CBS_data(&dh_p), CBS_len(&dh_p), NULL)) == NULL ||
  1045. (dh->g = BN_bin2bn(CBS_data(&dh_g), CBS_len(&dh_g), NULL)) == NULL ||
  1046. (dh->pub_key = BN_bin2bn(CBS_data(&dh_Ys), CBS_len(&dh_Ys), NULL)) ==
  1047. NULL) {
  1048. OPENSSL_PUT_ERROR(SSL, ERR_R_BN_LIB);
  1049. goto err;
  1050. }
  1051. if (DH_num_bits(dh) < 1024) {
  1052. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_DH_P_LENGTH);
  1053. goto err;
  1054. }
  1055. s->session->sess_cert->peer_dh_tmp = dh;
  1056. dh = NULL;
  1057. } else if (alg_k & SSL_kECDHE) {
  1058. uint16_t curve_id;
  1059. int curve_nid = 0;
  1060. const EC_GROUP *group;
  1061. CBS point;
  1062. /* Extract elliptic curve parameters and the server's ephemeral ECDH public
  1063. * key. Check curve is one of our preferences, if not server has sent an
  1064. * invalid curve. */
  1065. if (!tls1_check_curve(s, &server_key_exchange, &curve_id)) {
  1066. al = SSL_AD_DECODE_ERROR;
  1067. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_CURVE);
  1068. goto f_err;
  1069. }
  1070. curve_nid = tls1_ec_curve_id2nid(curve_id);
  1071. if (curve_nid == 0) {
  1072. al = SSL_AD_INTERNAL_ERROR;
  1073. OPENSSL_PUT_ERROR(SSL, SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
  1074. goto f_err;
  1075. }
  1076. ecdh = EC_KEY_new_by_curve_name(curve_nid);
  1077. if (ecdh == NULL) {
  1078. OPENSSL_PUT_ERROR(SSL, ERR_R_EC_LIB);
  1079. goto err;
  1080. }
  1081. group = EC_KEY_get0_group(ecdh);
  1082. /* Next, get the encoded ECPoint */
  1083. if (!CBS_get_u8_length_prefixed(&server_key_exchange, &point)) {
  1084. al = SSL_AD_DECODE_ERROR;
  1085. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1086. goto f_err;
  1087. }
  1088. if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
  1089. ((bn_ctx = BN_CTX_new()) == NULL)) {
  1090. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1091. goto err;
  1092. }
  1093. if (!EC_POINT_oct2point(group, srvr_ecpoint, CBS_data(&point),
  1094. CBS_len(&point), bn_ctx)) {
  1095. al = SSL_AD_DECODE_ERROR;
  1096. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ECPOINT);
  1097. goto f_err;
  1098. }
  1099. EC_KEY_set_public_key(ecdh, srvr_ecpoint);
  1100. s->session->sess_cert->peer_ecdh_tmp = ecdh;
  1101. ecdh = NULL;
  1102. BN_CTX_free(bn_ctx);
  1103. bn_ctx = NULL;
  1104. EC_POINT_free(srvr_ecpoint);
  1105. srvr_ecpoint = NULL;
  1106. } else if (!(alg_k & SSL_kPSK)) {
  1107. al = SSL_AD_UNEXPECTED_MESSAGE;
  1108. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  1109. goto f_err;
  1110. }
  1111. /* At this point, |server_key_exchange| contains the signature, if any, while
  1112. * |server_key_exchange_orig| contains the entire message. From that, derive
  1113. * a CBS containing just the parameter. */
  1114. CBS_init(&parameter, CBS_data(&server_key_exchange_orig),
  1115. CBS_len(&server_key_exchange_orig) - CBS_len(&server_key_exchange));
  1116. /* ServerKeyExchange should be signed by the server's public key. */
  1117. if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher)) {
  1118. pkey = X509_get_pubkey(s->session->sess_cert->peer_cert);
  1119. if (pkey == NULL) {
  1120. goto err;
  1121. }
  1122. if (SSL_USE_SIGALGS(s)) {
  1123. if (!tls12_check_peer_sigalg(&md, &al, s, &server_key_exchange, pkey)) {
  1124. goto f_err;
  1125. }
  1126. } else if (pkey->type == EVP_PKEY_RSA) {
  1127. md = EVP_md5_sha1();
  1128. } else {
  1129. md = EVP_sha1();
  1130. }
  1131. /* The last field in |server_key_exchange| is the signature. */
  1132. CBS signature;
  1133. if (!CBS_get_u16_length_prefixed(&server_key_exchange, &signature) ||
  1134. CBS_len(&server_key_exchange) != 0) {
  1135. al = SSL_AD_DECODE_ERROR;
  1136. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1137. goto f_err;
  1138. }
  1139. if (!EVP_DigestVerifyInit(&md_ctx, NULL, md, NULL, pkey) ||
  1140. !EVP_DigestVerifyUpdate(&md_ctx, s->s3->client_random,
  1141. SSL3_RANDOM_SIZE) ||
  1142. !EVP_DigestVerifyUpdate(&md_ctx, s->s3->server_random,
  1143. SSL3_RANDOM_SIZE) ||
  1144. !EVP_DigestVerifyUpdate(&md_ctx, CBS_data(&parameter),
  1145. CBS_len(&parameter)) ||
  1146. !EVP_DigestVerifyFinal(&md_ctx, CBS_data(&signature),
  1147. CBS_len(&signature))) {
  1148. /* bad signature */
  1149. al = SSL_AD_DECRYPT_ERROR;
  1150. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
  1151. goto f_err;
  1152. }
  1153. } else {
  1154. /* PSK ciphers are the only supported certificate-less ciphers. */
  1155. assert(alg_a == SSL_aPSK);
  1156. if (CBS_len(&server_key_exchange) > 0) {
  1157. al = SSL_AD_DECODE_ERROR;
  1158. OPENSSL_PUT_ERROR(SSL, SSL_R_EXTRA_DATA_IN_MESSAGE);
  1159. goto f_err;
  1160. }
  1161. }
  1162. EVP_PKEY_free(pkey);
  1163. EVP_MD_CTX_cleanup(&md_ctx);
  1164. return 1;
  1165. f_err:
  1166. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1167. err:
  1168. EVP_PKEY_free(pkey);
  1169. RSA_free(rsa);
  1170. DH_free(dh);
  1171. BN_CTX_free(bn_ctx);
  1172. EC_POINT_free(srvr_ecpoint);
  1173. EC_KEY_free(ecdh);
  1174. EVP_MD_CTX_cleanup(&md_ctx);
  1175. return -1;
  1176. }
  1177. static int ca_dn_cmp(const X509_NAME **a, const X509_NAME **b) {
  1178. return X509_NAME_cmp(*a, *b);
  1179. }
  1180. int ssl3_get_certificate_request(SSL *s) {
  1181. int ok, ret = 0;
  1182. unsigned long n;
  1183. X509_NAME *xn = NULL;
  1184. STACK_OF(X509_NAME) *ca_sk = NULL;
  1185. CBS cbs;
  1186. CBS certificate_types;
  1187. CBS certificate_authorities;
  1188. const uint8_t *data;
  1189. n = s->method->ssl_get_message(s, SSL3_ST_CR_CERT_REQ_A,
  1190. SSL3_ST_CR_CERT_REQ_B, -1, s->max_cert_list,
  1191. ssl_hash_message, &ok);
  1192. if (!ok) {
  1193. return n;
  1194. }
  1195. s->s3->tmp.cert_req = 0;
  1196. if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE) {
  1197. s->s3->tmp.reuse_message = 1;
  1198. /* If we get here we don't need any cached handshake records as we wont be
  1199. * doing client auth. */
  1200. if (s->s3->handshake_buffer &&
  1201. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  1202. goto err;
  1203. }
  1204. return 1;
  1205. }
  1206. if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST) {
  1207. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  1208. OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_MESSAGE_TYPE);
  1209. goto err;
  1210. }
  1211. CBS_init(&cbs, s->init_msg, n);
  1212. ca_sk = sk_X509_NAME_new(ca_dn_cmp);
  1213. if (ca_sk == NULL) {
  1214. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1215. goto err;
  1216. }
  1217. /* get the certificate types */
  1218. if (!CBS_get_u8_length_prefixed(&cbs, &certificate_types)) {
  1219. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1220. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1221. goto err;
  1222. }
  1223. if (!CBS_stow(&certificate_types, &s->s3->tmp.certificate_types,
  1224. &s->s3->tmp.num_certificate_types)) {
  1225. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1226. goto err;
  1227. }
  1228. if (SSL_USE_SIGALGS(s)) {
  1229. CBS supported_signature_algorithms;
  1230. if (!CBS_get_u16_length_prefixed(&cbs, &supported_signature_algorithms)) {
  1231. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1232. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1233. goto err;
  1234. }
  1235. if (!tls1_process_sigalgs(s, &supported_signature_algorithms)) {
  1236. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1237. OPENSSL_PUT_ERROR(SSL, SSL_R_SIGNATURE_ALGORITHMS_ERROR);
  1238. goto err;
  1239. }
  1240. }
  1241. /* get the CA RDNs */
  1242. if (!CBS_get_u16_length_prefixed(&cbs, &certificate_authorities)) {
  1243. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1244. OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
  1245. goto err;
  1246. }
  1247. while (CBS_len(&certificate_authorities) > 0) {
  1248. CBS distinguished_name;
  1249. if (!CBS_get_u16_length_prefixed(&certificate_authorities,
  1250. &distinguished_name)) {
  1251. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1252. OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_TOO_LONG);
  1253. goto err;
  1254. }
  1255. data = CBS_data(&distinguished_name);
  1256. xn = d2i_X509_NAME(NULL, &data, CBS_len(&distinguished_name));
  1257. if (xn == NULL) {
  1258. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1259. OPENSSL_PUT_ERROR(SSL, ERR_R_ASN1_LIB);
  1260. goto err;
  1261. }
  1262. if (!CBS_skip(&distinguished_name, data - CBS_data(&distinguished_name))) {
  1263. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1264. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1265. goto err;
  1266. }
  1267. if (CBS_len(&distinguished_name) != 0) {
  1268. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1269. OPENSSL_PUT_ERROR(SSL, SSL_R_CA_DN_LENGTH_MISMATCH);
  1270. goto err;
  1271. }
  1272. if (!sk_X509_NAME_push(ca_sk, xn)) {
  1273. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1274. goto err;
  1275. }
  1276. }
  1277. /* we should setup a certificate to return.... */
  1278. s->s3->tmp.cert_req = 1;
  1279. sk_X509_NAME_pop_free(s->s3->tmp.ca_names, X509_NAME_free);
  1280. s->s3->tmp.ca_names = ca_sk;
  1281. ca_sk = NULL;
  1282. ret = 1;
  1283. err:
  1284. sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
  1285. return ret;
  1286. }
  1287. int ssl3_get_new_session_ticket(SSL *s) {
  1288. int ok, al;
  1289. long n;
  1290. CBS new_session_ticket, ticket;
  1291. n = s->method->ssl_get_message(
  1292. s, SSL3_ST_CR_SESSION_TICKET_A, SSL3_ST_CR_SESSION_TICKET_B,
  1293. SSL3_MT_NEWSESSION_TICKET, 16384, ssl_hash_message, &ok);
  1294. if (!ok) {
  1295. return n;
  1296. }
  1297. if (s->hit) {
  1298. /* The server is sending a new ticket for an existing session. Sessions are
  1299. * immutable once established, so duplicate all but the ticket of the
  1300. * existing session. */
  1301. uint8_t *bytes;
  1302. size_t bytes_len;
  1303. if (!SSL_SESSION_to_bytes_for_ticket(s->session, &bytes, &bytes_len)) {
  1304. goto err;
  1305. }
  1306. SSL_SESSION *new_session = SSL_SESSION_from_bytes(bytes, bytes_len);
  1307. OPENSSL_free(bytes);
  1308. if (new_session == NULL) {
  1309. /* This should never happen. */
  1310. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1311. goto err;
  1312. }
  1313. if (s->session->sess_cert != NULL) {
  1314. /* |sess_cert| is not serialized and must be duplicated explicitly. */
  1315. assert(new_session->sess_cert == NULL);
  1316. new_session->sess_cert = ssl_sess_cert_dup(s->session->sess_cert);
  1317. if (new_session->sess_cert == NULL) {
  1318. SSL_SESSION_free(new_session);
  1319. goto err;
  1320. }
  1321. }
  1322. SSL_SESSION_free(s->session);
  1323. s->session = new_session;
  1324. }
  1325. CBS_init(&new_session_ticket, s->init_msg, n);
  1326. if (!CBS_get_u32(&new_session_ticket,
  1327. &s->session->tlsext_tick_lifetime_hint) ||
  1328. !CBS_get_u16_length_prefixed(&new_session_ticket, &ticket) ||
  1329. CBS_len(&new_session_ticket) != 0) {
  1330. al = SSL_AD_DECODE_ERROR;
  1331. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1332. goto f_err;
  1333. }
  1334. if (!CBS_stow(&ticket, &s->session->tlsext_tick,
  1335. &s->session->tlsext_ticklen)) {
  1336. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1337. goto err;
  1338. }
  1339. /* Generate a session ID for this session based on the session ticket. We use
  1340. * the session ID mechanism for detecting ticket resumption. This also fits in
  1341. * with assumptions elsewhere in OpenSSL.*/
  1342. if (!EVP_Digest(CBS_data(&ticket), CBS_len(&ticket), s->session->session_id,
  1343. &s->session->session_id_length, EVP_sha256(), NULL)) {
  1344. goto err;
  1345. }
  1346. return 1;
  1347. f_err:
  1348. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1349. err:
  1350. return -1;
  1351. }
  1352. int ssl3_get_cert_status(SSL *s) {
  1353. int ok, al;
  1354. long n;
  1355. CBS certificate_status, ocsp_response;
  1356. uint8_t status_type;
  1357. n = s->method->ssl_get_message(
  1358. s, SSL3_ST_CR_CERT_STATUS_A, SSL3_ST_CR_CERT_STATUS_B,
  1359. -1, 16384, ssl_hash_message, &ok);
  1360. if (!ok) {
  1361. return n;
  1362. }
  1363. if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_STATUS) {
  1364. /* A server may send status_request in ServerHello and then change
  1365. * its mind about sending CertificateStatus. */
  1366. s->s3->tmp.reuse_message = 1;
  1367. return 1;
  1368. }
  1369. CBS_init(&certificate_status, s->init_msg, n);
  1370. if (!CBS_get_u8(&certificate_status, &status_type) ||
  1371. status_type != TLSEXT_STATUSTYPE_ocsp ||
  1372. !CBS_get_u24_length_prefixed(&certificate_status, &ocsp_response) ||
  1373. CBS_len(&ocsp_response) == 0 ||
  1374. CBS_len(&certificate_status) != 0) {
  1375. al = SSL_AD_DECODE_ERROR;
  1376. OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
  1377. goto f_err;
  1378. }
  1379. if (!CBS_stow(&ocsp_response, &s->session->ocsp_response,
  1380. &s->session->ocsp_response_length)) {
  1381. al = SSL_AD_INTERNAL_ERROR;
  1382. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1383. goto f_err;
  1384. }
  1385. return 1;
  1386. f_err:
  1387. ssl3_send_alert(s, SSL3_AL_FATAL, al);
  1388. return -1;
  1389. }
  1390. int ssl3_get_server_done(SSL *s) {
  1391. int ok;
  1392. long n;
  1393. n = s->method->ssl_get_message(s, SSL3_ST_CR_SRVR_DONE_A,
  1394. SSL3_ST_CR_SRVR_DONE_B, SSL3_MT_SERVER_DONE,
  1395. 30, /* should be very small, like 0 :-) */
  1396. ssl_hash_message, &ok);
  1397. if (!ok) {
  1398. return n;
  1399. }
  1400. if (n > 0) {
  1401. /* should contain no data */
  1402. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
  1403. OPENSSL_PUT_ERROR(SSL, SSL_R_LENGTH_MISMATCH);
  1404. return -1;
  1405. }
  1406. return 1;
  1407. }
  1408. int ssl3_send_client_key_exchange(SSL *s) {
  1409. uint8_t *p;
  1410. int n = 0;
  1411. uint32_t alg_k;
  1412. uint32_t alg_a;
  1413. uint8_t *q;
  1414. EVP_PKEY *pkey = NULL;
  1415. EC_KEY *clnt_ecdh = NULL;
  1416. const EC_POINT *srvr_ecpoint = NULL;
  1417. EVP_PKEY *srvr_pub_pkey = NULL;
  1418. uint8_t *encodedPoint = NULL;
  1419. int encoded_pt_len = 0;
  1420. BN_CTX *bn_ctx = NULL;
  1421. unsigned int psk_len = 0;
  1422. uint8_t psk[PSK_MAX_PSK_LEN];
  1423. uint8_t *pms = NULL;
  1424. size_t pms_len = 0;
  1425. if (s->state == SSL3_ST_CW_KEY_EXCH_A) {
  1426. p = ssl_handshake_start(s);
  1427. alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
  1428. alg_a = s->s3->tmp.new_cipher->algorithm_auth;
  1429. /* If using a PSK key exchange, prepare the pre-shared key. */
  1430. if (alg_a & SSL_aPSK) {
  1431. char identity[PSK_MAX_IDENTITY_LEN + 1];
  1432. size_t identity_len;
  1433. if (s->psk_client_callback == NULL) {
  1434. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_NO_CLIENT_CB);
  1435. goto err;
  1436. }
  1437. memset(identity, 0, sizeof(identity));
  1438. psk_len =
  1439. s->psk_client_callback(s, s->s3->tmp.peer_psk_identity_hint, identity,
  1440. sizeof(identity), psk, sizeof(psk));
  1441. if (psk_len > PSK_MAX_PSK_LEN) {
  1442. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1443. goto err;
  1444. } else if (psk_len == 0) {
  1445. OPENSSL_PUT_ERROR(SSL, SSL_R_PSK_IDENTITY_NOT_FOUND);
  1446. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1447. goto err;
  1448. }
  1449. identity_len = OPENSSL_strnlen(identity, sizeof(identity));
  1450. if (identity_len > PSK_MAX_IDENTITY_LEN) {
  1451. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1452. goto err;
  1453. }
  1454. OPENSSL_free(s->session->psk_identity);
  1455. s->session->psk_identity = BUF_strdup(identity);
  1456. if (s->session->psk_identity == NULL) {
  1457. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1458. goto err;
  1459. }
  1460. /* Write out psk_identity. */
  1461. s2n(identity_len, p);
  1462. memcpy(p, identity, identity_len);
  1463. p += identity_len;
  1464. n = 2 + identity_len;
  1465. }
  1466. /* Depending on the key exchange method, compute |pms| and |pms_len|. */
  1467. if (alg_k & SSL_kRSA) {
  1468. RSA *rsa;
  1469. size_t enc_pms_len;
  1470. pms_len = SSL_MAX_MASTER_KEY_LENGTH;
  1471. pms = OPENSSL_malloc(pms_len);
  1472. if (pms == NULL) {
  1473. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1474. goto err;
  1475. }
  1476. if (s->session->sess_cert == NULL) {
  1477. /* We should always have a server certificate with SSL_kRSA. */
  1478. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1479. goto err;
  1480. }
  1481. pkey = X509_get_pubkey(s->session->sess_cert->peer_cert);
  1482. if (pkey == NULL ||
  1483. pkey->type != EVP_PKEY_RSA ||
  1484. pkey->pkey.rsa == NULL) {
  1485. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1486. EVP_PKEY_free(pkey);
  1487. goto err;
  1488. }
  1489. rsa = pkey->pkey.rsa;
  1490. EVP_PKEY_free(pkey);
  1491. pms[0] = s->client_version >> 8;
  1492. pms[1] = s->client_version & 0xff;
  1493. if (!RAND_bytes(&pms[2], SSL_MAX_MASTER_KEY_LENGTH - 2)) {
  1494. goto err;
  1495. }
  1496. s->session->master_key_length = SSL_MAX_MASTER_KEY_LENGTH;
  1497. q = p;
  1498. /* In TLS and beyond, reserve space for the length prefix. */
  1499. if (s->version > SSL3_VERSION) {
  1500. p += 2;
  1501. n += 2;
  1502. }
  1503. if (!RSA_encrypt(rsa, &enc_pms_len, p, RSA_size(rsa), pms, pms_len,
  1504. RSA_PKCS1_PADDING)) {
  1505. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_RSA_ENCRYPT);
  1506. goto err;
  1507. }
  1508. n += enc_pms_len;
  1509. /* Log the premaster secret, if logging is enabled. */
  1510. if (!ssl_ctx_log_rsa_client_key_exchange(s->ctx, p, enc_pms_len, pms,
  1511. pms_len)) {
  1512. goto err;
  1513. }
  1514. /* Fill in the length prefix. */
  1515. if (s->version > SSL3_VERSION) {
  1516. s2n(enc_pms_len, q);
  1517. }
  1518. } else if (alg_k & SSL_kDHE) {
  1519. DH *dh_srvr, *dh_clnt;
  1520. SESS_CERT *scert = s->session->sess_cert;
  1521. int dh_len;
  1522. size_t pub_len;
  1523. if (scert == NULL) {
  1524. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  1525. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  1526. goto err;
  1527. }
  1528. if (scert->peer_dh_tmp == NULL) {
  1529. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1530. goto err;
  1531. }
  1532. dh_srvr = scert->peer_dh_tmp;
  1533. /* generate a new random key */
  1534. dh_clnt = DHparams_dup(dh_srvr);
  1535. if (dh_clnt == NULL) {
  1536. OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
  1537. goto err;
  1538. }
  1539. if (!DH_generate_key(dh_clnt)) {
  1540. OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
  1541. DH_free(dh_clnt);
  1542. goto err;
  1543. }
  1544. pms_len = DH_size(dh_clnt);
  1545. pms = OPENSSL_malloc(pms_len);
  1546. if (pms == NULL) {
  1547. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1548. DH_free(dh_clnt);
  1549. goto err;
  1550. }
  1551. dh_len = DH_compute_key(pms, dh_srvr->pub_key, dh_clnt);
  1552. if (dh_len <= 0) {
  1553. OPENSSL_PUT_ERROR(SSL, ERR_R_DH_LIB);
  1554. DH_free(dh_clnt);
  1555. goto err;
  1556. }
  1557. pms_len = dh_len;
  1558. /* send off the data */
  1559. pub_len = BN_num_bytes(dh_clnt->pub_key);
  1560. s2n(pub_len, p);
  1561. BN_bn2bin(dh_clnt->pub_key, p);
  1562. n += 2 + pub_len;
  1563. DH_free(dh_clnt);
  1564. } else if (alg_k & SSL_kECDHE) {
  1565. const EC_GROUP *srvr_group = NULL;
  1566. EC_KEY *tkey;
  1567. int field_size = 0, ecdh_len;
  1568. if (s->session->sess_cert == NULL) {
  1569. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
  1570. OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
  1571. goto err;
  1572. }
  1573. if (s->session->sess_cert->peer_ecdh_tmp == NULL) {
  1574. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1575. goto err;
  1576. }
  1577. tkey = s->session->sess_cert->peer_ecdh_tmp;
  1578. srvr_group = EC_KEY_get0_group(tkey);
  1579. srvr_ecpoint = EC_KEY_get0_public_key(tkey);
  1580. if (srvr_group == NULL || srvr_ecpoint == NULL) {
  1581. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1582. goto err;
  1583. }
  1584. clnt_ecdh = EC_KEY_new();
  1585. if (clnt_ecdh == NULL) {
  1586. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1587. goto err;
  1588. }
  1589. if (!EC_KEY_set_group(clnt_ecdh, srvr_group)) {
  1590. OPENSSL_PUT_ERROR(SSL, ERR_R_EC_LIB);
  1591. goto err;
  1592. }
  1593. /* Generate a new ECDH key pair */
  1594. if (!EC_KEY_generate_key(clnt_ecdh)) {
  1595. OPENSSL_PUT_ERROR(SSL, ERR_R_ECDH_LIB);
  1596. goto err;
  1597. }
  1598. field_size = EC_GROUP_get_degree(srvr_group);
  1599. if (field_size <= 0) {
  1600. OPENSSL_PUT_ERROR(SSL, ERR_R_ECDH_LIB);
  1601. goto err;
  1602. }
  1603. pms_len = (field_size + 7) / 8;
  1604. pms = OPENSSL_malloc(pms_len);
  1605. if (pms == NULL) {
  1606. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1607. goto err;
  1608. }
  1609. ecdh_len = ECDH_compute_key(pms, pms_len, srvr_ecpoint, clnt_ecdh, NULL);
  1610. if (ecdh_len <= 0) {
  1611. OPENSSL_PUT_ERROR(SSL, ERR_R_ECDH_LIB);
  1612. goto err;
  1613. }
  1614. pms_len = ecdh_len;
  1615. /* First check the size of encoding and allocate memory accordingly. */
  1616. encoded_pt_len =
  1617. EC_POINT_point2oct(srvr_group, EC_KEY_get0_public_key(clnt_ecdh),
  1618. POINT_CONVERSION_UNCOMPRESSED, NULL, 0, NULL);
  1619. encodedPoint =
  1620. (uint8_t *)OPENSSL_malloc(encoded_pt_len * sizeof(uint8_t));
  1621. bn_ctx = BN_CTX_new();
  1622. if (encodedPoint == NULL || bn_ctx == NULL) {
  1623. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1624. goto err;
  1625. }
  1626. /* Encode the public key */
  1627. encoded_pt_len = EC_POINT_point2oct(
  1628. srvr_group, EC_KEY_get0_public_key(clnt_ecdh),
  1629. POINT_CONVERSION_UNCOMPRESSED, encodedPoint, encoded_pt_len, bn_ctx);
  1630. *p = encoded_pt_len; /* length of encoded point */
  1631. /* Encoded point will be copied here */
  1632. p += 1;
  1633. n += 1;
  1634. /* copy the point */
  1635. memcpy(p, encodedPoint, encoded_pt_len);
  1636. /* increment n to account for length field */
  1637. n += encoded_pt_len;
  1638. /* Free allocated memory */
  1639. BN_CTX_free(bn_ctx);
  1640. bn_ctx = NULL;
  1641. OPENSSL_free(encodedPoint);
  1642. encodedPoint = NULL;
  1643. EC_KEY_free(clnt_ecdh);
  1644. clnt_ecdh = NULL;
  1645. EVP_PKEY_free(srvr_pub_pkey);
  1646. srvr_pub_pkey = NULL;
  1647. } else if (alg_k & SSL_kPSK) {
  1648. /* For plain PSK, other_secret is a block of 0s with the same length as
  1649. * the pre-shared key. */
  1650. pms_len = psk_len;
  1651. pms = OPENSSL_malloc(pms_len);
  1652. if (pms == NULL) {
  1653. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1654. goto err;
  1655. }
  1656. memset(pms, 0, pms_len);
  1657. } else {
  1658. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
  1659. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1660. goto err;
  1661. }
  1662. /* For a PSK cipher suite, other_secret is combined with the pre-shared
  1663. * key. */
  1664. if (alg_a & SSL_aPSK) {
  1665. CBB cbb, child;
  1666. uint8_t *new_pms;
  1667. size_t new_pms_len;
  1668. CBB_zero(&cbb);
  1669. if (!CBB_init(&cbb, 2 + psk_len + 2 + pms_len) ||
  1670. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1671. !CBB_add_bytes(&child, pms, pms_len) ||
  1672. !CBB_add_u16_length_prefixed(&cbb, &child) ||
  1673. !CBB_add_bytes(&child, psk, psk_len) ||
  1674. !CBB_finish(&cbb, &new_pms, &new_pms_len)) {
  1675. CBB_cleanup(&cbb);
  1676. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1677. goto err;
  1678. }
  1679. OPENSSL_cleanse(pms, pms_len);
  1680. OPENSSL_free(pms);
  1681. pms = new_pms;
  1682. pms_len = new_pms_len;
  1683. }
  1684. /* The message must be added to the finished hash before calculating the
  1685. * master secret. */
  1686. if (!ssl_set_handshake_header(s, SSL3_MT_CLIENT_KEY_EXCHANGE, n)) {
  1687. goto err;
  1688. }
  1689. s->state = SSL3_ST_CW_KEY_EXCH_B;
  1690. s->session->master_key_length = s->enc_method->generate_master_secret(
  1691. s, s->session->master_key, pms, pms_len);
  1692. if (s->session->master_key_length == 0) {
  1693. goto err;
  1694. }
  1695. s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
  1696. OPENSSL_cleanse(pms, pms_len);
  1697. OPENSSL_free(pms);
  1698. }
  1699. /* SSL3_ST_CW_KEY_EXCH_B */
  1700. return s->method->do_write(s);
  1701. err:
  1702. BN_CTX_free(bn_ctx);
  1703. OPENSSL_free(encodedPoint);
  1704. EC_KEY_free(clnt_ecdh);
  1705. EVP_PKEY_free(srvr_pub_pkey);
  1706. if (pms) {
  1707. OPENSSL_cleanse(pms, pms_len);
  1708. OPENSSL_free(pms);
  1709. }
  1710. return -1;
  1711. }
  1712. int ssl3_send_cert_verify(SSL *s) {
  1713. if (s->state == SSL3_ST_CW_CERT_VRFY_A ||
  1714. s->state == SSL3_ST_CW_CERT_VRFY_B) {
  1715. enum ssl_private_key_result_t sign_result;
  1716. uint8_t *p = ssl_handshake_start(s);
  1717. size_t signature_length = 0;
  1718. unsigned long n = 0;
  1719. assert(ssl_has_private_key(s));
  1720. if (s->state == SSL3_ST_CW_CERT_VRFY_A) {
  1721. uint8_t *buf = (uint8_t *)s->init_buf->data;
  1722. const EVP_MD *md = NULL;
  1723. uint8_t digest[EVP_MAX_MD_SIZE];
  1724. size_t digest_length;
  1725. /* Write out the digest type if need be. */
  1726. if (SSL_USE_SIGALGS(s)) {
  1727. md = tls1_choose_signing_digest(s);
  1728. if (!tls12_get_sigandhash(s, p, md)) {
  1729. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1730. return -1;
  1731. }
  1732. p += 2;
  1733. n += 2;
  1734. }
  1735. /* Compute the digest. */
  1736. const int pkey_type = ssl_private_key_type(s);
  1737. if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey_type)) {
  1738. return -1;
  1739. }
  1740. /* The handshake buffer is no longer necessary. */
  1741. if (s->s3->handshake_buffer &&
  1742. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  1743. return -1;
  1744. }
  1745. /* Sign the digest. */
  1746. signature_length = ssl_private_key_max_signature_len(s);
  1747. if (p + 2 + signature_length > buf + SSL3_RT_MAX_PLAIN_LENGTH) {
  1748. OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
  1749. return -1;
  1750. }
  1751. s->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1752. sign_result = ssl_private_key_sign(s, &p[2], &signature_length,
  1753. signature_length, md, digest,
  1754. digest_length);
  1755. } else {
  1756. if (SSL_USE_SIGALGS(s)) {
  1757. /* The digest has already been selected and written. */
  1758. p += 2;
  1759. n += 2;
  1760. }
  1761. signature_length = ssl_private_key_max_signature_len(s);
  1762. s->rwstate = SSL_PRIVATE_KEY_OPERATION;
  1763. sign_result = ssl_private_key_sign_complete(s, &p[2], &signature_length,
  1764. signature_length);
  1765. }
  1766. if (sign_result == ssl_private_key_retry) {
  1767. s->state = SSL3_ST_CW_CERT_VRFY_B;
  1768. return -1;
  1769. }
  1770. s->rwstate = SSL_NOTHING;
  1771. if (sign_result != ssl_private_key_success) {
  1772. return -1;
  1773. }
  1774. s2n(signature_length, p);
  1775. n += signature_length + 2;
  1776. if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_VERIFY, n)) {
  1777. return -1;
  1778. }
  1779. s->state = SSL3_ST_CW_CERT_VRFY_C;
  1780. }
  1781. return ssl_do_write(s);
  1782. }
  1783. /* ssl3_has_client_certificate returns true if a client certificate is
  1784. * configured. */
  1785. static int ssl3_has_client_certificate(SSL *ssl) {
  1786. return ssl->cert && ssl->cert->x509 && ssl_has_private_key(ssl);
  1787. }
  1788. int ssl3_send_client_certificate(SSL *s) {
  1789. X509 *x509 = NULL;
  1790. EVP_PKEY *pkey = NULL;
  1791. int i;
  1792. if (s->state == SSL3_ST_CW_CERT_A) {
  1793. /* Let cert callback update client certificates if required */
  1794. if (s->cert->cert_cb) {
  1795. i = s->cert->cert_cb(s, s->cert->cert_cb_arg);
  1796. if (i < 0) {
  1797. s->rwstate = SSL_X509_LOOKUP;
  1798. return -1;
  1799. }
  1800. if (i == 0) {
  1801. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1802. return 0;
  1803. }
  1804. s->rwstate = SSL_NOTHING;
  1805. }
  1806. if (ssl3_has_client_certificate(s)) {
  1807. s->state = SSL3_ST_CW_CERT_C;
  1808. } else {
  1809. s->state = SSL3_ST_CW_CERT_B;
  1810. }
  1811. }
  1812. /* We need to get a client cert */
  1813. if (s->state == SSL3_ST_CW_CERT_B) {
  1814. /* If we get an error, we need to:
  1815. * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
  1816. * We then get retried later */
  1817. i = ssl_do_client_cert_cb(s, &x509, &pkey);
  1818. if (i < 0) {
  1819. s->rwstate = SSL_X509_LOOKUP;
  1820. return -1;
  1821. }
  1822. s->rwstate = SSL_NOTHING;
  1823. if (i == 1 && pkey != NULL && x509 != NULL) {
  1824. s->state = SSL3_ST_CW_CERT_B;
  1825. if (!SSL_use_certificate(s, x509) || !SSL_use_PrivateKey(s, pkey)) {
  1826. i = 0;
  1827. }
  1828. } else if (i == 1) {
  1829. i = 0;
  1830. OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
  1831. }
  1832. X509_free(x509);
  1833. EVP_PKEY_free(pkey);
  1834. if (i && !ssl3_has_client_certificate(s)) {
  1835. i = 0;
  1836. }
  1837. if (i == 0) {
  1838. if (s->version == SSL3_VERSION) {
  1839. s->s3->tmp.cert_req = 0;
  1840. ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
  1841. return 1;
  1842. } else {
  1843. s->s3->tmp.cert_req = 2;
  1844. /* There is no client certificate, so the handshake buffer may be
  1845. * released. */
  1846. if (s->s3->handshake_buffer &&
  1847. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  1848. ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
  1849. return -1;
  1850. }
  1851. }
  1852. }
  1853. /* Ok, we have a cert */
  1854. s->state = SSL3_ST_CW_CERT_C;
  1855. }
  1856. if (s->state == SSL3_ST_CW_CERT_C) {
  1857. if (s->s3->tmp.cert_req == 2) {
  1858. /* Send an empty Certificate message. */
  1859. uint8_t *p = ssl_handshake_start(s);
  1860. l2n3(0, p);
  1861. if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE, 3)) {
  1862. return -1;
  1863. }
  1864. } else if (!ssl3_output_cert_chain(s)) {
  1865. return -1;
  1866. }
  1867. s->state = SSL3_ST_CW_CERT_D;
  1868. }
  1869. /* SSL3_ST_CW_CERT_D */
  1870. return ssl_do_write(s);
  1871. }
  1872. int ssl3_send_next_proto(SSL *s) {
  1873. unsigned int len, padding_len;
  1874. uint8_t *d, *p;
  1875. if (s->state == SSL3_ST_CW_NEXT_PROTO_A) {
  1876. len = s->next_proto_negotiated_len;
  1877. padding_len = 32 - ((len + 2) % 32);
  1878. d = p = ssl_handshake_start(s);
  1879. *(p++) = len;
  1880. memcpy(p, s->next_proto_negotiated, len);
  1881. p += len;
  1882. *(p++) = padding_len;
  1883. memset(p, 0, padding_len);
  1884. p += padding_len;
  1885. if (!ssl_set_handshake_header(s, SSL3_MT_NEXT_PROTO, p - d)) {
  1886. return -1;
  1887. }
  1888. s->state = SSL3_ST_CW_NEXT_PROTO_B;
  1889. }
  1890. return ssl_do_write(s);
  1891. }
  1892. int ssl3_send_channel_id(SSL *s) {
  1893. uint8_t *d;
  1894. int ret = -1, public_key_len;
  1895. EVP_MD_CTX md_ctx;
  1896. ECDSA_SIG *sig = NULL;
  1897. uint8_t *public_key = NULL, *derp, *der_sig = NULL;
  1898. if (s->state != SSL3_ST_CW_CHANNEL_ID_A) {
  1899. return ssl_do_write(s);
  1900. }
  1901. if (!s->tlsext_channel_id_private && s->ctx->channel_id_cb) {
  1902. EVP_PKEY *key = NULL;
  1903. s->ctx->channel_id_cb(s, &key);
  1904. if (key != NULL) {
  1905. s->tlsext_channel_id_private = key;
  1906. }
  1907. }
  1908. if (!s->tlsext_channel_id_private) {
  1909. s->rwstate = SSL_CHANNEL_ID_LOOKUP;
  1910. return -1;
  1911. }
  1912. s->rwstate = SSL_NOTHING;
  1913. if (EVP_PKEY_id(s->tlsext_channel_id_private) != EVP_PKEY_EC) {
  1914. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1915. return -1;
  1916. }
  1917. EC_KEY *ec_key = s->tlsext_channel_id_private->pkey.ec;
  1918. d = ssl_handshake_start(s);
  1919. s2n(TLSEXT_TYPE_channel_id, d);
  1920. s2n(TLSEXT_CHANNEL_ID_SIZE, d);
  1921. EVP_MD_CTX_init(&md_ctx);
  1922. public_key_len = i2o_ECPublicKey(ec_key, NULL);
  1923. if (public_key_len <= 0) {
  1924. OPENSSL_PUT_ERROR(SSL, SSL_R_CANNOT_SERIALIZE_PUBLIC_KEY);
  1925. goto err;
  1926. }
  1927. /* i2o_ECPublicKey will produce an ANSI X9.62 public key which, for a
  1928. * P-256 key, is 0x04 (meaning uncompressed) followed by the x and y
  1929. * field elements as 32-byte, big-endian numbers. */
  1930. if (public_key_len != 65) {
  1931. OPENSSL_PUT_ERROR(SSL, SSL_R_CHANNEL_ID_NOT_P256);
  1932. goto err;
  1933. }
  1934. public_key = OPENSSL_malloc(public_key_len);
  1935. if (!public_key) {
  1936. OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
  1937. goto err;
  1938. }
  1939. derp = public_key;
  1940. i2o_ECPublicKey(ec_key, &derp);
  1941. uint8_t digest[EVP_MAX_MD_SIZE];
  1942. unsigned digest_len;
  1943. if (!EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL) ||
  1944. !tls1_channel_id_hash(&md_ctx, s) ||
  1945. !EVP_DigestFinal_ex(&md_ctx, digest, &digest_len)) {
  1946. goto err;
  1947. }
  1948. sig = ECDSA_do_sign(digest, digest_len, ec_key);
  1949. if (sig == NULL) {
  1950. goto err;
  1951. }
  1952. /* The first byte of public_key will be 0x4, denoting an uncompressed key. */
  1953. memcpy(d, public_key + 1, 64);
  1954. d += 64;
  1955. if (!BN_bn2bin_padded(d, 32, sig->r) ||
  1956. !BN_bn2bin_padded(d + 32, 32, sig->s)) {
  1957. OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
  1958. goto err;
  1959. }
  1960. if (!ssl_set_handshake_header(s, SSL3_MT_ENCRYPTED_EXTENSIONS,
  1961. 2 + 2 + TLSEXT_CHANNEL_ID_SIZE)) {
  1962. goto err;
  1963. }
  1964. s->state = SSL3_ST_CW_CHANNEL_ID_B;
  1965. ret = ssl_do_write(s);
  1966. err:
  1967. EVP_MD_CTX_cleanup(&md_ctx);
  1968. OPENSSL_free(public_key);
  1969. OPENSSL_free(der_sig);
  1970. ECDSA_SIG_free(sig);
  1971. return ret;
  1972. }
  1973. int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey) {
  1974. int i = 0;
  1975. if (s->ctx->client_cert_cb) {
  1976. i = s->ctx->client_cert_cb(s, px509, ppkey);
  1977. }
  1978. return i;
  1979. }