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.
 
 
 
 
 
 

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