Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1043 lignes
33 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 <stdio.h>
  136. #include <assert.h>
  137. #include <openssl/err.h>
  138. #include <openssl/evp.h>
  139. #include <openssl/hmac.h>
  140. #include <openssl/md5.h>
  141. #include <openssl/mem.h>
  142. #include <openssl/obj.h>
  143. #include <openssl/rand.h>
  144. #include "ssl_locl.h"
  145. /* tls1_P_hash computes the TLS P_<hash> function as described in RFC 5246,
  146. * section 5. It writes |out_len| bytes to |out|, using |md| as the hash and
  147. * |secret| as the secret. |seed1| through |seed3| are concatenated to form the
  148. * seed parameter. It returns one on success and zero on failure. */
  149. static int tls1_P_hash(uint8_t *out, size_t out_len, const EVP_MD *md,
  150. const uint8_t *secret, size_t secret_len,
  151. const uint8_t *seed1, size_t seed1_len,
  152. const uint8_t *seed2, size_t seed2_len,
  153. const uint8_t *seed3, size_t seed3_len) {
  154. size_t chunk;
  155. HMAC_CTX ctx, ctx_tmp, ctx_init;
  156. uint8_t A1[EVP_MAX_MD_SIZE];
  157. unsigned A1_len;
  158. int ret = 0;
  159. chunk = EVP_MD_size(md);
  160. HMAC_CTX_init(&ctx);
  161. HMAC_CTX_init(&ctx_tmp);
  162. HMAC_CTX_init(&ctx_init);
  163. if (!HMAC_Init_ex(&ctx_init, secret, secret_len, md, NULL) ||
  164. !HMAC_CTX_copy_ex(&ctx, &ctx_init) ||
  165. (seed1_len && !HMAC_Update(&ctx, seed1, seed1_len)) ||
  166. (seed2_len && !HMAC_Update(&ctx, seed2, seed2_len)) ||
  167. (seed3_len && !HMAC_Update(&ctx, seed3, seed3_len)) ||
  168. !HMAC_Final(&ctx, A1, &A1_len)) {
  169. goto err;
  170. }
  171. for (;;) {
  172. /* Reinit mac contexts. */
  173. if (!HMAC_CTX_copy_ex(&ctx, &ctx_init) ||
  174. !HMAC_Update(&ctx, A1, A1_len) ||
  175. (out_len > chunk && !HMAC_CTX_copy_ex(&ctx_tmp, &ctx)) ||
  176. (seed1_len && !HMAC_Update(&ctx, seed1, seed1_len)) ||
  177. (seed2_len && !HMAC_Update(&ctx, seed2, seed2_len)) ||
  178. (seed3_len && !HMAC_Update(&ctx, seed3, seed3_len))) {
  179. goto err;
  180. }
  181. if (out_len > chunk) {
  182. unsigned len;
  183. if (!HMAC_Final(&ctx, out, &len)) {
  184. goto err;
  185. }
  186. assert(len == chunk);
  187. out += len;
  188. out_len -= len;
  189. /* Calculate the next A1 value. */
  190. if (!HMAC_Final(&ctx_tmp, A1, &A1_len)) {
  191. goto err;
  192. }
  193. } else {
  194. /* Last chunk. */
  195. if (!HMAC_Final(&ctx, A1, &A1_len)) {
  196. goto err;
  197. }
  198. memcpy(out, A1, out_len);
  199. break;
  200. }
  201. }
  202. ret = 1;
  203. err:
  204. HMAC_CTX_cleanup(&ctx);
  205. HMAC_CTX_cleanup(&ctx_tmp);
  206. HMAC_CTX_cleanup(&ctx_init);
  207. OPENSSL_cleanse(A1, sizeof(A1));
  208. return ret;
  209. }
  210. int tls1_prf(SSL *s, uint8_t *out, size_t out_len, const uint8_t *secret,
  211. size_t secret_len, const char *label, size_t label_len,
  212. const uint8_t *seed1, size_t seed1_len,
  213. const uint8_t *seed2, size_t seed2_len) {
  214. size_t idx, len, count, i;
  215. const uint8_t *S1;
  216. long m;
  217. const EVP_MD *md;
  218. int ret = 0;
  219. uint8_t *tmp;
  220. if (out_len == 0) {
  221. return 1;
  222. }
  223. /* Allocate a temporary buffer. */
  224. tmp = OPENSSL_malloc(out_len);
  225. if (tmp == NULL) {
  226. OPENSSL_PUT_ERROR(SSL, tls1_prf, ERR_R_MALLOC_FAILURE);
  227. return 0;
  228. }
  229. /* Count number of digests and partition |secret| evenly. */
  230. count = 0;
  231. for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
  232. if ((m << TLS1_PRF_DGST_SHIFT) & ssl_get_algorithm2(s)) {
  233. count++;
  234. }
  235. }
  236. /* TODO(davidben): The only case where count isn't 1 is the old MD5/SHA-1
  237. * combination. The logic around multiple handshake digests can probably be
  238. * simplified. */
  239. assert(count == 1 || count == 2);
  240. len = secret_len / count;
  241. if (count == 1) {
  242. secret_len = 0;
  243. }
  244. S1 = secret;
  245. memset(out, 0, out_len);
  246. for (idx = 0; ssl_get_handshake_digest(idx, &m, &md); idx++) {
  247. if ((m << TLS1_PRF_DGST_SHIFT) & ssl_get_algorithm2(s)) {
  248. /* If |count| is 2 and |secret_len| is odd, |secret| is partitioned into
  249. * two halves with an overlapping byte. */
  250. if (!tls1_P_hash(tmp, out_len, md, S1, len + (secret_len & 1),
  251. (const uint8_t *)label, label_len, seed1, seed1_len,
  252. seed2, seed2_len)) {
  253. goto err;
  254. }
  255. S1 += len;
  256. for (i = 0; i < out_len; i++) {
  257. out[i] ^= tmp[i];
  258. }
  259. }
  260. }
  261. ret = 1;
  262. err:
  263. OPENSSL_cleanse(tmp, out_len);
  264. OPENSSL_free(tmp);
  265. return ret;
  266. }
  267. static int tls1_generate_key_block(SSL *s, uint8_t *out, size_t out_len) {
  268. return s->enc_method->prf(s, out, out_len, s->session->master_key,
  269. s->session->master_key_length,
  270. TLS_MD_KEY_EXPANSION_CONST,
  271. TLS_MD_KEY_EXPANSION_CONST_SIZE,
  272. s->s3->server_random, SSL3_RANDOM_SIZE,
  273. s->s3->client_random,
  274. SSL3_RANDOM_SIZE);
  275. }
  276. /* tls1_aead_ctx_init allocates |*aead_ctx|, if needed and returns 1. It
  277. * returns 0 on malloc error. */
  278. static int tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx) {
  279. if (*aead_ctx != NULL) {
  280. EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
  281. } else {
  282. *aead_ctx = (SSL_AEAD_CTX *)OPENSSL_malloc(sizeof(SSL_AEAD_CTX));
  283. if (*aead_ctx == NULL) {
  284. OPENSSL_PUT_ERROR(SSL, tls1_aead_ctx_init, ERR_R_MALLOC_FAILURE);
  285. return 0;
  286. }
  287. }
  288. return 1;
  289. }
  290. static int tls1_change_cipher_state_aead(SSL *s, char is_read,
  291. const uint8_t *key, unsigned key_len,
  292. const uint8_t *iv, unsigned iv_len,
  293. const uint8_t *mac_secret,
  294. unsigned mac_secret_len) {
  295. const EVP_AEAD *aead = s->s3->tmp.new_aead;
  296. SSL_AEAD_CTX *aead_ctx;
  297. /* merged_key is used to merge the MAC, cipher, and IV keys for an AEAD which
  298. * simulates pre-AEAD cipher suites. */
  299. uint8_t merged_key[EVP_AEAD_MAX_KEY_LENGTH];
  300. if (mac_secret_len > 0) {
  301. /* This is a "stateful" AEAD (for compatibility with pre-AEAD cipher
  302. * suites). */
  303. if (mac_secret_len + key_len + iv_len > sizeof(merged_key)) {
  304. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead,
  305. ERR_R_INTERNAL_ERROR);
  306. return 0;
  307. }
  308. memcpy(merged_key, mac_secret, mac_secret_len);
  309. memcpy(merged_key + mac_secret_len, key, key_len);
  310. memcpy(merged_key + mac_secret_len + key_len, iv, iv_len);
  311. key = merged_key;
  312. key_len += mac_secret_len;
  313. key_len += iv_len;
  314. }
  315. if (is_read) {
  316. if (!tls1_aead_ctx_init(&s->aead_read_ctx)) {
  317. return 0;
  318. }
  319. aead_ctx = s->aead_read_ctx;
  320. } else {
  321. /* When updating the cipher state for DTLS, we do not wish to overwrite the
  322. * old ones because DTLS stores pointers to them in order to implement
  323. * retransmission. See dtls1_hm_fragment_free.
  324. *
  325. * TODO(davidben): Simplify aead_write_ctx ownership, probably by just
  326. * forbidding DTLS renego. */
  327. if (SSL_IS_DTLS(s)) {
  328. s->aead_write_ctx = NULL;
  329. }
  330. if (!tls1_aead_ctx_init(&s->aead_write_ctx)) {
  331. return 0;
  332. }
  333. aead_ctx = s->aead_write_ctx;
  334. }
  335. if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
  336. EVP_AEAD_DEFAULT_TAG_LENGTH, NULL /* engine */)) {
  337. OPENSSL_free(aead_ctx);
  338. if (is_read) {
  339. s->aead_read_ctx = NULL;
  340. } else {
  341. s->aead_write_ctx = NULL;
  342. }
  343. return 0;
  344. }
  345. if (mac_secret_len == 0) {
  346. /* For a real AEAD, the IV is the fixed part of the nonce. */
  347. if (iv_len > sizeof(aead_ctx->fixed_nonce)) {
  348. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  349. return 0;
  350. }
  351. memcpy(aead_ctx->fixed_nonce, iv, iv_len);
  352. aead_ctx->fixed_nonce_len = iv_len;
  353. aead_ctx->variable_nonce_included_in_record =
  354. (s->s3->tmp.new_cipher->algorithm2 &
  355. SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_INCLUDED_IN_RECORD) != 0;
  356. aead_ctx->random_variable_nonce = 0;
  357. aead_ctx->omit_length_in_ad = 0;
  358. } else {
  359. aead_ctx->fixed_nonce_len = 0;
  360. aead_ctx->variable_nonce_included_in_record = 1;
  361. aead_ctx->random_variable_nonce = 1;
  362. aead_ctx->omit_length_in_ad = 1;
  363. }
  364. aead_ctx->variable_nonce_len = s->s3->tmp.new_variable_iv_len;
  365. aead_ctx->omit_version_in_ad = (s->version == SSL3_VERSION);
  366. if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len !=
  367. EVP_AEAD_nonce_length(aead)) {
  368. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  369. return 0;
  370. }
  371. aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
  372. return 1;
  373. }
  374. int tls1_change_cipher_state(SSL *s, int which) {
  375. /* is_read is true if we have just read a ChangeCipherSpec message - i.e. we
  376. * need to update the read cipherspec. Otherwise we have just written one. */
  377. const char is_read = (which & SSL3_CC_READ) != 0;
  378. /* use_client_keys is true if we wish to use the keys for the "client write"
  379. * direction. This is the case if we're a client sending a ChangeCipherSpec,
  380. * or a server reading a client's ChangeCipherSpec. */
  381. const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
  382. which == SSL3_CHANGE_CIPHER_SERVER_READ;
  383. const uint8_t *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
  384. const uint8_t *client_write_key, *server_write_key, *key;
  385. const uint8_t *client_write_iv, *server_write_iv, *iv;
  386. const EVP_AEAD *aead = s->s3->tmp.new_aead;
  387. size_t key_len, iv_len, mac_secret_len;
  388. const uint8_t *key_data;
  389. /* Reset sequence number to zero. */
  390. if (!SSL_IS_DTLS(s)) {
  391. memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
  392. }
  393. mac_secret_len = s->s3->tmp.new_mac_secret_len;
  394. iv_len = s->s3->tmp.new_fixed_iv_len;
  395. if (aead == NULL) {
  396. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  397. return 0;
  398. }
  399. key_len = EVP_AEAD_key_length(aead);
  400. if (mac_secret_len > 0) {
  401. /* For "stateful" AEADs (i.e. compatibility with pre-AEAD cipher
  402. * suites) the key length reported by |EVP_AEAD_key_length| will
  403. * include the MAC and IV key bytes. */
  404. if (key_len < mac_secret_len + iv_len) {
  405. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  406. return 0;
  407. }
  408. key_len -= mac_secret_len + iv_len;
  409. }
  410. key_data = s->s3->tmp.key_block;
  411. client_write_mac_secret = key_data;
  412. key_data += mac_secret_len;
  413. server_write_mac_secret = key_data;
  414. key_data += mac_secret_len;
  415. client_write_key = key_data;
  416. key_data += key_len;
  417. server_write_key = key_data;
  418. key_data += key_len;
  419. client_write_iv = key_data;
  420. key_data += iv_len;
  421. server_write_iv = key_data;
  422. key_data += iv_len;
  423. if (use_client_keys) {
  424. mac_secret = client_write_mac_secret;
  425. key = client_write_key;
  426. iv = client_write_iv;
  427. } else {
  428. mac_secret = server_write_mac_secret;
  429. key = server_write_key;
  430. iv = server_write_iv;
  431. }
  432. if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length) {
  433. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  434. return 0;
  435. }
  436. return tls1_change_cipher_state_aead(s, is_read, key, key_len, iv, iv_len,
  437. mac_secret, mac_secret_len);
  438. }
  439. int tls1_setup_key_block(SSL *s) {
  440. uint8_t *p;
  441. const EVP_AEAD *aead = NULL;
  442. int ret = 0;
  443. size_t mac_secret_len, fixed_iv_len, variable_iv_len, key_len;
  444. size_t key_block_len;
  445. if (s->s3->tmp.key_block_length != 0) {
  446. return 1;
  447. }
  448. if (s->session->cipher == NULL) {
  449. goto cipher_unavailable_err;
  450. }
  451. if (!ssl_cipher_get_evp_aead(&aead, &mac_secret_len, &fixed_iv_len,
  452. s->session->cipher,
  453. ssl3_version_from_wire(s, s->version))) {
  454. goto cipher_unavailable_err;
  455. }
  456. key_len = EVP_AEAD_key_length(aead);
  457. variable_iv_len = EVP_AEAD_nonce_length(aead);
  458. if (mac_secret_len > 0) {
  459. /* For "stateful" AEADs (i.e. compatibility with pre-AEAD cipher suites) the
  460. * key length reported by |EVP_AEAD_key_length| will include the MAC key
  461. * bytes and initial implicit IV. */
  462. if (key_len < mac_secret_len + fixed_iv_len) {
  463. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_INTERNAL_ERROR);
  464. return 0;
  465. }
  466. key_len -= mac_secret_len + fixed_iv_len;
  467. } else {
  468. /* The nonce is split into a fixed portion and a variable portion. */
  469. if (variable_iv_len < fixed_iv_len) {
  470. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_INTERNAL_ERROR);
  471. return 0;
  472. }
  473. variable_iv_len -= fixed_iv_len;
  474. }
  475. assert(mac_secret_len < 256);
  476. assert(fixed_iv_len < 256);
  477. assert(variable_iv_len < 256);
  478. s->s3->tmp.new_aead = aead;
  479. s->s3->tmp.new_mac_secret_len = (uint8_t)mac_secret_len;
  480. s->s3->tmp.new_fixed_iv_len = (uint8_t)fixed_iv_len;
  481. s->s3->tmp.new_variable_iv_len = (uint8_t)variable_iv_len;
  482. key_block_len = key_len + mac_secret_len + fixed_iv_len;
  483. key_block_len *= 2;
  484. ssl3_cleanup_key_block(s);
  485. p = (uint8_t *)OPENSSL_malloc(key_block_len);
  486. if (p == NULL) {
  487. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
  488. goto err;
  489. }
  490. s->s3->tmp.key_block_length = key_block_len;
  491. s->s3->tmp.key_block = p;
  492. if (!tls1_generate_key_block(s, p, key_block_len)) {
  493. goto err;
  494. }
  495. if (!SSL_USE_EXPLICIT_IV(s) &&
  496. (s->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0) {
  497. /* enable vulnerability countermeasure for CBC ciphers with known-IV
  498. * problem (http://www.openssl.org/~bodo/tls-cbc.txt). */
  499. s->s3->need_record_splitting = 1;
  500. if (s->session->cipher != NULL &&
  501. s->session->cipher->algorithm_enc == SSL_RC4) {
  502. s->s3->need_record_splitting = 0;
  503. }
  504. }
  505. ret = 1;
  506. err:
  507. return ret;
  508. cipher_unavailable_err:
  509. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block,
  510. SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
  511. return 0;
  512. }
  513. /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|,
  514. * respectively. It returns one on success and zero on failure. */
  515. int tls1_enc(SSL *s, int send) {
  516. SSL3_RECORD *rec;
  517. const SSL_AEAD_CTX *aead;
  518. if (send) {
  519. rec = &s->s3->wrec;
  520. aead = s->aead_write_ctx;
  521. } else {
  522. rec = &s->s3->rrec;
  523. aead = s->aead_read_ctx;
  524. }
  525. if (s->session == NULL || aead == NULL) {
  526. /* Handle the initial NULL cipher. */
  527. memmove(rec->data, rec->input, rec->length);
  528. rec->input = rec->data;
  529. return 1;
  530. }
  531. uint8_t ad[13], *seq, *in, *out, nonce[EVP_AEAD_MAX_NONCE_LENGTH];
  532. unsigned nonce_used;
  533. size_t n, ad_len;
  534. seq = send ? s->s3->write_sequence : s->s3->read_sequence;
  535. if (SSL_IS_DTLS(s)) {
  536. uint8_t dtlsseq[9], *p = dtlsseq;
  537. s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
  538. memcpy(p, &seq[2], 6);
  539. memcpy(ad, dtlsseq, 8);
  540. } else {
  541. int i;
  542. memcpy(ad, seq, 8);
  543. for (i = 7; i >= 0; i--) {
  544. ++seq[i];
  545. if (seq[i] != 0) {
  546. break;
  547. }
  548. }
  549. }
  550. ad[8] = rec->type;
  551. ad_len = 9;
  552. if (!aead->omit_version_in_ad) {
  553. ad[ad_len++] = (uint8_t)(s->version >> 8);
  554. ad[ad_len++] = (uint8_t)(s->version);
  555. }
  556. if (aead->fixed_nonce_len + aead->variable_nonce_len > sizeof(nonce)) {
  557. OPENSSL_PUT_ERROR(SSL, tls1_enc, ERR_R_INTERNAL_ERROR);
  558. return 0;
  559. }
  560. memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
  561. nonce_used = aead->fixed_nonce_len;
  562. if (send) {
  563. size_t len = rec->length;
  564. size_t eivlen = 0;
  565. in = rec->input;
  566. out = rec->data;
  567. uint8_t *variable_nonce = nonce + nonce_used;
  568. if (aead->random_variable_nonce) {
  569. assert(aead->variable_nonce_included_in_record);
  570. if (!RAND_bytes(nonce + nonce_used, aead->variable_nonce_len)) {
  571. return 0;
  572. }
  573. } else {
  574. /* When sending we use the sequence number as the variable part of the
  575. * nonce. */
  576. if (aead->variable_nonce_len != 8) {
  577. OPENSSL_PUT_ERROR(SSL, tls1_enc, ERR_R_INTERNAL_ERROR);
  578. return 0;
  579. }
  580. memcpy(nonce + nonce_used, ad, aead->variable_nonce_len);
  581. }
  582. nonce_used += aead->variable_nonce_len;
  583. /* in do_ssl3_write, rec->input is moved forward by variable_nonce_len in
  584. * order to leave space for the variable nonce. Thus we can copy the
  585. * sequence number bytes into place without overwriting any of the
  586. * plaintext. */
  587. if (aead->variable_nonce_included_in_record) {
  588. memcpy(out, variable_nonce, aead->variable_nonce_len);
  589. len -= aead->variable_nonce_len;
  590. eivlen = aead->variable_nonce_len;
  591. }
  592. if (!aead->omit_length_in_ad) {
  593. ad[ad_len++] = len >> 8;
  594. ad[ad_len++] = len & 0xff;
  595. }
  596. if (!EVP_AEAD_CTX_seal(&aead->ctx, out + eivlen, &n, len + aead->tag_len,
  597. nonce, nonce_used, in + eivlen, len, ad, ad_len)) {
  598. return 0;
  599. }
  600. if (aead->variable_nonce_included_in_record) {
  601. n += aead->variable_nonce_len;
  602. }
  603. } else {
  604. /* receive */
  605. size_t len = rec->length;
  606. if (rec->data != rec->input) {
  607. OPENSSL_PUT_ERROR(SSL, tls1_enc, ERR_R_INTERNAL_ERROR);
  608. return 0;
  609. }
  610. out = in = rec->input;
  611. if (len < aead->variable_nonce_len) {
  612. return 0;
  613. }
  614. memcpy(nonce + nonce_used,
  615. aead->variable_nonce_included_in_record ? in : ad,
  616. aead->variable_nonce_len);
  617. nonce_used += aead->variable_nonce_len;
  618. if (aead->variable_nonce_included_in_record) {
  619. in += aead->variable_nonce_len;
  620. len -= aead->variable_nonce_len;
  621. out += aead->variable_nonce_len;
  622. }
  623. if (!aead->omit_length_in_ad) {
  624. if (len < aead->tag_len) {
  625. return 0;
  626. }
  627. size_t plaintext_len = len - aead->tag_len;
  628. ad[ad_len++] = plaintext_len >> 8;
  629. ad[ad_len++] = plaintext_len & 0xff;
  630. }
  631. if (!EVP_AEAD_CTX_open(&aead->ctx, out, &n, rec->length, nonce, nonce_used, in,
  632. len, ad, ad_len)) {
  633. return 0;
  634. }
  635. rec->data = rec->input = out;
  636. }
  637. rec->length = n;
  638. return 1;
  639. }
  640. int tls1_cert_verify_mac(SSL *s, int md_nid, uint8_t *out) {
  641. unsigned int ret;
  642. EVP_MD_CTX ctx, *d = NULL;
  643. int i;
  644. if (s->s3->handshake_buffer &&
  645. !ssl3_digest_cached_records(s, free_handshake_buffer)) {
  646. return 0;
  647. }
  648. for (i = 0; i < SSL_MAX_DIGEST; i++) {
  649. if (s->s3->handshake_dgst[i] &&
  650. EVP_MD_CTX_type(s->s3->handshake_dgst[i]) == md_nid) {
  651. d = s->s3->handshake_dgst[i];
  652. break;
  653. }
  654. }
  655. if (!d) {
  656. OPENSSL_PUT_ERROR(SSL, tls1_cert_verify_mac, SSL_R_NO_REQUIRED_DIGEST);
  657. return 0;
  658. }
  659. EVP_MD_CTX_init(&ctx);
  660. EVP_MD_CTX_copy_ex(&ctx, d);
  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. long mask;
  676. EVP_MD_CTX_init(&ctx);
  677. for (i = 0; ssl_get_handshake_digest(i, &mask, &md); 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 olen,
  765. const char *label, size_t llen,
  766. const uint8_t *context, size_t contextlen,
  767. int use_context) {
  768. uint8_t *val = NULL;
  769. size_t vallen, currentvalpos;
  770. int ret;
  771. /* construct PRF arguments we construct the PRF argument ourself rather than
  772. * passing separate values into the TLS PRF to ensure that the concatenation
  773. * of values does not create a prohibited label. */
  774. vallen = llen + SSL3_RANDOM_SIZE * 2;
  775. if (use_context) {
  776. vallen += 2 + contextlen;
  777. }
  778. val = OPENSSL_malloc(vallen);
  779. if (val == NULL) {
  780. goto err2;
  781. }
  782. currentvalpos = 0;
  783. memcpy(val + currentvalpos, (uint8_t *)label, llen);
  784. currentvalpos += llen;
  785. memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
  786. currentvalpos += SSL3_RANDOM_SIZE;
  787. memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
  788. currentvalpos += SSL3_RANDOM_SIZE;
  789. if (use_context) {
  790. val[currentvalpos] = (contextlen >> 8) & 0xff;
  791. currentvalpos++;
  792. val[currentvalpos] = contextlen & 0xff;
  793. currentvalpos++;
  794. if (contextlen > 0 || context != NULL) {
  795. memcpy(val + currentvalpos, context, contextlen);
  796. }
  797. }
  798. /* disallow prohibited labels note that SSL3_RANDOM_SIZE > max(prohibited
  799. * label len) = 15, so size of val > max(prohibited label len) = 15 and the
  800. * comparisons won't have buffer overflow. */
  801. if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
  802. TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0 ||
  803. memcmp(val, TLS_MD_SERVER_FINISH_CONST,
  804. TLS_MD_SERVER_FINISH_CONST_SIZE) == 0 ||
  805. memcmp(val, TLS_MD_MASTER_SECRET_CONST,
  806. TLS_MD_MASTER_SECRET_CONST_SIZE) == 0 ||
  807. memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
  808. TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) {
  809. goto err1;
  810. }
  811. /* SSL_export_keying_material is not implemented for SSLv3, so passing
  812. * everything through the label parameter works. */
  813. assert(s->version != SSL3_VERSION);
  814. ret = s->enc_method->prf(s, out, olen, s->session->master_key,
  815. s->session->master_key_length, (const char *)val,
  816. vallen, NULL, 0, NULL, 0);
  817. goto out;
  818. err1:
  819. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material,
  820. SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
  821. ret = 0;
  822. goto out;
  823. err2:
  824. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_MALLOC_FAILURE);
  825. ret = 0;
  826. out:
  827. if (val != NULL) {
  828. OPENSSL_free(val);
  829. }
  830. return ret;
  831. }
  832. int tls1_alert_code(int code) {
  833. switch (code) {
  834. case SSL_AD_CLOSE_NOTIFY:
  835. return SSL3_AD_CLOSE_NOTIFY;
  836. case SSL_AD_UNEXPECTED_MESSAGE:
  837. return SSL3_AD_UNEXPECTED_MESSAGE;
  838. case SSL_AD_BAD_RECORD_MAC:
  839. return SSL3_AD_BAD_RECORD_MAC;
  840. case SSL_AD_DECRYPTION_FAILED:
  841. return TLS1_AD_DECRYPTION_FAILED;
  842. case SSL_AD_RECORD_OVERFLOW:
  843. return TLS1_AD_RECORD_OVERFLOW;
  844. case SSL_AD_DECOMPRESSION_FAILURE:
  845. return SSL3_AD_DECOMPRESSION_FAILURE;
  846. case SSL_AD_HANDSHAKE_FAILURE:
  847. return SSL3_AD_HANDSHAKE_FAILURE;
  848. case SSL_AD_NO_CERTIFICATE:
  849. return -1;
  850. case SSL_AD_BAD_CERTIFICATE:
  851. return SSL3_AD_BAD_CERTIFICATE;
  852. case SSL_AD_UNSUPPORTED_CERTIFICATE:
  853. return SSL3_AD_UNSUPPORTED_CERTIFICATE;
  854. case SSL_AD_CERTIFICATE_REVOKED:
  855. return SSL3_AD_CERTIFICATE_REVOKED;
  856. case SSL_AD_CERTIFICATE_EXPIRED:
  857. return SSL3_AD_CERTIFICATE_EXPIRED;
  858. case SSL_AD_CERTIFICATE_UNKNOWN:
  859. return SSL3_AD_CERTIFICATE_UNKNOWN;
  860. case SSL_AD_ILLEGAL_PARAMETER:
  861. return SSL3_AD_ILLEGAL_PARAMETER;
  862. case SSL_AD_UNKNOWN_CA:
  863. return TLS1_AD_UNKNOWN_CA;
  864. case SSL_AD_ACCESS_DENIED:
  865. return TLS1_AD_ACCESS_DENIED;
  866. case SSL_AD_DECODE_ERROR:
  867. return TLS1_AD_DECODE_ERROR;
  868. case SSL_AD_DECRYPT_ERROR:
  869. return TLS1_AD_DECRYPT_ERROR;
  870. case SSL_AD_EXPORT_RESTRICTION:
  871. return TLS1_AD_EXPORT_RESTRICTION;
  872. case SSL_AD_PROTOCOL_VERSION:
  873. return TLS1_AD_PROTOCOL_VERSION;
  874. case SSL_AD_INSUFFICIENT_SECURITY:
  875. return TLS1_AD_INSUFFICIENT_SECURITY;
  876. case SSL_AD_INTERNAL_ERROR:
  877. return TLS1_AD_INTERNAL_ERROR;
  878. case SSL_AD_USER_CANCELLED:
  879. return TLS1_AD_USER_CANCELLED;
  880. case SSL_AD_NO_RENEGOTIATION:
  881. return TLS1_AD_NO_RENEGOTIATION;
  882. case SSL_AD_UNSUPPORTED_EXTENSION:
  883. return TLS1_AD_UNSUPPORTED_EXTENSION;
  884. case SSL_AD_CERTIFICATE_UNOBTAINABLE:
  885. return TLS1_AD_CERTIFICATE_UNOBTAINABLE;
  886. case SSL_AD_UNRECOGNIZED_NAME:
  887. return TLS1_AD_UNRECOGNIZED_NAME;
  888. case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE:
  889. return TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
  890. case SSL_AD_BAD_CERTIFICATE_HASH_VALUE:
  891. return TLS1_AD_BAD_CERTIFICATE_HASH_VALUE;
  892. case SSL_AD_UNKNOWN_PSK_IDENTITY:
  893. return TLS1_AD_UNKNOWN_PSK_IDENTITY;
  894. case SSL_AD_INAPPROPRIATE_FALLBACK:
  895. return SSL3_AD_INAPPROPRIATE_FALLBACK;
  896. default:
  897. return -1;
  898. }
  899. }