Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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