Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

3029 linhas
83 KiB

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