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.
 
 
 
 
 
 

2873 regels
78 KiB

  1. /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
  2. * All rights reserved.
  3. *
  4. * This package is an SSL implementation written
  5. * by Eric Young (eay@cryptsoft.com).
  6. * The implementation was written so as to conform with Netscapes SSL.
  7. *
  8. * This library is free for commercial and non-commercial use as long as
  9. * the following conditions are aheared to. The following conditions
  10. * apply to all code found in this distribution, be it the RC4, RSA,
  11. * lhash, DES, etc., code; not just the SSL code. The SSL documentation
  12. * included with this distribution is covered by the same copyright terms
  13. * except that the holder is Tim Hudson (tjh@cryptsoft.com).
  14. *
  15. * Copyright remains Eric Young's, and as such any Copyright notices in
  16. * the code are not to be removed.
  17. * If this package is used in a product, Eric Young should be given attribution
  18. * as the author of the parts of the library used.
  19. * This can be in the form of a textual message at program startup or
  20. * in documentation (online or textual) provided with the package.
  21. *
  22. * Redistribution and use in source and binary forms, with or without
  23. * modification, are permitted provided that the following conditions
  24. * are met:
  25. * 1. Redistributions of source code must retain the copyright
  26. * notice, this list of conditions and the following disclaimer.
  27. * 2. Redistributions in binary form must reproduce the above copyright
  28. * notice, this list of conditions and the following disclaimer in the
  29. * documentation and/or other materials provided with the distribution.
  30. * 3. All advertising materials mentioning features or use of this software
  31. * must display the following acknowledgement:
  32. * "This product includes cryptographic software written by
  33. * Eric Young (eay@cryptsoft.com)"
  34. * The word 'cryptographic' can be left out if the rouines from the library
  35. * being used are not cryptographic related :-).
  36. * 4. If you include any Windows specific code (or a derivative thereof) from
  37. * the apps directory (application code) you must include an acknowledgement:
  38. * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
  39. *
  40. * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
  41. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  42. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  43. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  44. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  45. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  46. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  47. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  48. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  49. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  50. * SUCH DAMAGE.
  51. *
  52. * The licence and distribution terms for any publically available version or
  53. * derivative of this code cannot be changed. i.e. this code cannot simply be
  54. * copied and put under another distribution licence
  55. * [including the GNU Public Licence.]
  56. */
  57. /* ====================================================================
  58. * Copyright (c) 1998-2007 The OpenSSL Project. All rights reserved.
  59. *
  60. * Redistribution and use in source and binary forms, with or without
  61. * modification, are permitted provided that the following conditions
  62. * are met:
  63. *
  64. * 1. Redistributions of source code must retain the above copyright
  65. * notice, this list of conditions and the following disclaimer.
  66. *
  67. * 2. Redistributions in binary form must reproduce the above copyright
  68. * notice, this list of conditions and the following disclaimer in
  69. * the documentation and/or other materials provided with the
  70. * distribution.
  71. *
  72. * 3. All advertising materials mentioning features or use of this
  73. * software must display the following acknowledgment:
  74. * "This product includes software developed by the OpenSSL Project
  75. * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
  76. *
  77. * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
  78. * endorse or promote products derived from this software without
  79. * prior written permission. For written permission, please contact
  80. * openssl-core@openssl.org.
  81. *
  82. * 5. Products derived from this software may not be called "OpenSSL"
  83. * nor may "OpenSSL" appear in their names without prior written
  84. * permission of the OpenSSL Project.
  85. *
  86. * 6. Redistributions of any form whatsoever must retain the following
  87. * acknowledgment:
  88. * "This product includes software developed by the OpenSSL Project
  89. * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
  90. *
  91. * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
  92. * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  93. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  94. * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
  95. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  96. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  97. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  98. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  99. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  100. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  101. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
  102. * OF THE POSSIBILITY OF SUCH DAMAGE.
  103. * ====================================================================
  104. *
  105. * This product includes cryptographic software written by Eric Young
  106. * (eay@cryptsoft.com). This product includes software written by Tim
  107. * Hudson (tjh@cryptsoft.com).
  108. *
  109. */
  110. /* ====================================================================
  111. * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
  112. *
  113. * Portions of the attached software ("Contribution") are developed by
  114. * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
  115. *
  116. * The Contribution is licensed pursuant to the OpenSSL open source
  117. * license provided above.
  118. *
  119. * ECC cipher suite support in OpenSSL originally written by
  120. * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
  121. *
  122. */
  123. /* ====================================================================
  124. * Copyright 2005 Nokia. All rights reserved.
  125. *
  126. * The portions of the attached software ("Contribution") is developed by
  127. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  128. * license.
  129. *
  130. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  131. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  132. * support (see RFC 4279) to OpenSSL.
  133. *
  134. * No patent licenses or other rights except those expressly stated in
  135. * the OpenSSL open source license shall be deemed granted or received
  136. * expressly, by implication, estoppel, or otherwise.
  137. *
  138. * No assurances are provided by Nokia that the Contribution does not
  139. * infringe the patent or other intellectual property rights of any third
  140. * party or that the license provides you with all the necessary rights
  141. * to make use of the Contribution.
  142. *
  143. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  144. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  145. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  146. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  147. * OTHERWISE. */
  148. #define NETSCAPE_HANG_BUG
  149. #include <assert.h>
  150. #include <stdio.h>
  151. #include <string.h>
  152. #include <openssl/bn.h>
  153. #include <openssl/buf.h>
  154. #include <openssl/bytestring.h>
  155. #include <openssl/cipher.h>
  156. #include <openssl/dh.h>
  157. #include <openssl/ec.h>
  158. #include <openssl/ecdsa.h>
  159. #include <openssl/evp.h>
  160. #include <openssl/hmac.h>
  161. #include <openssl/md5.h>
  162. #include <openssl/mem.h>
  163. #include <openssl/obj.h>
  164. #include <openssl/rand.h>
  165. #include <openssl/sha.h>
  166. #include <openssl/x509.h>
  167. #include "ssl_locl.h"
  168. #include "../crypto/internal.h"
  169. #include "../crypto/dh/internal.h"
  170. static const SSL_METHOD *ssl3_get_server_method(int ver)
  171. {
  172. switch (ver)
  173. {
  174. case TLS1_2_VERSION:
  175. return TLSv1_2_server_method();
  176. case TLS1_1_VERSION:
  177. return TLSv1_1_server_method();
  178. case TLS1_VERSION:
  179. return TLSv1_server_method();
  180. case SSL3_VERSION:
  181. return SSLv3_server_method();
  182. default:
  183. return NULL;
  184. }
  185. }
  186. IMPLEMENT_tls_meth_func(TLS1_2_VERSION, TLSv1_2_server_method,
  187. ssl3_accept,
  188. ssl_undefined_function,
  189. ssl3_get_server_method,
  190. TLSv1_2_enc_data)
  191. IMPLEMENT_tls_meth_func(TLS1_1_VERSION, TLSv1_1_server_method,
  192. ssl3_accept,
  193. ssl_undefined_function,
  194. ssl3_get_server_method,
  195. TLSv1_1_enc_data)
  196. IMPLEMENT_tls_meth_func(TLS1_VERSION, TLSv1_server_method,
  197. ssl3_accept,
  198. ssl_undefined_function,
  199. ssl3_get_server_method,
  200. TLSv1_enc_data)
  201. IMPLEMENT_tls_meth_func(SSL3_VERSION, SSLv3_server_method,
  202. ssl3_accept,
  203. ssl_undefined_function,
  204. ssl3_get_server_method,
  205. SSLv3_enc_data)
  206. int ssl3_accept(SSL *s)
  207. {
  208. BUF_MEM *buf;
  209. unsigned long alg_a;
  210. void (*cb)(const SSL *ssl,int type,int val)=NULL;
  211. int ret= -1;
  212. int new_state,state,skip=0;
  213. ERR_clear_error();
  214. ERR_clear_system_error();
  215. if (s->info_callback != NULL)
  216. cb=s->info_callback;
  217. else if (s->ctx->info_callback != NULL)
  218. cb=s->ctx->info_callback;
  219. /* init things to blank */
  220. s->in_handshake++;
  221. if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
  222. if (s->cert == NULL)
  223. {
  224. OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_NO_CERTIFICATE_SET);
  225. return(-1);
  226. }
  227. for (;;)
  228. {
  229. state=s->state;
  230. switch (s->state)
  231. {
  232. case SSL_ST_RENEGOTIATE:
  233. s->renegotiate=1;
  234. /* s->state=SSL_ST_ACCEPT; */
  235. case SSL_ST_BEFORE:
  236. case SSL_ST_ACCEPT:
  237. case SSL_ST_BEFORE|SSL_ST_ACCEPT:
  238. case SSL_ST_OK|SSL_ST_ACCEPT:
  239. s->server=1;
  240. if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
  241. if ((s->version>>8) != 3)
  242. {
  243. OPENSSL_PUT_ERROR(SSL, ssl3_accept, ERR_R_INTERNAL_ERROR);
  244. return -1;
  245. }
  246. s->type=SSL_ST_ACCEPT;
  247. if (s->init_buf == NULL)
  248. {
  249. if ((buf=BUF_MEM_new()) == NULL)
  250. {
  251. ret= -1;
  252. goto end;
  253. }
  254. if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
  255. {
  256. ret= -1;
  257. goto end;
  258. }
  259. s->init_buf=buf;
  260. }
  261. if (!ssl3_setup_buffers(s))
  262. {
  263. ret= -1;
  264. goto end;
  265. }
  266. s->init_num=0;
  267. if (s->state != SSL_ST_RENEGOTIATE)
  268. {
  269. /* Ok, we now need to push on a buffering BIO so that
  270. * the output is sent in a way that TCP likes :-)
  271. */
  272. if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
  273. ssl3_init_finished_mac(s);
  274. s->state=SSL3_ST_SR_CLNT_HELLO_A;
  275. s->ctx->stats.sess_accept++;
  276. }
  277. else if (!s->s3->send_connection_binding &&
  278. !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
  279. {
  280. /* Server attempting to renegotiate with
  281. * client that doesn't support secure
  282. * renegotiation.
  283. */
  284. OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
  285. ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
  286. ret = -1;
  287. goto end;
  288. }
  289. else
  290. {
  291. /* s->state == SSL_ST_RENEGOTIATE,
  292. * we will just send a HelloRequest */
  293. s->ctx->stats.sess_accept_renegotiate++;
  294. s->state=SSL3_ST_SW_HELLO_REQ_A;
  295. }
  296. break;
  297. case SSL3_ST_SW_HELLO_REQ_A:
  298. case SSL3_ST_SW_HELLO_REQ_B:
  299. s->shutdown=0;
  300. ret=ssl3_send_hello_request(s);
  301. if (ret <= 0) goto end;
  302. s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
  303. s->state=SSL3_ST_SW_FLUSH;
  304. s->init_num=0;
  305. ssl3_init_finished_mac(s);
  306. break;
  307. case SSL3_ST_SW_HELLO_REQ_C:
  308. s->state=SSL_ST_OK;
  309. break;
  310. case SSL3_ST_SR_CLNT_HELLO_A:
  311. case SSL3_ST_SR_CLNT_HELLO_B:
  312. case SSL3_ST_SR_CLNT_HELLO_C:
  313. case SSL3_ST_SR_CLNT_HELLO_D:
  314. s->shutdown=0;
  315. ret=ssl3_get_client_hello(s);
  316. if (ret == PENDING_SESSION) {
  317. s->rwstate = SSL_PENDING_SESSION;
  318. goto end;
  319. }
  320. if (ret == CERTIFICATE_SELECTION_PENDING)
  321. {
  322. s->rwstate = SSL_CERTIFICATE_SELECTION_PENDING;
  323. goto end;
  324. }
  325. if (ret <= 0) goto end;
  326. s->renegotiate = 2;
  327. s->state=SSL3_ST_SW_SRVR_HELLO_A;
  328. s->init_num=0;
  329. break;
  330. case SSL3_ST_SW_SRVR_HELLO_A:
  331. case SSL3_ST_SW_SRVR_HELLO_B:
  332. ret=ssl3_send_server_hello(s);
  333. if (ret <= 0) goto end;
  334. if (s->hit)
  335. {
  336. if (s->tlsext_ticket_expected)
  337. s->state=SSL3_ST_SW_SESSION_TICKET_A;
  338. else
  339. s->state=SSL3_ST_SW_CHANGE_A;
  340. }
  341. else
  342. s->state = SSL3_ST_SW_CERT_A;
  343. s->init_num = 0;
  344. break;
  345. case SSL3_ST_SW_CERT_A:
  346. case SSL3_ST_SW_CERT_B:
  347. if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
  348. {
  349. ret=ssl3_send_server_certificate(s);
  350. if (ret <= 0) goto end;
  351. if (s->s3->tmp.certificate_status_expected)
  352. s->state=SSL3_ST_SW_CERT_STATUS_A;
  353. else
  354. s->state=SSL3_ST_SW_KEY_EXCH_A;
  355. }
  356. else
  357. {
  358. skip = 1;
  359. s->state=SSL3_ST_SW_KEY_EXCH_A;
  360. }
  361. s->init_num=0;
  362. break;
  363. case SSL3_ST_SW_KEY_EXCH_A:
  364. case SSL3_ST_SW_KEY_EXCH_B:
  365. alg_a = s->s3->tmp.new_cipher->algorithm_auth;
  366. /* Send a ServerKeyExchange message if:
  367. * - The key exchange is ephemeral or anonymous
  368. * Diffie-Hellman.
  369. * - There is a PSK identity hint.
  370. *
  371. * TODO(davidben): This logic is currently duplicated
  372. * in d1_srvr.c. Fix this. In the meantime, keep them
  373. * in sync.
  374. */
  375. if (ssl_cipher_requires_server_key_exchange(s->s3->tmp.new_cipher) ||
  376. ((alg_a & SSL_aPSK) && s->psk_identity_hint))
  377. {
  378. ret=ssl3_send_server_key_exchange(s);
  379. if (ret <= 0) goto end;
  380. }
  381. else
  382. skip=1;
  383. s->state=SSL3_ST_SW_CERT_REQ_A;
  384. s->init_num=0;
  385. break;
  386. case SSL3_ST_SW_CERT_REQ_A:
  387. case SSL3_ST_SW_CERT_REQ_B:
  388. if (/* don't request cert unless asked for it: */
  389. !(s->verify_mode & SSL_VERIFY_PEER) ||
  390. /* Don't request a certificate if an obc was presented */
  391. ((s->verify_mode & SSL_VERIFY_PEER_IF_NO_OBC) &&
  392. s->s3->tlsext_channel_id_valid) ||
  393. /* if SSL_VERIFY_CLIENT_ONCE is set,
  394. * don't request cert during re-negotiation: */
  395. ((s->session->peer != NULL) &&
  396. (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
  397. /* never request cert in anonymous ciphersuites
  398. * (see section "Certificate request" in SSL 3 drafts
  399. * and in RFC 2246): */
  400. ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
  401. /* ... except when the application insists on verification
  402. * (against the specs, but s3_clnt.c accepts this for SSL 3) */
  403. !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
  404. /* With normal PSK Certificates and
  405. * Certificate Requests are omitted */
  406. (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
  407. {
  408. /* no cert request */
  409. skip=1;
  410. s->s3->tmp.cert_request=0;
  411. s->state=SSL3_ST_SW_SRVR_DONE_A;
  412. if (s->s3->handshake_buffer)
  413. if (!ssl3_digest_cached_records(s, free_handshake_buffer))
  414. return -1;
  415. }
  416. else
  417. {
  418. s->s3->tmp.cert_request=1;
  419. ret=ssl3_send_certificate_request(s);
  420. if (ret <= 0) goto end;
  421. #ifndef NETSCAPE_HANG_BUG
  422. s->state=SSL3_ST_SW_SRVR_DONE_A;
  423. #else
  424. s->state=SSL3_ST_SW_FLUSH;
  425. s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
  426. #endif
  427. s->init_num=0;
  428. }
  429. break;
  430. case SSL3_ST_SW_SRVR_DONE_A:
  431. case SSL3_ST_SW_SRVR_DONE_B:
  432. ret=ssl3_send_server_done(s);
  433. if (ret <= 0) goto end;
  434. s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
  435. s->state=SSL3_ST_SW_FLUSH;
  436. s->init_num=0;
  437. break;
  438. case SSL3_ST_SW_FLUSH:
  439. /* This code originally checked to see if
  440. * any data was pending using BIO_CTRL_INFO
  441. * and then flushed. This caused problems
  442. * as documented in PR#1939. The proposed
  443. * fix doesn't completely resolve this issue
  444. * as buggy implementations of BIO_CTRL_PENDING
  445. * still exist. So instead we just flush
  446. * unconditionally.
  447. */
  448. s->rwstate=SSL_WRITING;
  449. if (BIO_flush(s->wbio) <= 0)
  450. {
  451. ret= -1;
  452. goto end;
  453. }
  454. s->rwstate=SSL_NOTHING;
  455. s->state=s->s3->tmp.next_state;
  456. break;
  457. case SSL3_ST_SR_CERT_A:
  458. case SSL3_ST_SR_CERT_B:
  459. if (s->s3->tmp.cert_request)
  460. {
  461. ret=ssl3_get_client_certificate(s);
  462. if (ret <= 0) goto end;
  463. }
  464. s->init_num=0;
  465. s->state=SSL3_ST_SR_KEY_EXCH_A;
  466. break;
  467. case SSL3_ST_SR_KEY_EXCH_A:
  468. case SSL3_ST_SR_KEY_EXCH_B:
  469. ret=ssl3_get_client_key_exchange(s);
  470. if (ret <= 0)
  471. goto end;
  472. s->state=SSL3_ST_SR_CERT_VRFY_A;
  473. s->init_num=0;
  474. break;
  475. case SSL3_ST_SR_CERT_VRFY_A:
  476. case SSL3_ST_SR_CERT_VRFY_B:
  477. ret=ssl3_get_cert_verify(s);
  478. if (ret <= 0) goto end;
  479. s->state = SSL3_ST_SR_CHANGE;
  480. s->init_num=0;
  481. break;
  482. case SSL3_ST_SR_CHANGE: {
  483. char next_proto_neg = 0;
  484. char channel_id = 0;
  485. next_proto_neg = s->s3->next_proto_neg_seen;
  486. channel_id = s->s3->tlsext_channel_id_valid;
  487. /* At this point, the next message must be entirely
  488. * behind a ChangeCipherSpec. */
  489. if (!ssl3_expect_change_cipher_spec(s))
  490. {
  491. ret = -1;
  492. goto end;
  493. }
  494. if (next_proto_neg)
  495. s->state = SSL3_ST_SR_NEXT_PROTO_A;
  496. else if (channel_id)
  497. s->state = SSL3_ST_SR_CHANNEL_ID_A;
  498. else
  499. s->state = SSL3_ST_SR_FINISHED_A;
  500. break;
  501. }
  502. case SSL3_ST_SR_NEXT_PROTO_A:
  503. case SSL3_ST_SR_NEXT_PROTO_B:
  504. ret=ssl3_get_next_proto(s);
  505. if (ret <= 0) goto end;
  506. s->init_num = 0;
  507. if (s->s3->tlsext_channel_id_valid)
  508. s->state=SSL3_ST_SR_CHANNEL_ID_A;
  509. else
  510. s->state=SSL3_ST_SR_FINISHED_A;
  511. break;
  512. case SSL3_ST_SR_CHANNEL_ID_A:
  513. case SSL3_ST_SR_CHANNEL_ID_B:
  514. ret=ssl3_get_channel_id(s);
  515. if (ret <= 0) goto end;
  516. s->init_num = 0;
  517. s->state=SSL3_ST_SR_FINISHED_A;
  518. break;
  519. case SSL3_ST_SR_FINISHED_A:
  520. case SSL3_ST_SR_FINISHED_B:
  521. ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
  522. SSL3_ST_SR_FINISHED_B);
  523. if (ret <= 0) goto end;
  524. if (s->hit)
  525. s->state=SSL_ST_OK;
  526. else if (s->tlsext_ticket_expected)
  527. s->state=SSL3_ST_SW_SESSION_TICKET_A;
  528. else
  529. s->state=SSL3_ST_SW_CHANGE_A;
  530. /* If this is a full handshake with ChannelID then
  531. * record the hashshake hashes in |s->session| in case
  532. * we need them to verify a ChannelID signature on a
  533. * resumption of this session in the future. */
  534. if (!s->hit && s->s3->tlsext_channel_id_new)
  535. {
  536. ret = tls1_record_handshake_hashes_for_channel_id(s);
  537. if (ret <= 0) goto end;
  538. }
  539. s->init_num=0;
  540. break;
  541. case SSL3_ST_SW_SESSION_TICKET_A:
  542. case SSL3_ST_SW_SESSION_TICKET_B:
  543. ret=ssl3_send_new_session_ticket(s);
  544. if (ret <= 0) goto end;
  545. s->state=SSL3_ST_SW_CHANGE_A;
  546. s->init_num=0;
  547. break;
  548. #if 0
  549. // TODO(davidben): Implement OCSP stapling on the server.
  550. case SSL3_ST_SW_CERT_STATUS_A:
  551. case SSL3_ST_SW_CERT_STATUS_B:
  552. ret=ssl3_send_cert_status(s);
  553. if (ret <= 0) goto end;
  554. s->state=SSL3_ST_SW_KEY_EXCH_A;
  555. s->init_num=0;
  556. break;
  557. #endif
  558. case SSL3_ST_SW_CHANGE_A:
  559. case SSL3_ST_SW_CHANGE_B:
  560. s->session->cipher=s->s3->tmp.new_cipher;
  561. if (!s->method->ssl3_enc->setup_key_block(s))
  562. { ret= -1; goto end; }
  563. ret=ssl3_send_change_cipher_spec(s,
  564. SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
  565. if (ret <= 0) goto end;
  566. s->state=SSL3_ST_SW_FINISHED_A;
  567. s->init_num=0;
  568. if (!s->method->ssl3_enc->change_cipher_state(s,
  569. SSL3_CHANGE_CIPHER_SERVER_WRITE))
  570. {
  571. ret= -1;
  572. goto end;
  573. }
  574. break;
  575. case SSL3_ST_SW_FINISHED_A:
  576. case SSL3_ST_SW_FINISHED_B:
  577. ret=ssl3_send_finished(s,
  578. SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
  579. s->method->ssl3_enc->server_finished_label,
  580. s->method->ssl3_enc->server_finished_label_len);
  581. if (ret <= 0) goto end;
  582. s->state = SSL3_ST_SW_FLUSH;
  583. if (s->hit)
  584. s->s3->tmp.next_state = SSL3_ST_SR_CHANGE;
  585. else
  586. s->s3->tmp.next_state = SSL_ST_OK;
  587. s->init_num=0;
  588. break;
  589. case SSL_ST_OK:
  590. /* clean a few things up */
  591. ssl3_cleanup_key_block(s);
  592. BUF_MEM_free(s->init_buf);
  593. s->init_buf=NULL;
  594. /* remove buffering on output */
  595. ssl_free_wbio_buffer(s);
  596. s->init_num=0;
  597. /* If we aren't retaining peer certificates then we can
  598. * discard it now. */
  599. if (s->session->peer && s->ctx->retain_only_sha256_of_client_certs)
  600. {
  601. X509_free(s->session->peer);
  602. s->session->peer = NULL;
  603. }
  604. if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
  605. {
  606. s->renegotiate=0;
  607. s->new_session=0;
  608. ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
  609. s->ctx->stats.sess_accept_good++;
  610. /* s->server=1; */
  611. s->handshake_func=ssl3_accept;
  612. if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
  613. }
  614. ret = 1;
  615. goto end;
  616. /* break; */
  617. default:
  618. OPENSSL_PUT_ERROR(SSL, ssl3_accept, SSL_R_UNKNOWN_STATE);
  619. ret= -1;
  620. goto end;
  621. /* break; */
  622. }
  623. if (!s->s3->tmp.reuse_message && !skip)
  624. {
  625. if (s->debug)
  626. {
  627. if ((ret=BIO_flush(s->wbio)) <= 0)
  628. goto end;
  629. }
  630. if ((cb != NULL) && (s->state != state))
  631. {
  632. new_state=s->state;
  633. s->state=state;
  634. cb(s,SSL_CB_ACCEPT_LOOP,1);
  635. s->state=new_state;
  636. }
  637. }
  638. skip=0;
  639. }
  640. end:
  641. /* BIO_flush(s->wbio); */
  642. s->in_handshake--;
  643. if (cb != NULL)
  644. cb(s,SSL_CB_ACCEPT_EXIT,ret);
  645. return(ret);
  646. }
  647. int ssl3_send_hello_request(SSL *s)
  648. {
  649. if (s->state == SSL3_ST_SW_HELLO_REQ_A)
  650. {
  651. ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
  652. s->state=SSL3_ST_SW_HELLO_REQ_B;
  653. }
  654. /* SSL3_ST_SW_HELLO_REQ_B */
  655. return ssl_do_write(s);
  656. }
  657. int ssl3_get_client_hello(SSL *s)
  658. {
  659. int i,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
  660. long n;
  661. const SSL_CIPHER *c;
  662. STACK_OF(SSL_CIPHER) *ciphers=NULL;
  663. struct ssl_early_callback_ctx early_ctx;
  664. CBS client_hello;
  665. uint16_t client_version;
  666. CBS client_random, session_id, cipher_suites, compression_methods;
  667. /* We do this so that we will respond with our native type.
  668. * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
  669. * This down switching should be handled by a different method.
  670. * If we are SSLv3, we will respond with SSLv3, even if prompted with
  671. * TLSv1.
  672. */
  673. switch (s->state) {
  674. case SSL3_ST_SR_CLNT_HELLO_A:
  675. case SSL3_ST_SR_CLNT_HELLO_B:
  676. s->first_packet=1;
  677. n=s->method->ssl_get_message(s,
  678. SSL3_ST_SR_CLNT_HELLO_A,
  679. SSL3_ST_SR_CLNT_HELLO_B,
  680. SSL3_MT_CLIENT_HELLO,
  681. SSL3_RT_MAX_PLAIN_LENGTH,
  682. SSL_GET_MESSAGE_HASH_MESSAGE,
  683. &ok);
  684. if (!ok) return((int)n);
  685. s->first_packet=0;
  686. /* If we require cookies and this ClientHello doesn't
  687. * contain one, just return since we do not want to
  688. * allocate any memory yet. So check cookie length...
  689. */
  690. if (SSL_IS_DTLS(s) && (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE))
  691. {
  692. CBS session_id;
  693. uint8_t cookie_length;
  694. CBS_init(&client_hello, s->init_msg, n);
  695. if (!CBS_skip(&client_hello, 2 + SSL3_RANDOM_SIZE) ||
  696. !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
  697. !CBS_get_u8(&client_hello, &cookie_length))
  698. {
  699. al = SSL_AD_DECODE_ERROR;
  700. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
  701. goto f_err;
  702. }
  703. if (cookie_length == 0)
  704. return 1;
  705. }
  706. s->state = SSL3_ST_SR_CLNT_HELLO_C;
  707. /* fallthrough */
  708. case SSL3_ST_SR_CLNT_HELLO_C:
  709. case SSL3_ST_SR_CLNT_HELLO_D:
  710. /* We have previously parsed the ClientHello message,
  711. * and can't call ssl_get_message again without hashing
  712. * the message into the Finished digest again. */
  713. n = s->init_num;
  714. memset(&early_ctx, 0, sizeof(early_ctx));
  715. early_ctx.ssl = s;
  716. early_ctx.client_hello = s->init_msg;
  717. early_ctx.client_hello_len = n;
  718. if (!ssl_early_callback_init(&early_ctx))
  719. {
  720. al = SSL_AD_DECODE_ERROR;
  721. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CLIENTHELLO_PARSE_FAILED);
  722. goto f_err;
  723. }
  724. if (s->state == SSL3_ST_SR_CLNT_HELLO_C &&
  725. s->ctx->select_certificate_cb != NULL)
  726. {
  727. int ret;
  728. s->state = SSL3_ST_SR_CLNT_HELLO_D;
  729. ret = s->ctx->select_certificate_cb(&early_ctx);
  730. if (ret == 0)
  731. return CERTIFICATE_SELECTION_PENDING;
  732. else if (ret == -1)
  733. {
  734. /* Connection rejected. */
  735. al = SSL_AD_ACCESS_DENIED;
  736. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CONNECTION_REJECTED);
  737. goto f_err;
  738. }
  739. }
  740. s->state = SSL3_ST_SR_CLNT_HELLO_D;
  741. break;
  742. default:
  743. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_UNKNOWN_STATE);
  744. return -1;
  745. }
  746. CBS_init(&client_hello, s->init_msg, n);
  747. if (!CBS_get_u16(&client_hello, &client_version) ||
  748. !CBS_get_bytes(&client_hello, &client_random, SSL3_RANDOM_SIZE) ||
  749. !CBS_get_u8_length_prefixed(&client_hello, &session_id) ||
  750. CBS_len(&session_id) > SSL_MAX_SSL_SESSION_ID_LENGTH)
  751. {
  752. al = SSL_AD_DECODE_ERROR;
  753. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
  754. goto f_err;
  755. }
  756. /* use version from inside client hello, not from record header
  757. * (may differ: see RFC 2246, Appendix E, second paragraph) */
  758. s->client_version = client_version;
  759. if (SSL_IS_DTLS(s) ? (s->client_version > s->version &&
  760. s->method->version != DTLS_ANY_VERSION)
  761. : (s->client_version < s->version))
  762. {
  763. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
  764. if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
  765. !s->enc_write_ctx && !s->write_hash)
  766. {
  767. /* similar to ssl3_get_record, send alert using remote version number */
  768. s->version = s->client_version;
  769. }
  770. al = SSL_AD_PROTOCOL_VERSION;
  771. goto f_err;
  772. }
  773. /* Load the client random. */
  774. memcpy(s->s3->client_random, CBS_data(&client_random), SSL3_RANDOM_SIZE);
  775. s->hit=0;
  776. /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
  777. * 0.9.7 and later allow this by default, but optionally ignore resumption requests
  778. * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
  779. * than a change to default behavior so that applications relying on this for security
  780. * won't even compile against older library versions).
  781. *
  782. * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
  783. * renegotiation but not a new session (s->new_session remains unset): for servers,
  784. * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
  785. * setting will be ignored.
  786. */
  787. if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
  788. {
  789. if (!ssl_get_new_session(s,1))
  790. goto err;
  791. }
  792. else
  793. {
  794. i = ssl_get_prev_session(s, &early_ctx);
  795. if (i == PENDING_SESSION)
  796. {
  797. ret = PENDING_SESSION;
  798. goto err;
  799. }
  800. else if (i == -1)
  801. {
  802. goto err;
  803. }
  804. /* Only resume if the session's version matches the negotiated
  805. * version: most clients do not accept a mismatch. */
  806. if (i == 1 && s->version == s->session->ssl_version)
  807. {
  808. s->hit = 1;
  809. }
  810. else
  811. {
  812. /* No session was found or it was unacceptable. */
  813. if (!ssl_get_new_session(s, 1))
  814. goto err;
  815. }
  816. }
  817. if (SSL_IS_DTLS(s))
  818. {
  819. CBS cookie;
  820. if (!CBS_get_u8_length_prefixed(&client_hello, &cookie) ||
  821. CBS_len(&cookie) > DTLS1_COOKIE_LENGTH)
  822. {
  823. al = SSL_AD_DECODE_ERROR;
  824. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
  825. goto f_err;
  826. }
  827. /* Verify the cookie if appropriate option is set. */
  828. if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
  829. CBS_len(&cookie) > 0)
  830. {
  831. if (s->ctx->app_verify_cookie_cb != NULL)
  832. {
  833. if (s->ctx->app_verify_cookie_cb(s,
  834. CBS_data(&cookie), CBS_len(&cookie)) == 0)
  835. {
  836. al=SSL_AD_HANDSHAKE_FAILURE;
  837. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
  838. goto f_err;
  839. }
  840. /* else cookie verification succeeded */
  841. }
  842. else if (!CBS_mem_equal(&cookie, s->d1->cookie, s->d1->cookie_len))
  843. {
  844. /* default verification */
  845. al=SSL_AD_HANDSHAKE_FAILURE;
  846. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_COOKIE_MISMATCH);
  847. goto f_err;
  848. }
  849. /* Set to -2 so if successful we return 2 and
  850. * don't send HelloVerifyRequest. */
  851. ret = -2;
  852. }
  853. if (s->method->version == DTLS_ANY_VERSION)
  854. {
  855. /* Select version to use */
  856. if (s->client_version <= DTLS1_2_VERSION &&
  857. !(s->options & SSL_OP_NO_DTLSv1_2))
  858. {
  859. s->version = DTLS1_2_VERSION;
  860. s->method = DTLSv1_2_server_method();
  861. }
  862. else if (s->client_version <= DTLS1_VERSION &&
  863. !(s->options & SSL_OP_NO_DTLSv1))
  864. {
  865. s->version = DTLS1_VERSION;
  866. s->method = DTLSv1_server_method();
  867. }
  868. else
  869. {
  870. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_WRONG_VERSION_NUMBER);
  871. s->version = s->client_version;
  872. al = SSL_AD_PROTOCOL_VERSION;
  873. goto f_err;
  874. }
  875. s->session->ssl_version = s->version;
  876. }
  877. }
  878. if (!CBS_get_u16_length_prefixed(&client_hello, &cipher_suites) ||
  879. !CBS_get_u8_length_prefixed(&client_hello, &compression_methods) ||
  880. CBS_len(&compression_methods) == 0)
  881. {
  882. al = SSL_AD_DECODE_ERROR;
  883. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_DECODE_ERROR);
  884. goto f_err;
  885. }
  886. /* TODO(davidben): Per spec, cipher_suites can never be empty
  887. * (specified at the ClientHello structure level). This logic
  888. * allows it to be empty if resuming a session. Can we always
  889. * require non-empty? If a client sends empty cipher_suites
  890. * because it's resuming a session, it could always fail to
  891. * resume a session, so it's unlikely to actually work. */
  892. if (CBS_len(&cipher_suites) == 0 && CBS_len(&session_id) != 0)
  893. {
  894. /* We need a cipher if we are not resuming a session. */
  895. al = SSL_AD_ILLEGAL_PARAMETER;
  896. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_SPECIFIED);
  897. goto f_err;
  898. }
  899. ciphers = ssl_bytes_to_cipher_list(s, &cipher_suites);
  900. if (ciphers == NULL)
  901. {
  902. goto err;
  903. }
  904. /* If it is a hit, check that the cipher is in the list */
  905. if (s->hit && CBS_len(&cipher_suites) > 0)
  906. {
  907. size_t j;
  908. int found_cipher = 0;
  909. unsigned long id = s->session->cipher->id;
  910. for (j = 0; j < sk_SSL_CIPHER_num(ciphers); j++)
  911. {
  912. c = sk_SSL_CIPHER_value(ciphers, j);
  913. if (c->id == id)
  914. {
  915. found_cipher = 1;
  916. break;
  917. }
  918. }
  919. if (!found_cipher)
  920. {
  921. /* we need to have the cipher in the cipher
  922. * list if we are asked to reuse it */
  923. al=SSL_AD_ILLEGAL_PARAMETER;
  924. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_REQUIRED_CIPHER_MISSING);
  925. goto f_err;
  926. }
  927. }
  928. /* Only null compression is supported. */
  929. if (memchr(CBS_data(&compression_methods), 0,
  930. CBS_len(&compression_methods)) == NULL)
  931. {
  932. al = SSL_AD_ILLEGAL_PARAMETER;
  933. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_COMPRESSION_SPECIFIED);
  934. goto f_err;
  935. }
  936. /* TLS extensions*/
  937. if (s->version >= SSL3_VERSION)
  938. {
  939. if (!ssl_parse_clienthello_tlsext(s, &client_hello))
  940. {
  941. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_PARSE_TLSEXT);
  942. goto err;
  943. }
  944. }
  945. /* There should be nothing left over in the record. */
  946. if (CBS_len(&client_hello) != 0)
  947. {
  948. /* wrong packet length */
  949. al=SSL_AD_DECODE_ERROR;
  950. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_BAD_PACKET_LENGTH);
  951. goto f_err;
  952. }
  953. /* Check if we want to use external pre-shared secret for this
  954. * handshake for not reused session only. We need to generate
  955. * server_random before calling tls_session_secret_cb in order to allow
  956. * SessionTicket processing to use it in key derivation. */
  957. {
  958. unsigned char *pos;
  959. pos=s->s3->server_random;
  960. if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
  961. {
  962. goto f_err;
  963. }
  964. }
  965. if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
  966. {
  967. const SSL_CIPHER *pref_cipher=NULL;
  968. s->session->master_key_length=sizeof(s->session->master_key);
  969. if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
  970. ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
  971. {
  972. s->hit=1;
  973. s->session->verify_result=X509_V_OK;
  974. /* check if some cipher was preferred by call back */
  975. pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, ciphers, ssl_get_cipher_preferences(s));
  976. if (pref_cipher == NULL)
  977. {
  978. al=SSL_AD_HANDSHAKE_FAILURE;
  979. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
  980. goto f_err;
  981. }
  982. s->session->cipher=pref_cipher;
  983. if (s->cipher_list)
  984. ssl_cipher_preference_list_free(s->cipher_list);
  985. if (s->cipher_list_by_id)
  986. sk_SSL_CIPHER_free(s->cipher_list_by_id);
  987. s->cipher_list = ssl_cipher_preference_list_from_ciphers(ciphers);
  988. s->cipher_list_by_id = sk_SSL_CIPHER_dup(ciphers);
  989. }
  990. }
  991. /* Given ciphers and SSL_get_ciphers, we must pick a cipher */
  992. if (!s->hit)
  993. {
  994. if (ciphers == NULL)
  995. {
  996. al=SSL_AD_ILLEGAL_PARAMETER;
  997. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_CIPHERS_PASSED);
  998. goto f_err;
  999. }
  1000. /* Let cert callback update server certificates if required */
  1001. if (s->cert->cert_cb)
  1002. {
  1003. int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
  1004. if (rv == 0)
  1005. {
  1006. al=SSL_AD_INTERNAL_ERROR;
  1007. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_CERT_CB_ERROR);
  1008. goto f_err;
  1009. }
  1010. if (rv < 0)
  1011. {
  1012. s->rwstate=SSL_X509_LOOKUP;
  1013. goto err;
  1014. }
  1015. s->rwstate = SSL_NOTHING;
  1016. }
  1017. c=ssl3_choose_cipher(s, ciphers, ssl_get_cipher_preferences(s));
  1018. if (c == NULL)
  1019. {
  1020. al=SSL_AD_HANDSHAKE_FAILURE;
  1021. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_hello, SSL_R_NO_SHARED_CIPHER);
  1022. goto f_err;
  1023. }
  1024. s->s3->tmp.new_cipher=c;
  1025. }
  1026. else
  1027. {
  1028. /* Session-id reuse */
  1029. s->s3->tmp.new_cipher=s->session->cipher;
  1030. }
  1031. if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
  1032. {
  1033. if (!ssl3_digest_cached_records(s, free_handshake_buffer))
  1034. goto f_err;
  1035. }
  1036. /* we now have the following setup.
  1037. * client_random
  1038. * cipher_list - our prefered list of ciphers
  1039. * ciphers - the clients prefered list of ciphers
  1040. * compression - basically ignored right now
  1041. * ssl version is set - sslv3
  1042. * s->session - The ssl session has been setup.
  1043. * s->hit - session reuse flag
  1044. * s->tmp.new_cipher - the new cipher to use.
  1045. */
  1046. if (ret < 0) ret=-ret;
  1047. if (0)
  1048. {
  1049. f_err:
  1050. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  1051. }
  1052. err:
  1053. if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
  1054. return ret;
  1055. }
  1056. int ssl3_send_server_hello(SSL *s)
  1057. {
  1058. unsigned char *buf;
  1059. unsigned char *p,*d;
  1060. int sl;
  1061. unsigned long l;
  1062. if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
  1063. {
  1064. /* We only accept ChannelIDs on connections with ECDHE in order
  1065. * to avoid a known attack while we fix ChannelID itself. */
  1066. if (s->s3->tlsext_channel_id_valid &&
  1067. (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kEECDH) == 0)
  1068. s->s3->tlsext_channel_id_valid = 0;
  1069. /* If this is a resumption and the original handshake didn't
  1070. * support ChannelID then we didn't record the original
  1071. * handshake hashes in the session and so cannot resume with
  1072. * ChannelIDs. */
  1073. if (s->hit &&
  1074. s->s3->tlsext_channel_id_new &&
  1075. s->session->original_handshake_hash_len == 0)
  1076. s->s3->tlsext_channel_id_valid = 0;
  1077. buf=(unsigned char *)s->init_buf->data;
  1078. /* Do the message type and length last */
  1079. d=p= ssl_handshake_start(s);
  1080. *(p++)=s->version>>8;
  1081. *(p++)=s->version&0xff;
  1082. /* Random stuff */
  1083. memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
  1084. p+=SSL3_RANDOM_SIZE;
  1085. /* There are several cases for the session ID to send
  1086. * back in the server hello:
  1087. * - For session reuse from the session cache,
  1088. * we send back the old session ID.
  1089. * - If stateless session reuse (using a session ticket)
  1090. * is successful, we send back the client's "session ID"
  1091. * (which doesn't actually identify the session).
  1092. * - If it is a new session, we send back the new
  1093. * session ID.
  1094. * - However, if we want the new session to be single-use,
  1095. * we send back a 0-length session ID.
  1096. * s->hit is non-zero in either case of session reuse,
  1097. * so the following won't overwrite an ID that we're supposed
  1098. * to send back.
  1099. */
  1100. if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
  1101. && !s->hit)
  1102. s->session->session_id_length=0;
  1103. sl=s->session->session_id_length;
  1104. if (sl > (int)sizeof(s->session->session_id))
  1105. {
  1106. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
  1107. return -1;
  1108. }
  1109. *(p++)=sl;
  1110. memcpy(p,s->session->session_id,sl);
  1111. p+=sl;
  1112. /* put the cipher */
  1113. s2n(ssl3_get_cipher_value(s->s3->tmp.new_cipher), p);
  1114. /* put the compression method */
  1115. *(p++)=0;
  1116. if (ssl_prepare_serverhello_tlsext(s) <= 0)
  1117. {
  1118. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, SSL_R_SERVERHELLO_TLSEXT);
  1119. return -1;
  1120. }
  1121. if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
  1122. {
  1123. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_hello, ERR_R_INTERNAL_ERROR);
  1124. return -1;
  1125. }
  1126. /* do the header */
  1127. l=(p-d);
  1128. ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
  1129. s->state=SSL3_ST_SW_SRVR_HELLO_B;
  1130. }
  1131. /* SSL3_ST_SW_SRVR_HELLO_B */
  1132. return ssl_do_write(s);
  1133. }
  1134. int ssl3_send_server_done(SSL *s)
  1135. {
  1136. if (s->state == SSL3_ST_SW_SRVR_DONE_A)
  1137. {
  1138. ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
  1139. s->state = SSL3_ST_SW_SRVR_DONE_B;
  1140. }
  1141. /* SSL3_ST_SW_SRVR_DONE_B */
  1142. return ssl_do_write(s);
  1143. }
  1144. int ssl3_send_server_key_exchange(SSL *s)
  1145. {
  1146. unsigned char *q;
  1147. int j,num;
  1148. unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
  1149. unsigned int u;
  1150. DH *dh=NULL,*dhp;
  1151. EC_KEY *ecdh=NULL, *ecdhp;
  1152. unsigned char *encodedPoint = NULL;
  1153. int encodedlen = 0;
  1154. int curve_id = 0;
  1155. BN_CTX *bn_ctx = NULL;
  1156. const char* psk_identity_hint = NULL;
  1157. size_t psk_identity_hint_len = 0;
  1158. EVP_PKEY *pkey;
  1159. const EVP_MD *md = NULL;
  1160. unsigned char *p,*d;
  1161. int al,i;
  1162. unsigned long alg_k;
  1163. unsigned long alg_a;
  1164. int n;
  1165. CERT *cert;
  1166. BIGNUM *r[4];
  1167. int nr[4],kn;
  1168. BUF_MEM *buf;
  1169. EVP_MD_CTX md_ctx;
  1170. EVP_MD_CTX_init(&md_ctx);
  1171. if (s->state == SSL3_ST_SW_KEY_EXCH_A)
  1172. {
  1173. alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
  1174. alg_a=s->s3->tmp.new_cipher->algorithm_auth;
  1175. cert=s->cert;
  1176. buf=s->init_buf;
  1177. r[0]=r[1]=r[2]=r[3]=NULL;
  1178. n=0;
  1179. if (alg_a & SSL_aPSK)
  1180. {
  1181. /* size for PSK identity hint */
  1182. psk_identity_hint = s->psk_identity_hint;
  1183. if (psk_identity_hint)
  1184. psk_identity_hint_len = strlen(psk_identity_hint);
  1185. else
  1186. psk_identity_hint_len = 0;
  1187. n+=2+psk_identity_hint_len;
  1188. }
  1189. if (alg_k & SSL_kEDH)
  1190. {
  1191. dhp=cert->dh_tmp;
  1192. if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
  1193. dhp=s->cert->dh_tmp_cb(s, 0, 1024);
  1194. if (dhp == NULL)
  1195. {
  1196. al=SSL_AD_HANDSHAKE_FAILURE;
  1197. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
  1198. goto f_err;
  1199. }
  1200. if (s->s3->tmp.dh != NULL)
  1201. {
  1202. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
  1203. goto err;
  1204. }
  1205. if ((dh=DHparams_dup(dhp)) == NULL)
  1206. {
  1207. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
  1208. goto err;
  1209. }
  1210. s->s3->tmp.dh=dh;
  1211. if ((dhp->pub_key == NULL ||
  1212. dhp->priv_key == NULL ||
  1213. (s->options & SSL_OP_SINGLE_DH_USE)))
  1214. {
  1215. if(!DH_generate_key(dh))
  1216. {
  1217. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
  1218. goto err;
  1219. }
  1220. }
  1221. else
  1222. {
  1223. dh->pub_key=BN_dup(dhp->pub_key);
  1224. dh->priv_key=BN_dup(dhp->priv_key);
  1225. if ((dh->pub_key == NULL) ||
  1226. (dh->priv_key == NULL))
  1227. {
  1228. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_DH_LIB);
  1229. goto err;
  1230. }
  1231. }
  1232. r[0]=dh->p;
  1233. r[1]=dh->g;
  1234. r[2]=dh->pub_key;
  1235. }
  1236. else
  1237. if (alg_k & SSL_kEECDH)
  1238. {
  1239. const EC_GROUP *group;
  1240. ecdhp=cert->ecdh_tmp;
  1241. if (s->cert->ecdh_tmp_auto)
  1242. {
  1243. /* Get NID of appropriate shared curve */
  1244. int nid = tls1_get_shared_curve(s);
  1245. if (nid != NID_undef)
  1246. ecdhp = EC_KEY_new_by_curve_name(nid);
  1247. }
  1248. else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
  1249. {
  1250. ecdhp = s->cert->ecdh_tmp_cb(s, 0, 1024);
  1251. }
  1252. if (ecdhp == NULL)
  1253. {
  1254. al=SSL_AD_HANDSHAKE_FAILURE;
  1255. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_MISSING_TMP_ECDH_KEY);
  1256. goto f_err;
  1257. }
  1258. if (s->s3->tmp.ecdh != NULL)
  1259. {
  1260. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
  1261. goto err;
  1262. }
  1263. /* Duplicate the ECDH structure. */
  1264. if (ecdhp == NULL)
  1265. {
  1266. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1267. goto err;
  1268. }
  1269. if (s->cert->ecdh_tmp_auto)
  1270. ecdh = ecdhp;
  1271. else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
  1272. {
  1273. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1274. goto err;
  1275. }
  1276. s->s3->tmp.ecdh=ecdh;
  1277. if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
  1278. (EC_KEY_get0_private_key(ecdh) == NULL) ||
  1279. (s->options & SSL_OP_SINGLE_ECDH_USE))
  1280. {
  1281. if(!EC_KEY_generate_key(ecdh))
  1282. {
  1283. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1284. goto err;
  1285. }
  1286. }
  1287. if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
  1288. (EC_KEY_get0_public_key(ecdh) == NULL) ||
  1289. (EC_KEY_get0_private_key(ecdh) == NULL))
  1290. {
  1291. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1292. goto err;
  1293. }
  1294. /* XXX: For now, we only support ephemeral ECDH
  1295. * keys over named (not generic) curves. For
  1296. * supported named curves, curve_id is non-zero.
  1297. */
  1298. if ((curve_id =
  1299. tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
  1300. == 0)
  1301. {
  1302. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
  1303. goto err;
  1304. }
  1305. /* Encode the public key.
  1306. * First check the size of encoding and
  1307. * allocate memory accordingly.
  1308. */
  1309. encodedlen = EC_POINT_point2oct(group,
  1310. EC_KEY_get0_public_key(ecdh),
  1311. POINT_CONVERSION_UNCOMPRESSED,
  1312. NULL, 0, NULL);
  1313. encodedPoint = (unsigned char *)
  1314. OPENSSL_malloc(encodedlen*sizeof(unsigned char));
  1315. bn_ctx = BN_CTX_new();
  1316. if ((encodedPoint == NULL) || (bn_ctx == NULL))
  1317. {
  1318. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_MALLOC_FAILURE);
  1319. goto err;
  1320. }
  1321. encodedlen = EC_POINT_point2oct(group,
  1322. EC_KEY_get0_public_key(ecdh),
  1323. POINT_CONVERSION_UNCOMPRESSED,
  1324. encodedPoint, encodedlen, bn_ctx);
  1325. if (encodedlen == 0)
  1326. {
  1327. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_ECDH_LIB);
  1328. goto err;
  1329. }
  1330. BN_CTX_free(bn_ctx); bn_ctx=NULL;
  1331. /* XXX: For now, we only support named (not
  1332. * generic) curves in ECDH ephemeral key exchanges.
  1333. * In this situation, we need four additional bytes
  1334. * to encode the entire ServerECDHParams
  1335. * structure.
  1336. */
  1337. n += 4 + encodedlen;
  1338. /* We'll generate the serverKeyExchange message
  1339. * explicitly so we can set these to NULLs
  1340. */
  1341. r[0]=NULL;
  1342. r[1]=NULL;
  1343. r[2]=NULL;
  1344. r[3]=NULL;
  1345. }
  1346. else
  1347. if (!(alg_k & SSL_kPSK))
  1348. {
  1349. al=SSL_AD_HANDSHAKE_FAILURE;
  1350. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
  1351. goto f_err;
  1352. }
  1353. for (i=0; i < 4 && r[i] != NULL; i++)
  1354. {
  1355. nr[i]=BN_num_bytes(r[i]);
  1356. n+=2+nr[i];
  1357. }
  1358. if (ssl_cipher_has_server_public_key(s->s3->tmp.new_cipher))
  1359. {
  1360. if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
  1361. == NULL)
  1362. {
  1363. al=SSL_AD_DECODE_ERROR;
  1364. goto f_err;
  1365. }
  1366. kn=EVP_PKEY_size(pkey);
  1367. }
  1368. else
  1369. {
  1370. pkey=NULL;
  1371. kn=0;
  1372. }
  1373. if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
  1374. {
  1375. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_BUF);
  1376. goto err;
  1377. }
  1378. d = p = ssl_handshake_start(s);
  1379. for (i=0; i < 4 && r[i] != NULL; i++)
  1380. {
  1381. s2n(nr[i],p);
  1382. BN_bn2bin(r[i],p);
  1383. p+=nr[i];
  1384. }
  1385. /* Note: ECDHE PSK ciphersuites use SSL_kEECDH and SSL_aPSK.
  1386. * When one of them is used, the server key exchange record needs to have both
  1387. * the psk_identity_hint and the ServerECDHParams. */
  1388. if (alg_a & SSL_aPSK)
  1389. {
  1390. /* copy PSK identity hint (if provided) */
  1391. s2n(psk_identity_hint_len, p);
  1392. if (psk_identity_hint_len > 0)
  1393. {
  1394. memcpy(p, psk_identity_hint, psk_identity_hint_len);
  1395. p+=psk_identity_hint_len;
  1396. }
  1397. }
  1398. if (alg_k & SSL_kEECDH)
  1399. {
  1400. /* XXX: For now, we only support named (not generic) curves.
  1401. * In this situation, the serverKeyExchange message has:
  1402. * [1 byte CurveType], [2 byte CurveName]
  1403. * [1 byte length of encoded point], followed by
  1404. * the actual encoded point itself
  1405. */
  1406. *p = NAMED_CURVE_TYPE;
  1407. p += 1;
  1408. *p = 0;
  1409. p += 1;
  1410. *p = curve_id;
  1411. p += 1;
  1412. *p = encodedlen;
  1413. p += 1;
  1414. memcpy((unsigned char*)p,
  1415. (unsigned char *)encodedPoint,
  1416. encodedlen);
  1417. OPENSSL_free(encodedPoint);
  1418. encodedPoint = NULL;
  1419. p += encodedlen;
  1420. }
  1421. /* not anonymous */
  1422. if (pkey != NULL)
  1423. {
  1424. /* n is the length of the params, they start at &(d[4])
  1425. * and p points to the space at the end. */
  1426. if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
  1427. {
  1428. q=md_buf;
  1429. j=0;
  1430. for (num=2; num > 0; num--)
  1431. {
  1432. EVP_DigestInit_ex(&md_ctx,
  1433. (num == 2) ? EVP_md5() : EVP_sha1(), NULL);
  1434. EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
  1435. EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
  1436. EVP_DigestUpdate(&md_ctx,d,n);
  1437. EVP_DigestFinal_ex(&md_ctx,q,
  1438. (unsigned int *)&i);
  1439. q+=i;
  1440. j+=i;
  1441. }
  1442. if (RSA_sign(NID_md5_sha1, md_buf, j,
  1443. &(p[2]), &u, pkey->pkey.rsa) <= 0)
  1444. {
  1445. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_RSA);
  1446. goto err;
  1447. }
  1448. s2n(u,p);
  1449. n+=u+2;
  1450. }
  1451. else
  1452. if (md)
  1453. {
  1454. size_t sig_len = EVP_PKEY_size(pkey);
  1455. /* send signature algorithm */
  1456. if (SSL_USE_SIGALGS(s))
  1457. {
  1458. if (!tls12_get_sigandhash(p, pkey, md))
  1459. {
  1460. /* Should never happen */
  1461. al=SSL_AD_INTERNAL_ERROR;
  1462. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_R_INTERNAL_ERROR);
  1463. goto f_err;
  1464. }
  1465. p+=2;
  1466. }
  1467. if (!EVP_DigestSignInit(&md_ctx, NULL, md, NULL, pkey) ||
  1468. !EVP_DigestSignUpdate(&md_ctx, s->s3->client_random, SSL3_RANDOM_SIZE) ||
  1469. !EVP_DigestSignUpdate(&md_ctx, s->s3->server_random, SSL3_RANDOM_SIZE) ||
  1470. !EVP_DigestSignUpdate(&md_ctx, d, n) ||
  1471. !EVP_DigestSignFinal(&md_ctx, &p[2], &sig_len))
  1472. {
  1473. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, ERR_LIB_EVP);
  1474. goto err;
  1475. }
  1476. s2n(sig_len, p);
  1477. n += sig_len + 2;
  1478. if (SSL_USE_SIGALGS(s))
  1479. n += 2;
  1480. }
  1481. else
  1482. {
  1483. /* Is this error check actually needed? */
  1484. al=SSL_AD_HANDSHAKE_FAILURE;
  1485. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_key_exchange, SSL_R_UNKNOWN_PKEY_TYPE);
  1486. goto f_err;
  1487. }
  1488. }
  1489. ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
  1490. }
  1491. s->state = SSL3_ST_SW_KEY_EXCH_B;
  1492. EVP_MD_CTX_cleanup(&md_ctx);
  1493. return ssl_do_write(s);
  1494. f_err:
  1495. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  1496. err:
  1497. if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
  1498. BN_CTX_free(bn_ctx);
  1499. EVP_MD_CTX_cleanup(&md_ctx);
  1500. return(-1);
  1501. }
  1502. int ssl3_send_certificate_request(SSL *s)
  1503. {
  1504. unsigned char *p,*d;
  1505. size_t i;
  1506. int j,nl,off,n;
  1507. STACK_OF(X509_NAME) *sk=NULL;
  1508. X509_NAME *name;
  1509. BUF_MEM *buf;
  1510. if (s->state == SSL3_ST_SW_CERT_REQ_A)
  1511. {
  1512. buf=s->init_buf;
  1513. d=p=ssl_handshake_start(s);
  1514. /* get the list of acceptable cert types */
  1515. p++;
  1516. n=ssl3_get_req_cert_type(s,p);
  1517. d[0]=n;
  1518. p+=n;
  1519. n++;
  1520. if (SSL_USE_SIGALGS(s))
  1521. {
  1522. const unsigned char *psigs;
  1523. nl = tls12_get_psigalgs(s, &psigs);
  1524. s2n(nl, p);
  1525. memcpy(p, psigs, nl);
  1526. p += nl;
  1527. n += nl + 2;
  1528. }
  1529. off=n;
  1530. p+=2;
  1531. n+=2;
  1532. sk=SSL_get_client_CA_list(s);
  1533. nl=0;
  1534. if (sk != NULL)
  1535. {
  1536. for (i=0; i<sk_X509_NAME_num(sk); i++)
  1537. {
  1538. name=sk_X509_NAME_value(sk,i);
  1539. j=i2d_X509_NAME(name,NULL);
  1540. if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
  1541. {
  1542. OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
  1543. goto err;
  1544. }
  1545. p = ssl_handshake_start(s) + n;
  1546. s2n(j,p);
  1547. i2d_X509_NAME(name,&p);
  1548. n+=2+j;
  1549. nl+=2+j;
  1550. }
  1551. }
  1552. /* else no CA names */
  1553. p = ssl_handshake_start(s) + off;
  1554. s2n(nl,p);
  1555. ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
  1556. #ifdef NETSCAPE_HANG_BUG
  1557. if (!SSL_IS_DTLS(s))
  1558. {
  1559. if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
  1560. {
  1561. OPENSSL_PUT_ERROR(SSL, ssl3_send_certificate_request, ERR_R_BUF_LIB);
  1562. goto err;
  1563. }
  1564. p=(unsigned char *)s->init_buf->data + s->init_num;
  1565. /* do the header */
  1566. *(p++)=SSL3_MT_SERVER_DONE;
  1567. *(p++)=0;
  1568. *(p++)=0;
  1569. *(p++)=0;
  1570. s->init_num += 4;
  1571. }
  1572. #endif
  1573. s->state = SSL3_ST_SW_CERT_REQ_B;
  1574. }
  1575. /* SSL3_ST_SW_CERT_REQ_B */
  1576. return ssl_do_write(s);
  1577. err:
  1578. return(-1);
  1579. }
  1580. int ssl3_get_client_key_exchange(SSL *s)
  1581. {
  1582. int al,ok;
  1583. long n;
  1584. CBS client_key_exchange;
  1585. unsigned long alg_k;
  1586. unsigned long alg_a;
  1587. uint8_t *premaster_secret = NULL;
  1588. size_t premaster_secret_len = 0;
  1589. RSA *rsa=NULL;
  1590. uint8_t *decrypt_buf = NULL;
  1591. EVP_PKEY *pkey=NULL;
  1592. BIGNUM *pub=NULL;
  1593. DH *dh_srvr;
  1594. EC_KEY *srvr_ecdh = NULL;
  1595. EVP_PKEY *clnt_pub_pkey = NULL;
  1596. EC_POINT *clnt_ecpoint = NULL;
  1597. BN_CTX *bn_ctx = NULL;
  1598. unsigned int psk_len = 0;
  1599. unsigned char psk[PSK_MAX_PSK_LEN];
  1600. n=s->method->ssl_get_message(s,
  1601. SSL3_ST_SR_KEY_EXCH_A,
  1602. SSL3_ST_SR_KEY_EXCH_B,
  1603. SSL3_MT_CLIENT_KEY_EXCHANGE,
  1604. 2048, /* ??? */
  1605. SSL_GET_MESSAGE_HASH_MESSAGE,
  1606. &ok);
  1607. if (!ok) return((int)n);
  1608. CBS_init(&client_key_exchange, s->init_msg, n);
  1609. alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
  1610. alg_a=s->s3->tmp.new_cipher->algorithm_auth;
  1611. /* If using a PSK key exchange, prepare the pre-shared key. */
  1612. if (alg_a & SSL_aPSK)
  1613. {
  1614. CBS psk_identity;
  1615. /* If using PSK, the ClientKeyExchange contains a
  1616. * psk_identity. If PSK, then this is the only field
  1617. * in the message. */
  1618. if (!CBS_get_u16_length_prefixed(&client_key_exchange, &psk_identity) ||
  1619. ((alg_k & SSL_kPSK) && CBS_len(&client_key_exchange) != 0))
  1620. {
  1621. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
  1622. al = SSL_AD_DECODE_ERROR;
  1623. goto f_err;
  1624. }
  1625. if (s->psk_server_callback == NULL)
  1626. {
  1627. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_NO_SERVER_CB);
  1628. al = SSL_AD_INTERNAL_ERROR;
  1629. goto f_err;
  1630. }
  1631. if (CBS_len(&psk_identity) > PSK_MAX_IDENTITY_LEN ||
  1632. CBS_contains_zero_byte(&psk_identity))
  1633. {
  1634. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DATA_LENGTH_TOO_LONG);
  1635. al = SSL_AD_ILLEGAL_PARAMETER;
  1636. goto f_err;
  1637. }
  1638. if (!CBS_strdup(&psk_identity, &s->session->psk_identity))
  1639. {
  1640. al = SSL_AD_INTERNAL_ERROR;
  1641. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1642. goto f_err;
  1643. }
  1644. /* Look up the key for the identity. */
  1645. psk_len = s->psk_server_callback(s, s->session->psk_identity, psk, sizeof(psk));
  1646. if (psk_len > PSK_MAX_PSK_LEN)
  1647. {
  1648. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
  1649. al = SSL_AD_INTERNAL_ERROR;
  1650. goto f_err;
  1651. }
  1652. else if (psk_len == 0)
  1653. {
  1654. /* PSK related to the given identity not found */
  1655. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_PSK_IDENTITY_NOT_FOUND);
  1656. al = SSL_AD_UNKNOWN_PSK_IDENTITY;
  1657. goto f_err;
  1658. }
  1659. }
  1660. /* Depending on the key exchange method, compute |premaster_secret| and
  1661. * |premaster_secret_len|. */
  1662. if (alg_k & SSL_kRSA)
  1663. {
  1664. CBS encrypted_premaster_secret;
  1665. uint8_t rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
  1666. uint8_t good;
  1667. size_t rsa_size, decrypt_len, premaster_index, j;
  1668. pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
  1669. if ( (pkey == NULL) ||
  1670. (pkey->type != EVP_PKEY_RSA) ||
  1671. (pkey->pkey.rsa == NULL))
  1672. {
  1673. al=SSL_AD_HANDSHAKE_FAILURE;
  1674. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_RSA_CERTIFICATE);
  1675. goto f_err;
  1676. }
  1677. rsa=pkey->pkey.rsa;
  1678. /* TLS and [incidentally] DTLS{0xFEFF} */
  1679. if (s->version > SSL3_VERSION)
  1680. {
  1681. CBS copy = client_key_exchange;
  1682. if (!CBS_get_u16_length_prefixed(&client_key_exchange,
  1683. &encrypted_premaster_secret) ||
  1684. CBS_len(&client_key_exchange) != 0)
  1685. {
  1686. if (!(s->options & SSL_OP_TLS_D5_BUG))
  1687. {
  1688. al = SSL_AD_DECODE_ERROR;
  1689. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
  1690. goto f_err;
  1691. }
  1692. else
  1693. encrypted_premaster_secret = copy;
  1694. }
  1695. }
  1696. else
  1697. encrypted_premaster_secret = client_key_exchange;
  1698. /* Reject overly short RSA keys because we want to be sure that
  1699. * the buffer size makes it safe to iterate over the entire size
  1700. * of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The actual
  1701. * expected size is larger due to RSA padding, but the bound is
  1702. * sufficient to be safe. */
  1703. rsa_size = RSA_size(rsa);
  1704. if (rsa_size < SSL_MAX_MASTER_KEY_LENGTH)
  1705. {
  1706. al = SSL_AD_DECRYPT_ERROR;
  1707. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECRYPTION_FAILED);
  1708. goto f_err;
  1709. }
  1710. /* We must not leak whether a decryption failure occurs because
  1711. * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
  1712. * RFC 2246, section 7.4.7.1). The code follows that advice of
  1713. * the TLS RFC and generates a random premaster secret for the
  1714. * case that the decrypt fails. See
  1715. * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
  1716. if (RAND_pseudo_bytes(rand_premaster_secret,
  1717. sizeof(rand_premaster_secret)) <= 0)
  1718. goto err;
  1719. /* Allocate a buffer large enough for an RSA decryption. */
  1720. decrypt_buf = OPENSSL_malloc(rsa_size);
  1721. if (decrypt_buf == NULL)
  1722. {
  1723. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1724. goto err;
  1725. }
  1726. /* Decrypt with no padding. PKCS#1 padding will be removed as
  1727. * part of the timing-sensitive code below. */
  1728. if (!RSA_decrypt(rsa, &decrypt_len, decrypt_buf, rsa_size,
  1729. CBS_data(&encrypted_premaster_secret),
  1730. CBS_len(&encrypted_premaster_secret),
  1731. RSA_NO_PADDING))
  1732. {
  1733. goto err;
  1734. }
  1735. if (decrypt_len != rsa_size)
  1736. {
  1737. /* This should never happen, but do a check so we do not
  1738. * read uninitialized memory. */
  1739. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
  1740. goto err;
  1741. }
  1742. /* Remove the PKCS#1 padding and adjust |decrypt_len| as
  1743. * appropriate. |good| will be 0xff if the premaster is
  1744. * acceptable and zero otherwise. */
  1745. good = constant_time_eq_int_8(
  1746. RSA_message_index_PKCS1_type_2(decrypt_buf, decrypt_len, &premaster_index), 1);
  1747. decrypt_len = decrypt_len - premaster_index;
  1748. /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. */
  1749. good &= constant_time_eq_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
  1750. /* Copy over the unpadded premaster. Whatever the value of
  1751. * |decrypt_good_mask|, copy as if the premaster were the right
  1752. * length. It is important the memory access pattern be
  1753. * constant. */
  1754. premaster_secret = BUF_memdup(
  1755. decrypt_buf + (rsa_size - SSL_MAX_MASTER_KEY_LENGTH),
  1756. SSL_MAX_MASTER_KEY_LENGTH);
  1757. if (premaster_secret == NULL)
  1758. {
  1759. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1760. goto err;
  1761. }
  1762. OPENSSL_free(decrypt_buf);
  1763. decrypt_buf = NULL;
  1764. /* If the version in the decrypted pre-master secret is correct
  1765. * then version_good will be 0xff, otherwise it'll be zero. The
  1766. * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
  1767. * (http://eprint.iacr.org/2003/052/) exploits the version
  1768. * number check as a "bad version oracle". Thus version checks
  1769. * are done in constant time and are treated like any other
  1770. * decryption error. */
  1771. good &= constant_time_eq_8(premaster_secret[0], (unsigned)(s->client_version>>8));
  1772. good &= constant_time_eq_8(premaster_secret[1], (unsigned)(s->client_version&0xff));
  1773. /* Now copy rand_premaster_secret over premaster_secret using
  1774. * decrypt_good_mask. */
  1775. for (j = 0; j < sizeof(rand_premaster_secret); j++)
  1776. {
  1777. premaster_secret[j] = constant_time_select_8(good, premaster_secret[j], rand_premaster_secret[j]);
  1778. }
  1779. premaster_secret_len = sizeof(rand_premaster_secret);
  1780. }
  1781. else if (alg_k & SSL_kEDH)
  1782. {
  1783. CBS dh_Yc;
  1784. int dh_len;
  1785. if (!CBS_get_u16_length_prefixed(&client_key_exchange, &dh_Yc) ||
  1786. CBS_len(&dh_Yc) == 0 ||
  1787. CBS_len(&client_key_exchange) != 0)
  1788. {
  1789. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
  1790. al = SSL_R_DECODE_ERROR;
  1791. goto f_err;
  1792. }
  1793. if (s->s3->tmp.dh == NULL)
  1794. {
  1795. al=SSL_AD_HANDSHAKE_FAILURE;
  1796. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_MISSING_TMP_DH_KEY);
  1797. goto f_err;
  1798. }
  1799. dh_srvr=s->s3->tmp.dh;
  1800. pub = BN_bin2bn(CBS_data(&dh_Yc), CBS_len(&dh_Yc), NULL);
  1801. if (pub == NULL)
  1802. {
  1803. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_BN_LIB);
  1804. goto err;
  1805. }
  1806. /* Allocate a buffer for the premaster secret. */
  1807. premaster_secret = OPENSSL_malloc(DH_size(dh_srvr));
  1808. if (premaster_secret == NULL)
  1809. {
  1810. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1811. goto err;
  1812. }
  1813. dh_len = DH_compute_key(premaster_secret, pub, dh_srvr);
  1814. if (dh_len <= 0)
  1815. {
  1816. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_DH_LIB);
  1817. BN_clear_free(pub);
  1818. goto err;
  1819. }
  1820. DH_free(s->s3->tmp.dh);
  1821. s->s3->tmp.dh=NULL;
  1822. BN_clear_free(pub);
  1823. pub=NULL;
  1824. premaster_secret_len = dh_len;
  1825. }
  1826. else if (alg_k & SSL_kEECDH)
  1827. {
  1828. int field_size = 0, ecdh_len;
  1829. const EC_KEY *tkey;
  1830. const EC_GROUP *group;
  1831. const BIGNUM *priv_key;
  1832. CBS ecdh_Yc;
  1833. /* initialize structures for server's ECDH key pair */
  1834. if ((srvr_ecdh = EC_KEY_new()) == NULL)
  1835. {
  1836. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1837. goto err;
  1838. }
  1839. /* Use the ephermeral values we saved when generating the
  1840. * ServerKeyExchange msg. */
  1841. tkey = s->s3->tmp.ecdh;
  1842. group = EC_KEY_get0_group(tkey);
  1843. priv_key = EC_KEY_get0_private_key(tkey);
  1844. if (!EC_KEY_set_group(srvr_ecdh, group) ||
  1845. !EC_KEY_set_private_key(srvr_ecdh, priv_key))
  1846. {
  1847. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
  1848. goto err;
  1849. }
  1850. /* Let's get client's public key */
  1851. if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
  1852. {
  1853. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1854. goto err;
  1855. }
  1856. /* Get client's public key from encoded point
  1857. * in the ClientKeyExchange message.
  1858. */
  1859. if (!CBS_get_u8_length_prefixed(&client_key_exchange, &ecdh_Yc) ||
  1860. CBS_len(&client_key_exchange) != 0)
  1861. {
  1862. al = SSL_AD_DECODE_ERROR;
  1863. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_DECODE_ERROR);
  1864. goto f_err;
  1865. }
  1866. if ((bn_ctx = BN_CTX_new()) == NULL)
  1867. {
  1868. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1869. goto err;
  1870. }
  1871. if (!EC_POINT_oct2point(group, clnt_ecpoint,
  1872. CBS_data(&ecdh_Yc), CBS_len(&ecdh_Yc), bn_ctx))
  1873. {
  1874. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_EC_LIB);
  1875. goto err;
  1876. }
  1877. /* Allocate a buffer for both the secret and the PSK. */
  1878. field_size = EC_GROUP_get_degree(group);
  1879. if (field_size <= 0)
  1880. {
  1881. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
  1882. goto err;
  1883. }
  1884. ecdh_len = (field_size + 7) / 8;
  1885. premaster_secret = OPENSSL_malloc(ecdh_len);
  1886. if (premaster_secret == NULL)
  1887. {
  1888. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1889. goto err;
  1890. }
  1891. /* Compute the shared pre-master secret */
  1892. ecdh_len = ECDH_compute_key(premaster_secret,
  1893. ecdh_len, clnt_ecpoint, srvr_ecdh, NULL);
  1894. if (ecdh_len <= 0)
  1895. {
  1896. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_ECDH_LIB);
  1897. goto err;
  1898. }
  1899. EVP_PKEY_free(clnt_pub_pkey);
  1900. clnt_pub_pkey = NULL;
  1901. EC_POINT_free(clnt_ecpoint);
  1902. clnt_ecpoint = NULL;
  1903. EC_KEY_free(srvr_ecdh);
  1904. srvr_ecdh = NULL;
  1905. BN_CTX_free(bn_ctx);
  1906. bn_ctx = NULL;
  1907. EC_KEY_free(s->s3->tmp.ecdh);
  1908. s->s3->tmp.ecdh = NULL;
  1909. premaster_secret_len = ecdh_len;
  1910. }
  1911. else if (alg_k & SSL_kPSK)
  1912. {
  1913. /* For plain PSK, other_secret is a block of 0s with the same
  1914. * length as the pre-shared key. */
  1915. premaster_secret_len = psk_len;
  1916. premaster_secret = OPENSSL_malloc(premaster_secret_len);
  1917. if (premaster_secret == NULL)
  1918. {
  1919. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1920. goto err;
  1921. }
  1922. memset(premaster_secret, 0, premaster_secret_len);
  1923. }
  1924. else
  1925. {
  1926. al=SSL_AD_HANDSHAKE_FAILURE;
  1927. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, SSL_R_UNKNOWN_CIPHER_TYPE);
  1928. goto f_err;
  1929. }
  1930. /* For a PSK cipher suite, the actual pre-master secret is combined with
  1931. * the pre-shared key. */
  1932. if (alg_a & SSL_aPSK)
  1933. {
  1934. CBB new_premaster, child;
  1935. uint8_t *new_data;
  1936. size_t new_len;
  1937. if (!CBB_init(&new_premaster, 2 + psk_len + 2 + premaster_secret_len))
  1938. {
  1939. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_MALLOC_FAILURE);
  1940. goto err;
  1941. }
  1942. if (!CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1943. !CBB_add_bytes(&child, premaster_secret, premaster_secret_len) ||
  1944. !CBB_add_u16_length_prefixed(&new_premaster, &child) ||
  1945. !CBB_add_bytes(&child, psk, psk_len) ||
  1946. !CBB_finish(&new_premaster, &new_data, &new_len))
  1947. {
  1948. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_key_exchange, ERR_R_INTERNAL_ERROR);
  1949. CBB_cleanup(&new_premaster);
  1950. goto err;
  1951. }
  1952. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1953. OPENSSL_free(premaster_secret);
  1954. premaster_secret = new_data;
  1955. premaster_secret_len = new_len;
  1956. }
  1957. /* Compute the master secret */
  1958. s->session->master_key_length = s->method->ssl3_enc
  1959. ->generate_master_secret(s,
  1960. s->session->master_key, premaster_secret, premaster_secret_len);
  1961. if (s->session->master_key_length == 0)
  1962. goto err;
  1963. s->session->extended_master_secret = s->s3->tmp.extended_master_secret;
  1964. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1965. OPENSSL_free(premaster_secret);
  1966. return 1;
  1967. f_err:
  1968. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  1969. err:
  1970. if (premaster_secret)
  1971. {
  1972. if (premaster_secret_len)
  1973. OPENSSL_cleanse(premaster_secret, premaster_secret_len);
  1974. OPENSSL_free(premaster_secret);
  1975. }
  1976. if (decrypt_buf)
  1977. OPENSSL_free(decrypt_buf);
  1978. EVP_PKEY_free(clnt_pub_pkey);
  1979. EC_POINT_free(clnt_ecpoint);
  1980. if (srvr_ecdh != NULL)
  1981. EC_KEY_free(srvr_ecdh);
  1982. BN_CTX_free(bn_ctx);
  1983. return(-1);
  1984. }
  1985. int ssl3_get_cert_verify(SSL *s)
  1986. {
  1987. int al,ok,ret=0;
  1988. long n;
  1989. CBS certificate_verify, signature;
  1990. X509 *peer = s->session->peer;
  1991. EVP_PKEY *pkey = NULL;
  1992. const EVP_MD *md = NULL;
  1993. uint8_t digest[EVP_MAX_MD_SIZE];
  1994. size_t digest_length;
  1995. EVP_PKEY_CTX *pctx = NULL;
  1996. /* Only RSA and ECDSA client certificates are supported, so a
  1997. * CertificateVerify is required if and only if there's a
  1998. * client certificate. */
  1999. if (peer == NULL)
  2000. {
  2001. if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer))
  2002. return -1;
  2003. return 1;
  2004. }
  2005. n=s->method->ssl_get_message(s,
  2006. SSL3_ST_SR_CERT_VRFY_A,
  2007. SSL3_ST_SR_CERT_VRFY_B,
  2008. SSL3_MT_CERTIFICATE_VERIFY,
  2009. SSL3_RT_MAX_PLAIN_LENGTH,
  2010. SSL_GET_MESSAGE_DONT_HASH_MESSAGE,
  2011. &ok);
  2012. if (!ok)
  2013. return (int)n;
  2014. /* Filter out unsupported certificate types. */
  2015. pkey = X509_get_pubkey(peer);
  2016. if (!(X509_certificate_type(peer, pkey) & EVP_PKT_SIGN) ||
  2017. (pkey->type != EVP_PKEY_RSA && pkey->type != EVP_PKEY_EC))
  2018. {
  2019. al = SSL_AD_UNSUPPORTED_CERTIFICATE;
  2020. OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
  2021. goto f_err;
  2022. }
  2023. CBS_init(&certificate_verify, s->init_msg, n);
  2024. /* Determine the digest type if needbe. */
  2025. if (SSL_USE_SIGALGS(s))
  2026. {
  2027. if (!tls12_check_peer_sigalg(&md, &al, s, &certificate_verify, pkey))
  2028. goto f_err;
  2029. }
  2030. /* Compute the digest. */
  2031. if (!ssl3_cert_verify_hash(s, digest, &digest_length, &md, pkey))
  2032. goto err;
  2033. /* The handshake buffer is no longer necessary, and we may hash the
  2034. * current message.*/
  2035. if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer))
  2036. goto err;
  2037. ssl3_hash_current_message(s);
  2038. /* Parse and verify the signature. */
  2039. if (!CBS_get_u16_length_prefixed(&certificate_verify, &signature) ||
  2040. CBS_len(&certificate_verify) != 0)
  2041. {
  2042. al = SSL_AD_DECODE_ERROR;
  2043. OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_DECODE_ERROR);
  2044. goto f_err;
  2045. }
  2046. pctx = EVP_PKEY_CTX_new(pkey, NULL);
  2047. if (pctx == NULL)
  2048. goto err;
  2049. if (!EVP_PKEY_verify_init(pctx) ||
  2050. !EVP_PKEY_CTX_set_signature_md(pctx, md) ||
  2051. !EVP_PKEY_verify(pctx, CBS_data(&signature), CBS_len(&signature),
  2052. digest, digest_length))
  2053. {
  2054. al = SSL_AD_DECRYPT_ERROR;
  2055. OPENSSL_PUT_ERROR(SSL, ssl3_get_cert_verify, SSL_R_BAD_SIGNATURE);
  2056. goto f_err;
  2057. }
  2058. ret = 1;
  2059. if (0)
  2060. {
  2061. f_err:
  2062. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  2063. }
  2064. err:
  2065. EVP_PKEY_CTX_free(pctx);
  2066. EVP_PKEY_free(pkey);
  2067. return(ret);
  2068. }
  2069. int ssl3_get_client_certificate(SSL *s)
  2070. {
  2071. int i,ok,al,ret= -1;
  2072. X509 *x=NULL;
  2073. unsigned long n;
  2074. STACK_OF(X509) *sk=NULL;
  2075. SHA256_CTX sha256;
  2076. CBS certificate_msg, certificate_list;
  2077. int is_first_certificate = 1;
  2078. n=s->method->ssl_get_message(s,
  2079. SSL3_ST_SR_CERT_A,
  2080. SSL3_ST_SR_CERT_B,
  2081. -1,
  2082. s->max_cert_list,
  2083. SSL_GET_MESSAGE_HASH_MESSAGE,
  2084. &ok);
  2085. if (!ok) return((int)n);
  2086. if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
  2087. {
  2088. if ( (s->verify_mode & SSL_VERIFY_PEER) &&
  2089. (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
  2090. {
  2091. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  2092. al=SSL_AD_HANDSHAKE_FAILURE;
  2093. goto f_err;
  2094. }
  2095. /* If tls asked for a client cert, the client must return a 0 list */
  2096. if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
  2097. {
  2098. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
  2099. al=SSL_AD_UNEXPECTED_MESSAGE;
  2100. goto f_err;
  2101. }
  2102. s->s3->tmp.reuse_message=1;
  2103. return(1);
  2104. }
  2105. if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
  2106. {
  2107. al=SSL_AD_UNEXPECTED_MESSAGE;
  2108. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_WRONG_MESSAGE_TYPE);
  2109. goto f_err;
  2110. }
  2111. CBS_init(&certificate_msg, s->init_msg, n);
  2112. if ((sk=sk_X509_new_null()) == NULL)
  2113. {
  2114. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
  2115. goto err;
  2116. }
  2117. if (!CBS_get_u24_length_prefixed(&certificate_msg, &certificate_list) ||
  2118. CBS_len(&certificate_msg) != 0)
  2119. {
  2120. al = SSL_AD_DECODE_ERROR;
  2121. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
  2122. goto f_err;
  2123. }
  2124. while (CBS_len(&certificate_list) > 0)
  2125. {
  2126. CBS certificate;
  2127. const uint8_t *data;
  2128. if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate))
  2129. {
  2130. al = SSL_AD_DECODE_ERROR;
  2131. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_DECODE_ERROR);
  2132. goto f_err;
  2133. }
  2134. if (is_first_certificate && s->ctx->retain_only_sha256_of_client_certs)
  2135. {
  2136. /* If this is the first certificate, and we don't want
  2137. * to keep peer certificates in memory, then we hash it
  2138. * right away. */
  2139. SHA256_Init(&sha256);
  2140. SHA256_Update(&sha256, CBS_data(&certificate), CBS_len(&certificate));
  2141. SHA256_Final(s->session->peer_sha256, &sha256);
  2142. s->session->peer_sha256_valid = 1;
  2143. }
  2144. is_first_certificate = 0;
  2145. data = CBS_data(&certificate);
  2146. x = d2i_X509(NULL, &data, CBS_len(&certificate));
  2147. if (x == NULL)
  2148. {
  2149. al = SSL_AD_BAD_CERTIFICATE;
  2150. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_ASN1_LIB);
  2151. goto f_err;
  2152. }
  2153. if (!CBS_skip(&certificate, data - CBS_data(&certificate)))
  2154. {
  2155. al = SSL_AD_INTERNAL_ERROR;
  2156. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_INTERNAL_ERROR);
  2157. goto f_err;
  2158. }
  2159. if (CBS_len(&certificate) != 0)
  2160. {
  2161. al = SSL_AD_DECODE_ERROR;
  2162. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERT_LENGTH_MISMATCH);
  2163. goto f_err;
  2164. }
  2165. if (!sk_X509_push(sk,x))
  2166. {
  2167. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
  2168. goto err;
  2169. }
  2170. x = NULL;
  2171. }
  2172. if (sk_X509_num(sk) <= 0)
  2173. {
  2174. /* TLS does not mind 0 certs returned */
  2175. if (s->version == SSL3_VERSION)
  2176. {
  2177. al=SSL_AD_HANDSHAKE_FAILURE;
  2178. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_NO_CERTIFICATES_RETURNED);
  2179. goto f_err;
  2180. }
  2181. /* Fail for TLS only if we required a certificate */
  2182. else if ((s->verify_mode & SSL_VERIFY_PEER) &&
  2183. (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
  2184. {
  2185. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
  2186. al=SSL_AD_HANDSHAKE_FAILURE;
  2187. goto f_err;
  2188. }
  2189. /* No client certificate so digest cached records */
  2190. if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, free_handshake_buffer))
  2191. {
  2192. al=SSL_AD_INTERNAL_ERROR;
  2193. goto f_err;
  2194. }
  2195. }
  2196. else
  2197. {
  2198. i=ssl_verify_cert_chain(s,sk);
  2199. if (i <= 0)
  2200. {
  2201. al=ssl_verify_alarm_type(s->verify_result);
  2202. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, SSL_R_CERTIFICATE_VERIFY_FAILED);
  2203. goto f_err;
  2204. }
  2205. }
  2206. if (s->session->peer != NULL) /* This should not be needed */
  2207. X509_free(s->session->peer);
  2208. s->session->peer=sk_X509_shift(sk);
  2209. s->session->verify_result = s->verify_result;
  2210. /* With the current implementation, sess_cert will always be NULL
  2211. * when we arrive here. */
  2212. if (s->session->sess_cert == NULL)
  2213. {
  2214. s->session->sess_cert = ssl_sess_cert_new();
  2215. if (s->session->sess_cert == NULL)
  2216. {
  2217. OPENSSL_PUT_ERROR(SSL, ssl3_get_client_certificate, ERR_R_MALLOC_FAILURE);
  2218. goto err;
  2219. }
  2220. }
  2221. if (s->session->sess_cert->cert_chain != NULL)
  2222. sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
  2223. s->session->sess_cert->cert_chain=sk;
  2224. /* Inconsistency alert: cert_chain does *not* include the
  2225. * peer's own certificate, while we do include it in s3_clnt.c */
  2226. sk=NULL;
  2227. ret=1;
  2228. if (0)
  2229. {
  2230. f_err:
  2231. ssl3_send_alert(s,SSL3_AL_FATAL,al);
  2232. }
  2233. err:
  2234. if (x != NULL) X509_free(x);
  2235. if (sk != NULL) sk_X509_pop_free(sk,X509_free);
  2236. return(ret);
  2237. }
  2238. int ssl3_send_server_certificate(SSL *s)
  2239. {
  2240. CERT_PKEY *cpk;
  2241. if (s->state == SSL3_ST_SW_CERT_A)
  2242. {
  2243. cpk=ssl_get_server_send_pkey(s);
  2244. if (cpk == NULL)
  2245. {
  2246. OPENSSL_PUT_ERROR(SSL, ssl3_send_server_certificate, ERR_R_INTERNAL_ERROR);
  2247. return(0);
  2248. }
  2249. ssl3_output_cert_chain(s,cpk);
  2250. s->state=SSL3_ST_SW_CERT_B;
  2251. }
  2252. /* SSL3_ST_SW_CERT_B */
  2253. return ssl_do_write(s);
  2254. }
  2255. /* send a new session ticket (not necessarily for a new session) */
  2256. int ssl3_send_new_session_ticket(SSL *s)
  2257. {
  2258. if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
  2259. {
  2260. uint8_t *session;
  2261. size_t session_len;
  2262. uint8_t *p, *macstart;
  2263. int len;
  2264. unsigned int hlen;
  2265. EVP_CIPHER_CTX ctx;
  2266. HMAC_CTX hctx;
  2267. SSL_CTX *tctx = s->initial_ctx;
  2268. unsigned char iv[EVP_MAX_IV_LENGTH];
  2269. unsigned char key_name[16];
  2270. /* The maximum overhead of encrypting the session is 16 (key
  2271. * name) + IV + one block of encryption overhead + HMAC. */
  2272. const size_t max_ticket_overhead = 16 + EVP_MAX_IV_LENGTH +
  2273. EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE;
  2274. /* Serialize the SSL_SESSION to be encoded into the ticket. */
  2275. if (!SSL_SESSION_to_bytes_for_ticket(s->session, &session,
  2276. &session_len))
  2277. {
  2278. return -1;
  2279. }
  2280. /* If the session is too long, emit a dummy value rather than
  2281. * abort the connection. */
  2282. if (session_len > 0xFFFF - max_ticket_overhead)
  2283. {
  2284. const char kTicketPlaceholder[] = "TICKET TOO LARGE";
  2285. size_t placeholder_len = strlen(kTicketPlaceholder);
  2286. OPENSSL_free(session);
  2287. p = ssl_handshake_start(s);
  2288. /* Emit ticket_lifetime_hint. */
  2289. l2n(0, p);
  2290. /* Emit ticket. */
  2291. s2n(placeholder_len, p);
  2292. memcpy(p, kTicketPlaceholder, placeholder_len);
  2293. p += placeholder_len;
  2294. len = p - ssl_handshake_start(s);
  2295. ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
  2296. s->state = SSL3_ST_SW_SESSION_TICKET_B;
  2297. return ssl_do_write(s);
  2298. }
  2299. /* Grow buffer if need be: the length calculation is as
  2300. * follows: handshake_header_length +
  2301. * 4 (ticket lifetime hint) + 2 (ticket length) +
  2302. * max_ticket_overhead + * session_length */
  2303. if (!BUF_MEM_grow(s->init_buf,
  2304. SSL_HM_HEADER_LENGTH(s) + 6 +
  2305. max_ticket_overhead + session_len))
  2306. {
  2307. OPENSSL_free(session);
  2308. return -1;
  2309. }
  2310. p = ssl_handshake_start(s);
  2311. EVP_CIPHER_CTX_init(&ctx);
  2312. HMAC_CTX_init(&hctx);
  2313. /* Initialize HMAC and cipher contexts. If callback present
  2314. * it does all the work otherwise use generated values
  2315. * from parent ctx.
  2316. */
  2317. if (tctx->tlsext_ticket_key_cb)
  2318. {
  2319. if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
  2320. &hctx, 1) < 0)
  2321. {
  2322. OPENSSL_free(session);
  2323. return -1;
  2324. }
  2325. }
  2326. else
  2327. {
  2328. RAND_pseudo_bytes(iv, 16);
  2329. EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
  2330. tctx->tlsext_tick_aes_key, iv);
  2331. HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
  2332. tlsext_tick_md(), NULL);
  2333. memcpy(key_name, tctx->tlsext_tick_key_name, 16);
  2334. }
  2335. /* Ticket lifetime hint (advisory only):
  2336. * We leave this unspecified for resumed session (for simplicity),
  2337. * and guess that tickets for new sessions will live as long
  2338. * as their sessions. */
  2339. l2n(s->hit ? 0 : s->session->timeout, p);
  2340. /* Skip ticket length for now */
  2341. p += 2;
  2342. /* Output key name */
  2343. macstart = p;
  2344. memcpy(p, key_name, 16);
  2345. p += 16;
  2346. /* output IV */
  2347. memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
  2348. p += EVP_CIPHER_CTX_iv_length(&ctx);
  2349. /* Encrypt session data */
  2350. EVP_EncryptUpdate(&ctx, p, &len, session, session_len);
  2351. p += len;
  2352. EVP_EncryptFinal_ex(&ctx, p, &len);
  2353. p += len;
  2354. EVP_CIPHER_CTX_cleanup(&ctx);
  2355. HMAC_Update(&hctx, macstart, p - macstart);
  2356. HMAC_Final(&hctx, p, &hlen);
  2357. HMAC_CTX_cleanup(&hctx);
  2358. p += hlen;
  2359. /* Now write out lengths: p points to end of data written */
  2360. /* Total length */
  2361. len = p - ssl_handshake_start(s);
  2362. ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
  2363. /* Skip ticket lifetime hint */
  2364. p = ssl_handshake_start(s) + 4;
  2365. s2n(len - 6, p);
  2366. s->state=SSL3_ST_SW_SESSION_TICKET_B;
  2367. OPENSSL_free(session);
  2368. }
  2369. /* SSL3_ST_SW_SESSION_TICKET_B */
  2370. return ssl_do_write(s);
  2371. }
  2372. #if 0
  2373. int ssl3_send_cert_status(SSL *s)
  2374. {
  2375. if (s->state == SSL3_ST_SW_CERT_STATUS_A)
  2376. {
  2377. unsigned char *p;
  2378. /* Grow buffer if need be: the length calculation is as
  2379. * follows 1 (message type) + 3 (message length) +
  2380. * 1 (ocsp response type) + 3 (ocsp response length)
  2381. * + (ocsp response)
  2382. */
  2383. if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
  2384. return -1;
  2385. p=(unsigned char *)s->init_buf->data;
  2386. /* do the header */
  2387. *(p++)=SSL3_MT_CERTIFICATE_STATUS;
  2388. /* message length */
  2389. l2n3(s->tlsext_ocsp_resplen + 4, p);
  2390. /* status type */
  2391. *(p++)= s->tlsext_status_type;
  2392. /* length of OCSP response */
  2393. l2n3(s->tlsext_ocsp_resplen, p);
  2394. /* actual response */
  2395. memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
  2396. /* number of bytes to write */
  2397. s->init_num = 8 + s->tlsext_ocsp_resplen;
  2398. s->state=SSL3_ST_SW_CERT_STATUS_B;
  2399. s->init_off = 0;
  2400. }
  2401. /* SSL3_ST_SW_CERT_STATUS_B */
  2402. return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
  2403. }
  2404. #endif
  2405. /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
  2406. * sets the next_proto member in s if found */
  2407. int ssl3_get_next_proto(SSL *s)
  2408. {
  2409. int ok;
  2410. long n;
  2411. CBS next_protocol, selected_protocol, padding;
  2412. /* Clients cannot send a NextProtocol message if we didn't see the
  2413. * extension in their ClientHello */
  2414. if (!s->s3->next_proto_neg_seen)
  2415. {
  2416. OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
  2417. return -1;
  2418. }
  2419. n=s->method->ssl_get_message(s,
  2420. SSL3_ST_SR_NEXT_PROTO_A,
  2421. SSL3_ST_SR_NEXT_PROTO_B,
  2422. SSL3_MT_NEXT_PROTO,
  2423. 514, /* See the payload format below */
  2424. SSL_GET_MESSAGE_HASH_MESSAGE,
  2425. &ok);
  2426. if (!ok)
  2427. return((int)n);
  2428. /* s->state doesn't reflect whether ChangeCipherSpec has been received
  2429. * in this handshake, but s->s3->change_cipher_spec does (will be reset
  2430. * by ssl3_get_finished).
  2431. * TODO(davidben): Is this check now redundant with
  2432. * SSL3_FLAGS_EXPECT_CCS? */
  2433. if (!s->s3->change_cipher_spec)
  2434. {
  2435. OPENSSL_PUT_ERROR(SSL, ssl3_get_next_proto, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
  2436. return -1;
  2437. }
  2438. CBS_init(&next_protocol, s->init_msg, n);
  2439. /* The payload looks like:
  2440. * uint8 proto_len;
  2441. * uint8 proto[proto_len];
  2442. * uint8 padding_len;
  2443. * uint8 padding[padding_len];
  2444. */
  2445. if (!CBS_get_u8_length_prefixed(&next_protocol, &selected_protocol) ||
  2446. !CBS_get_u8_length_prefixed(&next_protocol, &padding) ||
  2447. CBS_len(&next_protocol) != 0)
  2448. return 0;
  2449. if (!CBS_stow(&selected_protocol,
  2450. &s->next_proto_negotiated,
  2451. &s->next_proto_negotiated_len))
  2452. return 0;
  2453. return 1;
  2454. }
  2455. /* ssl3_get_channel_id reads and verifies a ClientID handshake message. */
  2456. int ssl3_get_channel_id(SSL *s)
  2457. {
  2458. int ret = -1, ok;
  2459. long n;
  2460. EVP_MD_CTX md_ctx;
  2461. uint8_t channel_id_hash[SHA256_DIGEST_LENGTH];
  2462. unsigned int channel_id_hash_len;
  2463. const uint8_t *p;
  2464. uint16_t extension_type, expected_extension_type;
  2465. EC_GROUP* p256 = NULL;
  2466. EC_KEY* key = NULL;
  2467. EC_POINT* point = NULL;
  2468. ECDSA_SIG sig;
  2469. BIGNUM x, y;
  2470. CBS encrypted_extensions, extension;
  2471. n = s->method->ssl_get_message(s,
  2472. SSL3_ST_SR_CHANNEL_ID_A,
  2473. SSL3_ST_SR_CHANNEL_ID_B,
  2474. SSL3_MT_ENCRYPTED_EXTENSIONS,
  2475. 2 + 2 + TLSEXT_CHANNEL_ID_SIZE,
  2476. SSL_GET_MESSAGE_DONT_HASH_MESSAGE,
  2477. &ok);
  2478. if (!ok)
  2479. return((int)n);
  2480. /* Before incorporating the EncryptedExtensions message to the
  2481. * handshake hash, compute the hash that should have been signed. */
  2482. channel_id_hash_len = sizeof(channel_id_hash);
  2483. EVP_MD_CTX_init(&md_ctx);
  2484. if (!EVP_DigestInit_ex(&md_ctx, EVP_sha256(), NULL) ||
  2485. !tls1_channel_id_hash(&md_ctx, s) ||
  2486. !EVP_DigestFinal(&md_ctx, channel_id_hash, &channel_id_hash_len))
  2487. {
  2488. EVP_MD_CTX_cleanup(&md_ctx);
  2489. return -1;
  2490. }
  2491. EVP_MD_CTX_cleanup(&md_ctx);
  2492. assert(channel_id_hash_len == SHA256_DIGEST_LENGTH);
  2493. ssl3_hash_current_message(s);
  2494. /* s->state doesn't reflect whether ChangeCipherSpec has been received
  2495. * in this handshake, but s->s3->change_cipher_spec does (will be reset
  2496. * by ssl3_get_finished).
  2497. * TODO(davidben): Is this check now redundant with
  2498. * SSL3_FLAGS_EXPECT_CCS? */
  2499. if (!s->s3->change_cipher_spec)
  2500. {
  2501. OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_GOT_CHANNEL_ID_BEFORE_A_CCS);
  2502. return -1;
  2503. }
  2504. CBS_init(&encrypted_extensions, s->init_msg, n);
  2505. /* EncryptedExtensions could include multiple extensions, but
  2506. * the only extension that could be negotiated is ChannelID,
  2507. * so there can only be one entry.
  2508. *
  2509. * The payload looks like:
  2510. * uint16 extension_type
  2511. * uint16 extension_len;
  2512. * uint8 x[32];
  2513. * uint8 y[32];
  2514. * uint8 r[32];
  2515. * uint8 s[32];
  2516. */
  2517. expected_extension_type = TLSEXT_TYPE_channel_id;
  2518. if (s->s3->tlsext_channel_id_new)
  2519. expected_extension_type = TLSEXT_TYPE_channel_id_new;
  2520. if (!CBS_get_u16(&encrypted_extensions, &extension_type) ||
  2521. !CBS_get_u16_length_prefixed(&encrypted_extensions, &extension) ||
  2522. CBS_len(&encrypted_extensions) != 0 ||
  2523. extension_type != expected_extension_type ||
  2524. CBS_len(&extension) != TLSEXT_CHANNEL_ID_SIZE)
  2525. {
  2526. OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_INVALID_MESSAGE);
  2527. return -1;
  2528. }
  2529. p256 = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
  2530. if (!p256)
  2531. {
  2532. OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_NO_P256_SUPPORT);
  2533. return -1;
  2534. }
  2535. BN_init(&x);
  2536. BN_init(&y);
  2537. sig.r = BN_new();
  2538. sig.s = BN_new();
  2539. p = CBS_data(&extension);
  2540. if (BN_bin2bn(p + 0, 32, &x) == NULL ||
  2541. BN_bin2bn(p + 32, 32, &y) == NULL ||
  2542. BN_bin2bn(p + 64, 32, sig.r) == NULL ||
  2543. BN_bin2bn(p + 96, 32, sig.s) == NULL)
  2544. goto err;
  2545. point = EC_POINT_new(p256);
  2546. if (!point ||
  2547. !EC_POINT_set_affine_coordinates_GFp(p256, point, &x, &y, NULL))
  2548. goto err;
  2549. key = EC_KEY_new();
  2550. if (!key ||
  2551. !EC_KEY_set_group(key, p256) ||
  2552. !EC_KEY_set_public_key(key, point))
  2553. goto err;
  2554. /* We stored the handshake hash in |tlsext_channel_id| the first time
  2555. * that we were called. */
  2556. if (!ECDSA_do_verify(channel_id_hash, channel_id_hash_len, &sig, key))
  2557. {
  2558. OPENSSL_PUT_ERROR(SSL, ssl3_get_channel_id, SSL_R_CHANNEL_ID_SIGNATURE_INVALID);
  2559. s->s3->tlsext_channel_id_valid = 0;
  2560. goto err;
  2561. }
  2562. memcpy(s->s3->tlsext_channel_id, p, 64);
  2563. ret = 1;
  2564. err:
  2565. BN_free(&x);
  2566. BN_free(&y);
  2567. BN_free(sig.r);
  2568. BN_free(sig.s);
  2569. if (key)
  2570. EC_KEY_free(key);
  2571. if (point)
  2572. EC_POINT_free(point);
  2573. if (p256)
  2574. EC_GROUP_free(p256);
  2575. return ret;
  2576. }