25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

2574 satır
78 KiB

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