Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

1004 строки
32 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 2005 Nokia. All rights reserved.
  112. *
  113. * The portions of the attached software ("Contribution") is developed by
  114. * Nokia Corporation and is licensed pursuant to the OpenSSL open source
  115. * license.
  116. *
  117. * The Contribution, originally written by Mika Kousa and Pasi Eronen of
  118. * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
  119. * support (see RFC 4279) to OpenSSL.
  120. *
  121. * No patent licenses or other rights except those expressly stated in
  122. * the OpenSSL open source license shall be deemed granted or received
  123. * expressly, by implication, estoppel, or otherwise.
  124. *
  125. * No assurances are provided by Nokia that the Contribution does not
  126. * infringe the patent or other intellectual property rights of any third
  127. * party or that the license provides you with all the necessary rights
  128. * to make use of the Contribution.
  129. *
  130. * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
  131. * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
  132. * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
  133. * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
  134. * OTHERWISE. */
  135. #include <assert.h>
  136. #include <stdio.h>
  137. #include <string.h>
  138. #include <openssl/err.h>
  139. #include <openssl/evp.h>
  140. #include <openssl/hmac.h>
  141. #include <openssl/md5.h>
  142. #include <openssl/mem.h>
  143. #include <openssl/obj.h>
  144. #include <openssl/rand.h>
  145. #include "internal.h"
  146. /* tls1_P_hash computes the TLS P_<hash> function as described in RFC 5246,
  147. * section 5. It writes |out_len| bytes to |out|, using |md| as the hash and
  148. * |secret| as the secret. |seed1| through |seed3| are concatenated to form the
  149. * seed parameter. It returns one on success and zero on failure. */
  150. static int tls1_P_hash(uint8_t *out, size_t out_len, const EVP_MD *md,
  151. const uint8_t *secret, size_t secret_len,
  152. const uint8_t *seed1, size_t seed1_len,
  153. const uint8_t *seed2, size_t seed2_len,
  154. const uint8_t *seed3, size_t seed3_len) {
  155. size_t chunk;
  156. HMAC_CTX ctx, ctx_tmp, ctx_init;
  157. uint8_t A1[EVP_MAX_MD_SIZE];
  158. unsigned A1_len;
  159. int ret = 0;
  160. chunk = EVP_MD_size(md);
  161. HMAC_CTX_init(&ctx);
  162. HMAC_CTX_init(&ctx_tmp);
  163. HMAC_CTX_init(&ctx_init);
  164. if (!HMAC_Init_ex(&ctx_init, secret, secret_len, md, NULL) ||
  165. !HMAC_CTX_copy_ex(&ctx, &ctx_init) ||
  166. (seed1_len && !HMAC_Update(&ctx, seed1, seed1_len)) ||
  167. (seed2_len && !HMAC_Update(&ctx, seed2, seed2_len)) ||
  168. (seed3_len && !HMAC_Update(&ctx, seed3, seed3_len)) ||
  169. !HMAC_Final(&ctx, A1, &A1_len)) {
  170. goto err;
  171. }
  172. for (;;) {
  173. /* Reinit mac contexts. */
  174. if (!HMAC_CTX_copy_ex(&ctx, &ctx_init) ||
  175. !HMAC_Update(&ctx, A1, A1_len) ||
  176. (out_len > chunk && !HMAC_CTX_copy_ex(&ctx_tmp, &ctx)) ||
  177. (seed1_len && !HMAC_Update(&ctx, seed1, seed1_len)) ||
  178. (seed2_len && !HMAC_Update(&ctx, seed2, seed2_len)) ||
  179. (seed3_len && !HMAC_Update(&ctx, seed3, seed3_len))) {
  180. goto err;
  181. }
  182. if (out_len > chunk) {
  183. unsigned len;
  184. if (!HMAC_Final(&ctx, out, &len)) {
  185. goto err;
  186. }
  187. assert(len == chunk);
  188. out += len;
  189. out_len -= len;
  190. /* Calculate the next A1 value. */
  191. if (!HMAC_Final(&ctx_tmp, A1, &A1_len)) {
  192. goto err;
  193. }
  194. } else {
  195. /* Last chunk. */
  196. if (!HMAC_Final(&ctx, A1, &A1_len)) {
  197. goto err;
  198. }
  199. memcpy(out, A1, out_len);
  200. break;
  201. }
  202. }
  203. ret = 1;
  204. err:
  205. HMAC_CTX_cleanup(&ctx);
  206. HMAC_CTX_cleanup(&ctx_tmp);
  207. HMAC_CTX_cleanup(&ctx_init);
  208. OPENSSL_cleanse(A1, sizeof(A1));
  209. return ret;
  210. }
  211. int tls1_prf(SSL *s, uint8_t *out, size_t out_len, const uint8_t *secret,
  212. size_t secret_len, const char *label, size_t label_len,
  213. const uint8_t *seed1, size_t seed1_len,
  214. const uint8_t *seed2, size_t seed2_len) {
  215. size_t idx, len, count, i;
  216. const uint8_t *S1;
  217. uint32_t m;
  218. const EVP_MD *md;
  219. int ret = 0;
  220. uint8_t *tmp;
  221. if (out_len == 0) {
  222. return 1;
  223. }
  224. /* Allocate a temporary buffer. */
  225. tmp = OPENSSL_malloc(out_len);
  226. if (tmp == NULL) {
  227. OPENSSL_PUT_ERROR(SSL, tls1_prf, ERR_R_MALLOC_FAILURE);
  228. return 0;
  229. }
  230. /* Count number of digests and partition |secret| evenly. */
  231. count = 0;
  232. for (idx = 0; ssl_get_handshake_digest(&m, &md, idx); idx++) {
  233. if ((m << TLS1_PRF_DGST_SHIFT) & ssl_get_algorithm2(s)) {
  234. count++;
  235. }
  236. }
  237. /* TODO(davidben): The only case where count isn't 1 is the old MD5/SHA-1
  238. * combination. The logic around multiple handshake digests can probably be
  239. * simplified. */
  240. assert(count == 1 || count == 2);
  241. len = secret_len / count;
  242. if (count == 1) {
  243. secret_len = 0;
  244. }
  245. S1 = secret;
  246. memset(out, 0, out_len);
  247. for (idx = 0; ssl_get_handshake_digest(&m, &md, idx); idx++) {
  248. if ((m << TLS1_PRF_DGST_SHIFT) & ssl_get_algorithm2(s)) {
  249. /* If |count| is 2 and |secret_len| is odd, |secret| is partitioned into
  250. * two halves with an overlapping byte. */
  251. if (!tls1_P_hash(tmp, out_len, md, S1, len + (secret_len & 1),
  252. (const uint8_t *)label, label_len, seed1, seed1_len,
  253. seed2, seed2_len)) {
  254. goto err;
  255. }
  256. S1 += len;
  257. for (i = 0; i < out_len; i++) {
  258. out[i] ^= tmp[i];
  259. }
  260. }
  261. }
  262. ret = 1;
  263. err:
  264. OPENSSL_cleanse(tmp, out_len);
  265. OPENSSL_free(tmp);
  266. return ret;
  267. }
  268. static int tls1_generate_key_block(SSL *s, uint8_t *out, size_t out_len) {
  269. return s->enc_method->prf(s, out, out_len, s->session->master_key,
  270. s->session->master_key_length,
  271. TLS_MD_KEY_EXPANSION_CONST,
  272. TLS_MD_KEY_EXPANSION_CONST_SIZE,
  273. s->s3->server_random, SSL3_RANDOM_SIZE,
  274. s->s3->client_random,
  275. SSL3_RANDOM_SIZE);
  276. }
  277. /* tls1_aead_ctx_init allocates |*aead_ctx|, if needed and returns 1. It
  278. * returns 0 on malloc error. */
  279. static int tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx) {
  280. if (*aead_ctx != NULL) {
  281. EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
  282. } else {
  283. *aead_ctx = (SSL_AEAD_CTX *)OPENSSL_malloc(sizeof(SSL_AEAD_CTX));
  284. if (*aead_ctx == NULL) {
  285. OPENSSL_PUT_ERROR(SSL, tls1_aead_ctx_init, ERR_R_MALLOC_FAILURE);
  286. return 0;
  287. }
  288. }
  289. return 1;
  290. }
  291. static int tls1_change_cipher_state_aead(SSL *s, char is_read,
  292. const uint8_t *key, unsigned key_len,
  293. const uint8_t *iv, unsigned iv_len,
  294. const uint8_t *mac_secret,
  295. unsigned mac_secret_len) {
  296. const EVP_AEAD *aead = s->s3->tmp.new_aead;
  297. SSL_AEAD_CTX *aead_ctx;
  298. /* merged_key is used to merge the MAC, cipher, and IV keys for an AEAD which
  299. * simulates pre-AEAD cipher suites. */
  300. uint8_t merged_key[EVP_AEAD_MAX_KEY_LENGTH];
  301. if (mac_secret_len > 0) {
  302. /* This is a "stateful" AEAD (for compatibility with pre-AEAD cipher
  303. * suites). */
  304. if (mac_secret_len + key_len + iv_len > sizeof(merged_key)) {
  305. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead,
  306. ERR_R_INTERNAL_ERROR);
  307. return 0;
  308. }
  309. memcpy(merged_key, mac_secret, mac_secret_len);
  310. memcpy(merged_key + mac_secret_len, key, key_len);
  311. memcpy(merged_key + mac_secret_len + key_len, iv, iv_len);
  312. key = merged_key;
  313. key_len += mac_secret_len;
  314. key_len += iv_len;
  315. }
  316. if (is_read) {
  317. if (!tls1_aead_ctx_init(&s->aead_read_ctx)) {
  318. return 0;
  319. }
  320. aead_ctx = s->aead_read_ctx;
  321. } else {
  322. if (SSL_IS_DTLS(s) && s->aead_write_ctx != NULL) {
  323. /* DTLS renegotiation is unsupported, so a CCS can only switch away from
  324. * the NULL cipher. This simplifies renegotiation. */
  325. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead,
  326. ERR_R_INTERNAL_ERROR);
  327. return 0;
  328. }
  329. if (!tls1_aead_ctx_init(&s->aead_write_ctx)) {
  330. return 0;
  331. }
  332. aead_ctx = s->aead_write_ctx;
  333. }
  334. aead_ctx->cipher = s->session->cipher;
  335. if (!EVP_AEAD_CTX_init_with_direction(
  336. &aead_ctx->ctx, aead, key, key_len, EVP_AEAD_DEFAULT_TAG_LENGTH,
  337. is_read ? evp_aead_open : evp_aead_seal)) {
  338. OPENSSL_free(aead_ctx);
  339. if (is_read) {
  340. s->aead_read_ctx = NULL;
  341. } else {
  342. s->aead_write_ctx = NULL;
  343. }
  344. return 0;
  345. }
  346. if (mac_secret_len == 0) {
  347. /* For a real AEAD, the IV is the fixed part of the nonce. */
  348. if (iv_len > sizeof(aead_ctx->fixed_nonce)) {
  349. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  350. return 0;
  351. }
  352. memcpy(aead_ctx->fixed_nonce, iv, iv_len);
  353. aead_ctx->fixed_nonce_len = iv_len;
  354. aead_ctx->variable_nonce_included_in_record =
  355. (s->s3->tmp.new_cipher->algorithm2 &
  356. SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_INCLUDED_IN_RECORD) != 0;
  357. aead_ctx->random_variable_nonce = 0;
  358. aead_ctx->omit_length_in_ad = 0;
  359. } else {
  360. aead_ctx->fixed_nonce_len = 0;
  361. aead_ctx->variable_nonce_included_in_record = 1;
  362. aead_ctx->random_variable_nonce = 1;
  363. aead_ctx->omit_length_in_ad = 1;
  364. }
  365. aead_ctx->variable_nonce_len = s->s3->tmp.new_variable_iv_len;
  366. aead_ctx->omit_version_in_ad = (s->version == SSL3_VERSION);
  367. if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len !=
  368. EVP_AEAD_nonce_length(aead)) {
  369. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  370. return 0;
  371. }
  372. aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
  373. return 1;
  374. }
  375. int tls1_change_cipher_state(SSL *s, int which) {
  376. /* is_read is true if we have just read a ChangeCipherSpec message - i.e. we
  377. * need to update the read cipherspec. Otherwise we have just written one. */
  378. const char is_read = (which & SSL3_CC_READ) != 0;
  379. /* use_client_keys is true if we wish to use the keys for the "client write"
  380. * direction. This is the case if we're a client sending a ChangeCipherSpec,
  381. * or a server reading a client's ChangeCipherSpec. */
  382. const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
  383. which == SSL3_CHANGE_CIPHER_SERVER_READ;
  384. const uint8_t *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
  385. const uint8_t *client_write_key, *server_write_key, *key;
  386. const uint8_t *client_write_iv, *server_write_iv, *iv;
  387. const EVP_AEAD *aead = s->s3->tmp.new_aead;
  388. size_t key_len, iv_len, mac_secret_len;
  389. const uint8_t *key_data;
  390. /* Reset sequence number to zero. */
  391. if (!SSL_IS_DTLS(s)) {
  392. memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
  393. }
  394. mac_secret_len = s->s3->tmp.new_mac_secret_len;
  395. iv_len = s->s3->tmp.new_fixed_iv_len;
  396. if (aead == NULL) {
  397. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  398. return 0;
  399. }
  400. key_len = EVP_AEAD_key_length(aead);
  401. if (mac_secret_len > 0) {
  402. /* For "stateful" AEADs (i.e. compatibility with pre-AEAD cipher
  403. * suites) the key length reported by |EVP_AEAD_key_length| will
  404. * include the MAC and IV key bytes. */
  405. if (key_len < mac_secret_len + iv_len) {
  406. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  407. return 0;
  408. }
  409. key_len -= mac_secret_len + iv_len;
  410. }
  411. key_data = s->s3->tmp.key_block;
  412. client_write_mac_secret = key_data;
  413. key_data += mac_secret_len;
  414. server_write_mac_secret = key_data;
  415. key_data += mac_secret_len;
  416. client_write_key = key_data;
  417. key_data += key_len;
  418. server_write_key = key_data;
  419. key_data += key_len;
  420. client_write_iv = key_data;
  421. key_data += iv_len;
  422. server_write_iv = key_data;
  423. key_data += iv_len;
  424. if (use_client_keys) {
  425. mac_secret = client_write_mac_secret;
  426. key = client_write_key;
  427. iv = client_write_iv;
  428. } else {
  429. mac_secret = server_write_mac_secret;
  430. key = server_write_key;
  431. iv = server_write_iv;
  432. }
  433. if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length) {
  434. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  435. return 0;
  436. }
  437. return tls1_change_cipher_state_aead(s, is_read, key, key_len, iv, iv_len,
  438. mac_secret, mac_secret_len);
  439. }
  440. int tls1_setup_key_block(SSL *s) {
  441. uint8_t *p;
  442. const EVP_AEAD *aead = NULL;
  443. int ret = 0;
  444. size_t mac_secret_len, fixed_iv_len, variable_iv_len, key_len;
  445. size_t key_block_len;
  446. if (s->s3->tmp.key_block_length != 0) {
  447. return 1;
  448. }
  449. if (s->session->cipher == NULL) {
  450. goto cipher_unavailable_err;
  451. }
  452. if (!ssl_cipher_get_evp_aead(&aead, &mac_secret_len, &fixed_iv_len,
  453. s->session->cipher,
  454. ssl3_version_from_wire(s, s->version))) {
  455. goto cipher_unavailable_err;
  456. }
  457. key_len = EVP_AEAD_key_length(aead);
  458. variable_iv_len = EVP_AEAD_nonce_length(aead);
  459. if (mac_secret_len > 0) {
  460. /* For "stateful" AEADs (i.e. compatibility with pre-AEAD cipher suites) the
  461. * key length reported by |EVP_AEAD_key_length| will include the MAC key
  462. * bytes and initial implicit IV. */
  463. if (key_len < mac_secret_len + fixed_iv_len) {
  464. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_INTERNAL_ERROR);
  465. return 0;
  466. }
  467. key_len -= mac_secret_len + fixed_iv_len;
  468. } else {
  469. /* The nonce is split into a fixed portion and a variable portion. */
  470. if (variable_iv_len < fixed_iv_len) {
  471. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_INTERNAL_ERROR);
  472. return 0;
  473. }
  474. variable_iv_len -= fixed_iv_len;
  475. }
  476. assert(mac_secret_len < 256);
  477. assert(fixed_iv_len < 256);
  478. assert(variable_iv_len < 256);
  479. s->s3->tmp.new_aead = aead;
  480. s->s3->tmp.new_mac_secret_len = (uint8_t)mac_secret_len;
  481. s->s3->tmp.new_fixed_iv_len = (uint8_t)fixed_iv_len;
  482. s->s3->tmp.new_variable_iv_len = (uint8_t)variable_iv_len;
  483. key_block_len = key_len + mac_secret_len + fixed_iv_len;
  484. key_block_len *= 2;
  485. ssl3_cleanup_key_block(s);
  486. p = (uint8_t *)OPENSSL_malloc(key_block_len);
  487. if (p == NULL) {
  488. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
  489. goto err;
  490. }
  491. s->s3->tmp.key_block_length = key_block_len;
  492. s->s3->tmp.key_block = p;
  493. if (!tls1_generate_key_block(s, p, key_block_len)) {
  494. goto err;
  495. }
  496. if (!SSL_USE_EXPLICIT_IV(s) &&
  497. (s->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0) {
  498. /* enable vulnerability countermeasure for CBC ciphers with known-IV
  499. * problem (http://www.openssl.org/~bodo/tls-cbc.txt). */
  500. s->s3->need_record_splitting = 1;
  501. if (s->session->cipher != NULL &&
  502. s->session->cipher->algorithm_enc == SSL_RC4) {
  503. s->s3->need_record_splitting = 0;
  504. }
  505. }
  506. ret = 1;
  507. err:
  508. return ret;
  509. cipher_unavailable_err:
  510. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block,
  511. SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
  512. return 0;
  513. }
  514. /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|,
  515. * respectively. It returns one on success and zero on failure. */
  516. int tls1_enc(SSL *s, int send) {
  517. SSL3_RECORD *rec;
  518. const SSL_AEAD_CTX *aead;
  519. if (send) {
  520. rec = &s->s3->wrec;
  521. aead = s->aead_write_ctx;
  522. } else {
  523. rec = &s->s3->rrec;
  524. aead = s->aead_read_ctx;
  525. }
  526. if (aead == NULL) {
  527. /* Handle the initial NULL cipher. */
  528. memmove(rec->data, rec->input, rec->length);
  529. rec->input = rec->data;
  530. return 1;
  531. }
  532. uint8_t ad[13], *seq, *in, *out, nonce[EVP_AEAD_MAX_NONCE_LENGTH];
  533. unsigned nonce_used;
  534. size_t n, ad_len;
  535. seq = send ? s->s3->write_sequence : s->s3->read_sequence;
  536. if (SSL_IS_DTLS(s)) {
  537. uint8_t dtlsseq[9], *p = dtlsseq;
  538. s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
  539. memcpy(p, &seq[2], 6);
  540. memcpy(ad, dtlsseq, 8);
  541. } else {
  542. memcpy(ad, seq, 8);
  543. if (!ssl3_record_sequence_update(seq, 8)) {
  544. return 0;
  545. }
  546. }
  547. ad[8] = rec->type;
  548. ad_len = 9;
  549. if (!aead->omit_version_in_ad) {
  550. ad[ad_len++] = (uint8_t)(s->version >> 8);
  551. ad[ad_len++] = (uint8_t)(s->version);
  552. }
  553. if (aead->fixed_nonce_len + aead->variable_nonce_len > sizeof(nonce)) {
  554. OPENSSL_PUT_ERROR(SSL, tls1_enc, ERR_R_INTERNAL_ERROR);
  555. return 0;
  556. }
  557. memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
  558. nonce_used = aead->fixed_nonce_len;
  559. if (send) {
  560. size_t len = rec->length;
  561. size_t eivlen = 0;
  562. in = rec->input;
  563. out = rec->data;
  564. uint8_t *variable_nonce = nonce + nonce_used;
  565. if (aead->random_variable_nonce) {
  566. assert(aead->variable_nonce_included_in_record);
  567. if (!RAND_bytes(nonce + nonce_used, aead->variable_nonce_len)) {
  568. return 0;
  569. }
  570. } else {
  571. /* When sending we use the sequence number as the variable part of the
  572. * nonce. */
  573. if (aead->variable_nonce_len != 8) {
  574. OPENSSL_PUT_ERROR(SSL, tls1_enc, ERR_R_INTERNAL_ERROR);
  575. return 0;
  576. }
  577. memcpy(nonce + nonce_used, ad, aead->variable_nonce_len);
  578. }
  579. nonce_used += aead->variable_nonce_len;
  580. /* in do_ssl3_write, rec->input is moved forward by variable_nonce_len in
  581. * order to leave space for the variable nonce. Thus we can copy the
  582. * sequence number bytes into place without overwriting any of the
  583. * plaintext. */
  584. if (aead->variable_nonce_included_in_record) {
  585. memcpy(out, variable_nonce, aead->variable_nonce_len);
  586. len -= aead->variable_nonce_len;
  587. eivlen = aead->variable_nonce_len;
  588. }
  589. if (!aead->omit_length_in_ad) {
  590. ad[ad_len++] = len >> 8;
  591. ad[ad_len++] = len & 0xff;
  592. }
  593. if (!EVP_AEAD_CTX_seal(&aead->ctx, out + eivlen, &n, len + aead->tag_len,
  594. nonce, nonce_used, in + eivlen, len, ad, ad_len)) {
  595. return 0;
  596. }
  597. if (aead->variable_nonce_included_in_record) {
  598. n += aead->variable_nonce_len;
  599. }
  600. } else {
  601. /* receive */
  602. size_t len = rec->length;
  603. if (rec->data != rec->input) {
  604. OPENSSL_PUT_ERROR(SSL, tls1_enc, ERR_R_INTERNAL_ERROR);
  605. return 0;
  606. }
  607. out = in = rec->input;
  608. if (len < aead->variable_nonce_len) {
  609. return 0;
  610. }
  611. memcpy(nonce + nonce_used,
  612. aead->variable_nonce_included_in_record ? in : ad,
  613. aead->variable_nonce_len);
  614. nonce_used += aead->variable_nonce_len;
  615. if (aead->variable_nonce_included_in_record) {
  616. in += aead->variable_nonce_len;
  617. len -= aead->variable_nonce_len;
  618. out += aead->variable_nonce_len;
  619. }
  620. if (!aead->omit_length_in_ad) {
  621. if (len < aead->tag_len) {
  622. return 0;
  623. }
  624. size_t plaintext_len = len - aead->tag_len;
  625. ad[ad_len++] = plaintext_len >> 8;
  626. ad[ad_len++] = plaintext_len & 0xff;
  627. }
  628. if (!EVP_AEAD_CTX_open(&aead->ctx, out, &n, rec->length, nonce, nonce_used, in,
  629. len, ad, ad_len)) {
  630. return 0;
  631. }
  632. rec->data = rec->input = out;
  633. }
  634. rec->length = n;
  635. return 1;
  636. }
  637. int tls1_cert_verify_mac(SSL *s, int md_nid, uint8_t *out) {
  638. unsigned int ret;
  639. EVP_MD_CTX ctx, *d = NULL;
  640. int i;
  641. if (s->s3->handshake_buffer &&
  642. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  643. return 0;
  644. }
  645. for (i = 0; i < SSL_MAX_DIGEST; i++) {
  646. if (s->s3->handshake_dgst[i] &&
  647. EVP_MD_CTX_type(s->s3->handshake_dgst[i]) == md_nid) {
  648. d = s->s3->handshake_dgst[i];
  649. break;
  650. }
  651. }
  652. if (!d) {
  653. OPENSSL_PUT_ERROR(SSL, tls1_cert_verify_mac, SSL_R_NO_REQUIRED_DIGEST);
  654. return 0;
  655. }
  656. EVP_MD_CTX_init(&ctx);
  657. if (!EVP_MD_CTX_copy_ex(&ctx, d)) {
  658. EVP_MD_CTX_cleanup(&ctx);
  659. return 0;
  660. }
  661. EVP_DigestFinal_ex(&ctx, out, &ret);
  662. EVP_MD_CTX_cleanup(&ctx);
  663. return ret;
  664. }
  665. /* tls1_handshake_digest calculates the current handshake hash and writes it to
  666. * |out|, which has space for |out_len| bytes. It returns the number of bytes
  667. * written or -1 in the event of an error. This function works on a copy of the
  668. * underlying digests so can be called multiple times and prior to the final
  669. * update etc. */
  670. int tls1_handshake_digest(SSL *s, uint8_t *out, size_t out_len) {
  671. const EVP_MD *md;
  672. EVP_MD_CTX ctx;
  673. int err = 0, len = 0;
  674. size_t i;
  675. uint32_t mask;
  676. EVP_MD_CTX_init(&ctx);
  677. for (i = 0; ssl_get_handshake_digest(&mask, &md, i); i++) {
  678. size_t hash_size;
  679. unsigned int digest_len;
  680. EVP_MD_CTX *hdgst = s->s3->handshake_dgst[i];
  681. if ((mask & ssl_get_algorithm2(s)) == 0) {
  682. continue;
  683. }
  684. hash_size = EVP_MD_size(md);
  685. if (!hdgst ||
  686. hash_size > out_len ||
  687. !EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
  688. !EVP_DigestFinal_ex(&ctx, out, &digest_len) ||
  689. digest_len != hash_size /* internal error */) {
  690. err = 1;
  691. break;
  692. }
  693. out += digest_len;
  694. out_len -= digest_len;
  695. len += digest_len;
  696. }
  697. EVP_MD_CTX_cleanup(&ctx);
  698. if (err != 0) {
  699. return -1;
  700. }
  701. return len;
  702. }
  703. int tls1_final_finish_mac(SSL *s, const char *str, int slen, uint8_t *out) {
  704. uint8_t buf[2 * EVP_MAX_MD_SIZE];
  705. int err = 0;
  706. int digests_len;
  707. if (s->s3->handshake_buffer &&
  708. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  709. return 0;
  710. }
  711. digests_len = tls1_handshake_digest(s, buf, sizeof(buf));
  712. if (digests_len < 0) {
  713. err = 1;
  714. digests_len = 0;
  715. }
  716. if (!s->enc_method->prf(s, out, 12, s->session->master_key,
  717. s->session->master_key_length, str, slen, buf,
  718. digests_len, NULL, 0)) {
  719. err = 1;
  720. }
  721. if (err) {
  722. return 0;
  723. } else {
  724. return 12;
  725. }
  726. }
  727. int tls1_generate_master_secret(SSL *s, uint8_t *out, const uint8_t *premaster,
  728. size_t premaster_len) {
  729. if (s->s3->tmp.extended_master_secret) {
  730. uint8_t digests[2 * EVP_MAX_MD_SIZE];
  731. int digests_len;
  732. /* The master secret is based on the handshake hash just after sending the
  733. * ClientKeyExchange. However, we might have a client certificate to send,
  734. * in which case we might need different hashes for the verification and
  735. * thus still need the handshake buffer around. Keeping both a handshake
  736. * buffer *and* running hashes isn't yet supported so, when it comes to
  737. * calculating the Finished hash, we'll have to hash the handshake buffer
  738. * again. */
  739. if (s->s3->handshake_buffer &&
  740. !ssl3_digest_cached_records(s, dont_free_handshake_buffer)) {
  741. return 0;
  742. }
  743. digests_len = tls1_handshake_digest(s, digests, sizeof(digests));
  744. if (digests_len == -1) {
  745. return 0;
  746. }
  747. if (!s->enc_method->prf(s, out, SSL3_MASTER_SECRET_SIZE, premaster,
  748. premaster_len, TLS_MD_EXTENDED_MASTER_SECRET_CONST,
  749. TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE, digests,
  750. digests_len, NULL, 0)) {
  751. return 0;
  752. }
  753. } else {
  754. if (!s->enc_method->prf(s, out, SSL3_MASTER_SECRET_SIZE, premaster,
  755. premaster_len, TLS_MD_MASTER_SECRET_CONST,
  756. TLS_MD_MASTER_SECRET_CONST_SIZE,
  757. s->s3->client_random, SSL3_RANDOM_SIZE,
  758. s->s3->server_random, SSL3_RANDOM_SIZE)) {
  759. return 0;
  760. }
  761. }
  762. return SSL3_MASTER_SECRET_SIZE;
  763. }
  764. int tls1_export_keying_material(SSL *s, uint8_t *out, size_t out_len,
  765. const char *label, size_t label_len,
  766. const uint8_t *context, size_t context_len,
  767. int use_context) {
  768. if (!s->s3->have_version || s->version == SSL3_VERSION) {
  769. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material,
  770. ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  771. return 0;
  772. }
  773. size_t seed_len = 2 * SSL3_RANDOM_SIZE;
  774. if (use_context) {
  775. if (context_len >= 1u << 16) {
  776. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_OVERFLOW);
  777. return 0;
  778. }
  779. seed_len += 2 + context_len;
  780. }
  781. uint8_t *seed = OPENSSL_malloc(seed_len);
  782. if (seed == NULL) {
  783. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_MALLOC_FAILURE);
  784. return 0;
  785. }
  786. memcpy(seed, s->s3->client_random, SSL3_RANDOM_SIZE);
  787. memcpy(seed + SSL3_RANDOM_SIZE, s->s3->server_random, SSL3_RANDOM_SIZE);
  788. if (use_context) {
  789. seed[2 * SSL3_RANDOM_SIZE] = (uint8_t)(context_len >> 8);
  790. seed[2 * SSL3_RANDOM_SIZE + 1] = (uint8_t)context_len;
  791. memcpy(seed + 2 * SSL3_RANDOM_SIZE + 2, context, context_len);
  792. }
  793. int ret = s->enc_method->prf(s, out, out_len, s->session->master_key,
  794. s->session->master_key_length, label, label_len,
  795. seed, seed_len, NULL, 0);
  796. OPENSSL_free(seed);
  797. return ret;
  798. }
  799. int tls1_alert_code(int code) {
  800. switch (code) {
  801. case SSL_AD_CLOSE_NOTIFY:
  802. return SSL3_AD_CLOSE_NOTIFY;
  803. case SSL_AD_UNEXPECTED_MESSAGE:
  804. return SSL3_AD_UNEXPECTED_MESSAGE;
  805. case SSL_AD_BAD_RECORD_MAC:
  806. return SSL3_AD_BAD_RECORD_MAC;
  807. case SSL_AD_DECRYPTION_FAILED:
  808. return TLS1_AD_DECRYPTION_FAILED;
  809. case SSL_AD_RECORD_OVERFLOW:
  810. return TLS1_AD_RECORD_OVERFLOW;
  811. case SSL_AD_DECOMPRESSION_FAILURE:
  812. return SSL3_AD_DECOMPRESSION_FAILURE;
  813. case SSL_AD_HANDSHAKE_FAILURE:
  814. return SSL3_AD_HANDSHAKE_FAILURE;
  815. case SSL_AD_NO_CERTIFICATE:
  816. return -1;
  817. case SSL_AD_BAD_CERTIFICATE:
  818. return SSL3_AD_BAD_CERTIFICATE;
  819. case SSL_AD_UNSUPPORTED_CERTIFICATE:
  820. return SSL3_AD_UNSUPPORTED_CERTIFICATE;
  821. case SSL_AD_CERTIFICATE_REVOKED:
  822. return SSL3_AD_CERTIFICATE_REVOKED;
  823. case SSL_AD_CERTIFICATE_EXPIRED:
  824. return SSL3_AD_CERTIFICATE_EXPIRED;
  825. case SSL_AD_CERTIFICATE_UNKNOWN:
  826. return SSL3_AD_CERTIFICATE_UNKNOWN;
  827. case SSL_AD_ILLEGAL_PARAMETER:
  828. return SSL3_AD_ILLEGAL_PARAMETER;
  829. case SSL_AD_UNKNOWN_CA:
  830. return TLS1_AD_UNKNOWN_CA;
  831. case SSL_AD_ACCESS_DENIED:
  832. return TLS1_AD_ACCESS_DENIED;
  833. case SSL_AD_DECODE_ERROR:
  834. return TLS1_AD_DECODE_ERROR;
  835. case SSL_AD_DECRYPT_ERROR:
  836. return TLS1_AD_DECRYPT_ERROR;
  837. case SSL_AD_EXPORT_RESTRICTION:
  838. return TLS1_AD_EXPORT_RESTRICTION;
  839. case SSL_AD_PROTOCOL_VERSION:
  840. return TLS1_AD_PROTOCOL_VERSION;
  841. case SSL_AD_INSUFFICIENT_SECURITY:
  842. return TLS1_AD_INSUFFICIENT_SECURITY;
  843. case SSL_AD_INTERNAL_ERROR:
  844. return TLS1_AD_INTERNAL_ERROR;
  845. case SSL_AD_USER_CANCELLED:
  846. return TLS1_AD_USER_CANCELLED;
  847. case SSL_AD_NO_RENEGOTIATION:
  848. return TLS1_AD_NO_RENEGOTIATION;
  849. case SSL_AD_UNSUPPORTED_EXTENSION:
  850. return TLS1_AD_UNSUPPORTED_EXTENSION;
  851. case SSL_AD_CERTIFICATE_UNOBTAINABLE:
  852. return TLS1_AD_CERTIFICATE_UNOBTAINABLE;
  853. case SSL_AD_UNRECOGNIZED_NAME:
  854. return TLS1_AD_UNRECOGNIZED_NAME;
  855. case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
  856. return TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
  857. case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
  858. return TLS1_AD_BAD_CERTIFICATE_HASH_VALUE;
  859. case SSL_AD_UNKNOWN_PSK_IDENTITY:
  860. return TLS1_AD_UNKNOWN_PSK_IDENTITY;
  861. case SSL_AD_INAPPROPRIATE_FALLBACK:
  862. return SSL3_AD_INAPPROPRIATE_FALLBACK;
  863. default:
  864. return -1;
  865. }
  866. }