Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

1375 rader
40 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. /* seed1 through seed5 are virtually concatenated */
  146. static int tls1_P_hash(const EVP_MD *md, const unsigned char *sec,
  147. int sec_len,
  148. const void *seed1, int seed1_len,
  149. const void *seed2, int seed2_len,
  150. const void *seed3, int seed3_len,
  151. const void *seed4, int seed4_len,
  152. const void *seed5, int seed5_len,
  153. unsigned char *out, int olen)
  154. {
  155. int chunk;
  156. size_t j;
  157. EVP_MD_CTX ctx, ctx_tmp, ctx_init;
  158. EVP_PKEY *mac_key;
  159. unsigned char A1[EVP_MAX_MD_SIZE];
  160. size_t A1_len;
  161. int ret = 0;
  162. chunk=EVP_MD_size(md);
  163. EVP_MD_CTX_init(&ctx);
  164. EVP_MD_CTX_init(&ctx_tmp);
  165. EVP_MD_CTX_init(&ctx_init);
  166. mac_key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, sec, sec_len);
  167. if (!mac_key)
  168. goto err;
  169. if (!EVP_DigestSignInit(&ctx_init,NULL,md, NULL, mac_key))
  170. goto err;
  171. if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
  172. goto err;
  173. if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
  174. goto err;
  175. if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
  176. goto err;
  177. if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
  178. goto err;
  179. if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
  180. goto err;
  181. if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
  182. goto err;
  183. A1_len = EVP_MAX_MD_SIZE;
  184. if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
  185. goto err;
  186. for (;;)
  187. {
  188. /* Reinit mac contexts */
  189. if (!EVP_MD_CTX_copy_ex(&ctx,&ctx_init))
  190. goto err;
  191. if (!EVP_DigestSignUpdate(&ctx,A1,A1_len))
  192. goto err;
  193. if (olen>chunk && !EVP_MD_CTX_copy_ex(&ctx_tmp,&ctx))
  194. goto err;
  195. if (seed1 && !EVP_DigestSignUpdate(&ctx,seed1,seed1_len))
  196. goto err;
  197. if (seed2 && !EVP_DigestSignUpdate(&ctx,seed2,seed2_len))
  198. goto err;
  199. if (seed3 && !EVP_DigestSignUpdate(&ctx,seed3,seed3_len))
  200. goto err;
  201. if (seed4 && !EVP_DigestSignUpdate(&ctx,seed4,seed4_len))
  202. goto err;
  203. if (seed5 && !EVP_DigestSignUpdate(&ctx,seed5,seed5_len))
  204. goto err;
  205. if (olen > chunk)
  206. {
  207. j = olen;
  208. if (!EVP_DigestSignFinal(&ctx,out,&j))
  209. goto err;
  210. out+=j;
  211. olen-=j;
  212. /* calc the next A1 value */
  213. A1_len = EVP_MAX_MD_SIZE;
  214. if (!EVP_DigestSignFinal(&ctx_tmp,A1,&A1_len))
  215. goto err;
  216. }
  217. else /* last one */
  218. {
  219. A1_len = EVP_MAX_MD_SIZE;
  220. if (!EVP_DigestSignFinal(&ctx,A1,&A1_len))
  221. goto err;
  222. memcpy(out,A1,olen);
  223. break;
  224. }
  225. }
  226. ret = 1;
  227. err:
  228. EVP_PKEY_free(mac_key);
  229. EVP_MD_CTX_cleanup(&ctx);
  230. EVP_MD_CTX_cleanup(&ctx_tmp);
  231. EVP_MD_CTX_cleanup(&ctx_init);
  232. OPENSSL_cleanse(A1,sizeof(A1));
  233. return ret;
  234. }
  235. /* seed1 through seed5 are virtually concatenated */
  236. static int tls1_PRF(long digest_mask,
  237. const void *seed1, int seed1_len,
  238. const void *seed2, int seed2_len,
  239. const void *seed3, int seed3_len,
  240. const void *seed4, int seed4_len,
  241. const void *seed5, int seed5_len,
  242. const unsigned char *sec, int slen,
  243. unsigned char *out1,
  244. unsigned char *out2, int olen)
  245. {
  246. int len,i,idx,count;
  247. const unsigned char *S1;
  248. long m;
  249. const EVP_MD *md;
  250. int ret = 0;
  251. /* Count number of digests and partition sec evenly */
  252. count=0;
  253. for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
  254. if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) count++;
  255. }
  256. len=slen/count;
  257. if (count == 1)
  258. slen = 0;
  259. S1=sec;
  260. memset(out1,0,olen);
  261. for (idx=0;ssl_get_handshake_digest(idx,&m,&md);idx++) {
  262. if ((m<<TLS1_PRF_DGST_SHIFT) & digest_mask) {
  263. if (!md) {
  264. OPENSSL_PUT_ERROR(SSL, tls1_PRF, SSL_R_UNSUPPORTED_DIGEST_TYPE);
  265. goto err;
  266. }
  267. if (!tls1_P_hash(md ,S1,len+(slen&1),
  268. seed1,seed1_len,seed2,seed2_len,seed3,seed3_len,seed4,seed4_len,seed5,seed5_len,
  269. out2,olen))
  270. goto err;
  271. S1+=len;
  272. for (i=0; i<olen; i++)
  273. {
  274. out1[i]^=out2[i];
  275. }
  276. }
  277. }
  278. ret = 1;
  279. err:
  280. return ret;
  281. }
  282. static int tls1_generate_key_block(SSL *s, unsigned char *km,
  283. unsigned char *tmp, int num)
  284. {
  285. int ret;
  286. ret = tls1_PRF(ssl_get_algorithm2(s),
  287. TLS_MD_KEY_EXPANSION_CONST,TLS_MD_KEY_EXPANSION_CONST_SIZE,
  288. s->s3->server_random,SSL3_RANDOM_SIZE,
  289. s->s3->client_random,SSL3_RANDOM_SIZE,
  290. NULL,0,NULL,0,
  291. s->session->master_key,s->session->master_key_length,
  292. km,tmp,num);
  293. #ifdef KSSL_DEBUG
  294. printf("tls1_generate_key_block() ==> %d byte master_key =\n\t",
  295. s->session->master_key_length);
  296. {
  297. int i;
  298. for (i=0; i < s->session->master_key_length; i++)
  299. {
  300. printf("%02X", s->session->master_key[i]);
  301. }
  302. printf("\n"); }
  303. #endif /* KSSL_DEBUG */
  304. return ret;
  305. }
  306. /* tls1_aead_ctx_init allocates |*aead_ctx|, if needed and returns 1. It
  307. * returns 0 on malloc error. */
  308. static int tls1_aead_ctx_init(SSL_AEAD_CTX **aead_ctx)
  309. {
  310. if (*aead_ctx != NULL)
  311. EVP_AEAD_CTX_cleanup(&(*aead_ctx)->ctx);
  312. else
  313. {
  314. *aead_ctx = (SSL_AEAD_CTX*) OPENSSL_malloc(sizeof(SSL_AEAD_CTX));
  315. if (*aead_ctx == NULL)
  316. {
  317. OPENSSL_PUT_ERROR(SSL, tls1_aead_ctx_init, ERR_R_MALLOC_FAILURE);
  318. return 0;
  319. }
  320. }
  321. return 1;
  322. }
  323. static int tls1_change_cipher_state_aead(SSL *s, char is_read,
  324. const unsigned char *key, unsigned key_len,
  325. const unsigned char *iv, unsigned iv_len,
  326. const unsigned char *mac_secret, unsigned mac_secret_len)
  327. {
  328. const EVP_AEAD *aead = s->s3->tmp.new_aead;
  329. SSL_AEAD_CTX *aead_ctx;
  330. /* mac_key_and_key is used to merge the MAC and cipher keys for an AEAD
  331. * which simulates pre-AEAD cipher suites. It needs to be large enough
  332. * to cope with the largest pair of keys. */
  333. uint8_t mac_key_and_key[32 /* HMAC(SHA256) */ + 32 /* AES-256 */];
  334. if (mac_secret_len > 0)
  335. {
  336. /* This is a "stateful" AEAD (for compatibility with pre-AEAD
  337. * cipher suites). */
  338. if (mac_secret_len + key_len > sizeof(mac_key_and_key))
  339. {
  340. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  341. return 0;
  342. }
  343. memcpy(mac_key_and_key, mac_secret, mac_secret_len);
  344. memcpy(mac_key_and_key + mac_secret_len, key, key_len);
  345. key = mac_key_and_key;
  346. key_len += mac_secret_len;
  347. }
  348. if (is_read)
  349. {
  350. if (!tls1_aead_ctx_init(&s->aead_read_ctx))
  351. return 0;
  352. aead_ctx = s->aead_read_ctx;
  353. }
  354. else
  355. {
  356. if (!tls1_aead_ctx_init(&s->aead_write_ctx))
  357. return 0;
  358. aead_ctx = s->aead_write_ctx;
  359. }
  360. if (!EVP_AEAD_CTX_init(&aead_ctx->ctx, aead, key, key_len,
  361. EVP_AEAD_DEFAULT_TAG_LENGTH, NULL /* engine */))
  362. return 0;
  363. if (iv_len > sizeof(aead_ctx->fixed_nonce))
  364. {
  365. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  366. return 0;
  367. }
  368. memcpy(aead_ctx->fixed_nonce, iv, iv_len);
  369. aead_ctx->fixed_nonce_len = iv_len;
  370. aead_ctx->variable_nonce_len = 8; /* correct for all true AEADs so far. */
  371. if (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)
  372. aead_ctx->variable_nonce_len = 0;
  373. aead_ctx->variable_nonce_included_in_record =
  374. (s->s3->tmp.new_cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_VARIABLE_NONCE_INCLUDED_IN_RECORD) != 0;
  375. if (aead_ctx->variable_nonce_len + aead_ctx->fixed_nonce_len != EVP_AEAD_nonce_length(aead))
  376. {
  377. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_aead, ERR_R_INTERNAL_ERROR);
  378. return 0;
  379. }
  380. aead_ctx->tag_len = EVP_AEAD_max_overhead(aead);
  381. return 1;
  382. }
  383. /* tls1_change_cipher_state_cipher performs the work needed to switch cipher
  384. * states when using EVP_CIPHER. The argument |is_read| is true iff this
  385. * function is being called due to reading, as opposed to writing, a
  386. * ChangeCipherSpec message. In order to support export ciphersuites,
  387. * use_client_keys indicates whether the key material provided is in the
  388. * "client write" direction. */
  389. static int tls1_change_cipher_state_cipher(
  390. SSL *s, char is_read, char use_client_keys,
  391. const unsigned char *mac_secret, unsigned mac_secret_len,
  392. const unsigned char *key, unsigned key_len,
  393. const unsigned char *iv, unsigned iv_len)
  394. {
  395. const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
  396. EVP_CIPHER_CTX *cipher_ctx;
  397. EVP_MD_CTX *mac_ctx;
  398. if (is_read)
  399. {
  400. if (s->enc_read_ctx != NULL && !SSL_IS_DTLS(s))
  401. EVP_CIPHER_CTX_cleanup(s->enc_read_ctx);
  402. else if ((s->enc_read_ctx=EVP_CIPHER_CTX_new()) == NULL)
  403. goto err;
  404. cipher_ctx = s->enc_read_ctx;
  405. mac_ctx = ssl_replace_hash(&s->read_hash, NULL);
  406. memcpy(s->s3->read_mac_secret, mac_secret, mac_secret_len);
  407. s->s3->read_mac_secret_size = mac_secret_len;
  408. }
  409. else
  410. {
  411. /* When updating the write contexts for DTLS, we do not wish to
  412. * free the old ones because DTLS stores pointers to them in
  413. * order to implement retransmission. */
  414. if (s->enc_write_ctx != NULL && !SSL_IS_DTLS(s))
  415. EVP_CIPHER_CTX_cleanup(s->enc_write_ctx);
  416. else if ((s->enc_write_ctx=OPENSSL_malloc(sizeof(EVP_CIPHER_CTX))) == NULL)
  417. goto err;
  418. else
  419. /* make sure it's intialized in case we exit later with an error */
  420. EVP_CIPHER_CTX_init(s->enc_write_ctx);
  421. cipher_ctx = s->enc_write_ctx;
  422. if (SSL_IS_DTLS(s))
  423. {
  424. /* This is the same as ssl_replace_hash, but doesn't
  425. * free the old |s->write_hash|. */
  426. mac_ctx = EVP_MD_CTX_create();
  427. if (!mac_ctx)
  428. goto err;
  429. s->write_hash = mac_ctx;
  430. }
  431. else
  432. mac_ctx = ssl_replace_hash(&s->write_hash, NULL);
  433. memcpy(s->s3->write_mac_secret, mac_secret, mac_secret_len);
  434. s->s3->write_mac_secret_size = mac_secret_len;
  435. }
  436. EVP_PKEY *mac_key =
  437. EVP_PKEY_new_mac_key(s->s3->tmp.new_mac_pkey_type,
  438. NULL, mac_secret, mac_secret_len);
  439. if (!mac_key)
  440. return 0;
  441. EVP_DigestSignInit(mac_ctx, NULL, s->s3->tmp.new_hash, NULL, mac_key);
  442. EVP_PKEY_free(mac_key);
  443. EVP_CipherInit_ex(cipher_ctx, cipher, NULL /* engine */, key, iv, !is_read);
  444. return 1;
  445. err:
  446. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state_cipher, ERR_R_MALLOC_FAILURE);
  447. return 0;
  448. }
  449. int tls1_change_cipher_state(SSL *s, int which)
  450. {
  451. /* is_read is true if we have just read a ChangeCipherSpec message -
  452. * i.e. we need to update the read cipherspec. Otherwise we have just
  453. * written one. */
  454. const char is_read = (which & SSL3_CC_READ) != 0;
  455. /* use_client_keys is true if we wish to use the keys for the "client
  456. * write" direction. This is the case if we're a client sending a
  457. * ChangeCipherSpec, or a server reading a client's ChangeCipherSpec. */
  458. const char use_client_keys = which == SSL3_CHANGE_CIPHER_CLIENT_WRITE ||
  459. which == SSL3_CHANGE_CIPHER_SERVER_READ;
  460. const unsigned char *client_write_mac_secret, *server_write_mac_secret, *mac_secret;
  461. const unsigned char *client_write_key, *server_write_key, *key;
  462. const unsigned char *client_write_iv, *server_write_iv, *iv;
  463. const EVP_CIPHER *cipher = s->s3->tmp.new_sym_enc;
  464. const EVP_AEAD *aead = s->s3->tmp.new_aead;
  465. unsigned key_len, iv_len, mac_secret_len;
  466. const unsigned char *key_data;
  467. /* Reset sequence number to zero. */
  468. if (s->version != DTLS1_VERSION)
  469. memset(is_read ? s->s3->read_sequence : s->s3->write_sequence, 0, 8);
  470. /* key_arg is used for SSLv2. We don't need it for TLS. */
  471. s->session->key_arg_length = 0;
  472. mac_secret_len = s->s3->tmp.new_mac_secret_size;
  473. if (aead != NULL)
  474. {
  475. key_len = EVP_AEAD_key_length(aead);
  476. /* For "stateful" AEADs (i.e. compatibility with pre-AEAD
  477. * cipher suites) the key length reported by
  478. * |EVP_AEAD_key_length| will include the MAC key bytes. */
  479. if (key_len < mac_secret_len)
  480. {
  481. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  482. return 0;
  483. }
  484. key_len -= mac_secret_len;
  485. iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->s3->tmp.new_cipher);
  486. }
  487. else
  488. {
  489. key_len = EVP_CIPHER_key_length(cipher);
  490. if (EVP_CIPHER_mode(cipher) == EVP_CIPH_GCM_MODE)
  491. iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
  492. else
  493. iv_len = EVP_CIPHER_iv_length(cipher);
  494. }
  495. key_data = s->s3->tmp.key_block;
  496. client_write_mac_secret = key_data; key_data += mac_secret_len;
  497. server_write_mac_secret = key_data; key_data += mac_secret_len;
  498. client_write_key = key_data; key_data += key_len;
  499. server_write_key = key_data; key_data += key_len;
  500. client_write_iv = key_data; key_data += iv_len;
  501. server_write_iv = key_data; key_data += iv_len;
  502. if (use_client_keys)
  503. {
  504. mac_secret = client_write_mac_secret;
  505. key = client_write_key;
  506. iv = client_write_iv;
  507. }
  508. else
  509. {
  510. mac_secret = server_write_mac_secret;
  511. key = server_write_key;
  512. iv = server_write_iv;
  513. }
  514. if (key_data - s->s3->tmp.key_block != s->s3->tmp.key_block_length)
  515. {
  516. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  517. return 0;
  518. }
  519. if (aead != NULL)
  520. {
  521. if (!tls1_change_cipher_state_aead(s, is_read,
  522. key, key_len, iv, iv_len,
  523. mac_secret, mac_secret_len))
  524. return 0;
  525. }
  526. else
  527. {
  528. if (!tls1_change_cipher_state_cipher(s, is_read, use_client_keys,
  529. mac_secret, mac_secret_len,
  530. key, key_len,
  531. iv, iv_len))
  532. return 0;
  533. }
  534. return 1;
  535. }
  536. int tls1_setup_key_block(SSL *s)
  537. {
  538. unsigned char *p1,*p2=NULL;
  539. const EVP_CIPHER *c = NULL;
  540. const EVP_MD *hash = NULL;
  541. const EVP_AEAD *aead = NULL;
  542. int num;
  543. int mac_type= NID_undef,mac_secret_size=0;
  544. int ret=0;
  545. unsigned key_len, iv_len;
  546. #ifdef KSSL_DEBUG
  547. printf ("tls1_setup_key_block()\n");
  548. #endif /* KSSL_DEBUG */
  549. if (s->s3->tmp.key_block_length != 0)
  550. return(1);
  551. if (s->session->cipher &&
  552. ((s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_AEAD) ||
  553. (s->session->cipher->algorithm2 & SSL_CIPHER_ALGORITHM2_STATEFUL_AEAD)))
  554. {
  555. if (!ssl_cipher_get_evp_aead(s->session, &aead))
  556. goto cipher_unavailable_err;
  557. key_len = EVP_AEAD_key_length(aead);
  558. iv_len = SSL_CIPHER_AEAD_FIXED_NONCE_LEN(s->session->cipher);
  559. if (!ssl_cipher_get_mac(s->session, &hash, &mac_type, &mac_secret_size))
  560. goto cipher_unavailable_err;
  561. /* For "stateful" AEADs (i.e. compatibility with pre-AEAD
  562. * cipher suites) the key length reported by
  563. * |EVP_AEAD_key_length| will include the MAC key bytes. */
  564. if (key_len < mac_secret_size)
  565. {
  566. OPENSSL_PUT_ERROR(SSL, tls1_change_cipher_state, ERR_R_INTERNAL_ERROR);
  567. return 0;
  568. }
  569. key_len -= mac_secret_size;
  570. }
  571. else
  572. {
  573. if (!ssl_cipher_get_evp(s->session,&c,&hash,&mac_type,&mac_secret_size))
  574. goto cipher_unavailable_err;
  575. key_len = EVP_CIPHER_key_length(c);
  576. if (EVP_CIPHER_mode(c) == EVP_CIPH_GCM_MODE)
  577. iv_len = EVP_GCM_TLS_FIXED_IV_LEN;
  578. else
  579. iv_len = EVP_CIPHER_iv_length(c);
  580. }
  581. s->s3->tmp.new_aead=aead;
  582. s->s3->tmp.new_sym_enc=c;
  583. s->s3->tmp.new_hash=hash;
  584. s->s3->tmp.new_mac_pkey_type = mac_type;
  585. s->s3->tmp.new_mac_secret_size = mac_secret_size;
  586. num=key_len+mac_secret_size+iv_len;
  587. num*=2;
  588. ssl3_cleanup_key_block(s);
  589. if ((p1=(unsigned char *)OPENSSL_malloc(num)) == NULL)
  590. {
  591. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
  592. goto err;
  593. }
  594. s->s3->tmp.key_block_length=num;
  595. s->s3->tmp.key_block=p1;
  596. if ((p2=(unsigned char *)OPENSSL_malloc(num)) == NULL)
  597. {
  598. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, ERR_R_MALLOC_FAILURE);
  599. goto err;
  600. }
  601. #ifdef TLS_DEBUG
  602. printf("client random\n");
  603. { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->client_random[z],((z+1)%16)?' ':'\n'); }
  604. printf("server random\n");
  605. { int z; for (z=0; z<SSL3_RANDOM_SIZE; z++) printf("%02X%c",s->s3->server_random[z],((z+1)%16)?' ':'\n'); }
  606. printf("pre-master\n");
  607. { int z; for (z=0; z<s->session->master_key_length; z++) printf("%02X%c",s->session->master_key[z],((z+1)%16)?' ':'\n'); }
  608. #endif
  609. if (!tls1_generate_key_block(s,p1,p2,num))
  610. goto err;
  611. #ifdef TLS_DEBUG
  612. printf("\nkey block\n");
  613. { int z; for (z=0; z<num; z++) printf("%02X%c",p1[z],((z+1)%16)?' ':'\n'); }
  614. #endif
  615. if (s->method->version <= TLS1_VERSION &&
  616. (s->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0)
  617. {
  618. /* enable vulnerability countermeasure for CBC ciphers with
  619. * known-IV problem (http://www.openssl.org/~bodo/tls-cbc.txt)
  620. */
  621. s->s3->need_record_splitting = 1;
  622. if (s->session->cipher != NULL)
  623. {
  624. if (s->session->cipher->algorithm_enc == SSL_eNULL)
  625. s->s3->need_record_splitting = 0;
  626. #ifndef OPENSSL_NO_RC4
  627. if (s->session->cipher->algorithm_enc == SSL_RC4)
  628. s->s3->need_record_splitting = 0;
  629. #endif
  630. }
  631. }
  632. ret = 1;
  633. err:
  634. if (p2)
  635. {
  636. OPENSSL_cleanse(p2,num);
  637. OPENSSL_free(p2);
  638. }
  639. return(ret);
  640. cipher_unavailable_err:
  641. OPENSSL_PUT_ERROR(SSL, tls1_setup_key_block, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
  642. return 0;
  643. }
  644. /* tls1_enc encrypts/decrypts the record in |s->wrec| / |s->rrec|, respectively.
  645. *
  646. * Returns:
  647. * 0: (in non-constant time) if the record is publically invalid (i.e. too
  648. * short etc).
  649. * 1: if the record's padding is valid / the encryption was successful.
  650. * -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
  651. * an internal error occured.
  652. */
  653. int tls1_enc(SSL *s, int send)
  654. {
  655. SSL3_RECORD *rec;
  656. EVP_CIPHER_CTX *ds;
  657. unsigned long l;
  658. int bs,i,j,k,pad=0,ret,mac_size=0;
  659. const EVP_CIPHER *enc;
  660. const SSL_AEAD_CTX *aead;
  661. if (send)
  662. rec = &s->s3->wrec;
  663. else
  664. rec = &s->s3->rrec;
  665. if (send)
  666. aead = s->aead_write_ctx;
  667. else
  668. aead = s->aead_read_ctx;
  669. if (aead)
  670. {
  671. unsigned char ad[13], *seq, *in, *out, nonce[16];
  672. unsigned nonce_used;
  673. size_t n;
  674. seq = send ? s->s3->write_sequence : s->s3->read_sequence;
  675. if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
  676. {
  677. unsigned char dtlsseq[9], *p = dtlsseq;
  678. s2n(send ? s->d1->w_epoch : s->d1->r_epoch, p);
  679. memcpy(p, &seq[2], 6);
  680. memcpy(ad, dtlsseq, 8);
  681. }
  682. else
  683. {
  684. memcpy(ad, seq, 8);
  685. for (i=7; i>=0; i--) /* increment */
  686. {
  687. ++seq[i];
  688. if (seq[i] != 0)
  689. break;
  690. }
  691. }
  692. ad[8] = rec->type;
  693. ad[9] = (unsigned char)(s->version>>8);
  694. ad[10] = (unsigned char)(s->version);
  695. if (aead->fixed_nonce_len + aead->variable_nonce_len > sizeof(nonce) ||
  696. aead->variable_nonce_len > 8)
  697. return -1; /* internal error - should never happen. */
  698. memcpy(nonce, aead->fixed_nonce, aead->fixed_nonce_len);
  699. nonce_used = aead->fixed_nonce_len;
  700. if (send)
  701. {
  702. size_t len = rec->length;
  703. size_t eivlen = 0;
  704. in = rec->input;
  705. out = rec->data;
  706. /* When sending we use the sequence number as the
  707. * variable part of the nonce. */
  708. if (aead->variable_nonce_len > 8)
  709. return -1;
  710. memcpy(nonce + nonce_used, ad, aead->variable_nonce_len);
  711. nonce_used += aead->variable_nonce_len;
  712. /* in do_ssl3_write, rec->input is moved forward by
  713. * variable_nonce_len in order to leave space for the
  714. * variable nonce. Thus we can copy the sequence number
  715. * bytes into place without overwriting any of the
  716. * plaintext. */
  717. if (aead->variable_nonce_included_in_record)
  718. {
  719. memcpy(out, ad, aead->variable_nonce_len);
  720. len -= aead->variable_nonce_len;
  721. eivlen = aead->variable_nonce_len;
  722. }
  723. ad[11] = len >> 8;
  724. ad[12] = len & 0xff;
  725. if (!EVP_AEAD_CTX_seal(
  726. &aead->ctx,
  727. out + eivlen, &n, len + aead->tag_len,
  728. nonce, nonce_used,
  729. in + eivlen, len,
  730. ad, sizeof(ad)))
  731. {
  732. return -1;
  733. }
  734. if (aead->variable_nonce_included_in_record)
  735. n += aead->variable_nonce_len;
  736. }
  737. else
  738. {
  739. /* receive */
  740. size_t len = rec->length;
  741. if (rec->data != rec->input)
  742. return -1; /* internal error - should never happen. */
  743. out = in = rec->input;
  744. if (len < aead->variable_nonce_len)
  745. return 0;
  746. memcpy(nonce + nonce_used,
  747. aead->variable_nonce_included_in_record ? in : ad,
  748. aead->variable_nonce_len);
  749. nonce_used += aead->variable_nonce_len;
  750. if (aead->variable_nonce_included_in_record)
  751. {
  752. in += aead->variable_nonce_len;
  753. len -= aead->variable_nonce_len;
  754. out += aead->variable_nonce_len;
  755. }
  756. if (len < aead->tag_len)
  757. return 0;
  758. len -= aead->tag_len;
  759. ad[11] = len >> 8;
  760. ad[12] = len & 0xff;
  761. if (!EVP_AEAD_CTX_open(
  762. &aead->ctx,
  763. out, &n, len,
  764. nonce, nonce_used,
  765. in, len + aead->tag_len,
  766. ad, sizeof(ad)))
  767. {
  768. return -1;
  769. }
  770. rec->data = rec->input = out;
  771. }
  772. rec->length = n;
  773. return 1;
  774. }
  775. if (send)
  776. {
  777. ds=s->enc_write_ctx;
  778. rec= &(s->s3->wrec);
  779. if (s->enc_write_ctx == NULL)
  780. enc=NULL;
  781. else
  782. {
  783. int ivlen;
  784. enc=EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
  785. /* For TLSv1.1 and later explicit IV */
  786. if (SSL_USE_EXPLICIT_IV(s)
  787. && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
  788. ivlen = EVP_CIPHER_iv_length(enc);
  789. else
  790. ivlen = 0;
  791. if (ivlen > 1)
  792. {
  793. if ( rec->data != rec->input)
  794. /* we can't write into the input stream:
  795. * Can this ever happen?? (steve)
  796. */
  797. fprintf(stderr,
  798. "%s:%d: rec->data != rec->input\n",
  799. __FILE__, __LINE__);
  800. else if (RAND_bytes(rec->input, ivlen) <= 0)
  801. return -1;
  802. }
  803. }
  804. }
  805. else
  806. {
  807. ds=s->enc_read_ctx;
  808. rec= &(s->s3->rrec);
  809. if (s->enc_read_ctx == NULL)
  810. enc=NULL;
  811. else
  812. enc=EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
  813. }
  814. #ifdef KSSL_DEBUG
  815. printf("tls1_enc(%d)\n", send);
  816. #endif /* KSSL_DEBUG */
  817. if ((s->session == NULL) || (ds == NULL) || (enc == NULL))
  818. {
  819. memmove(rec->data,rec->input,rec->length);
  820. rec->input=rec->data;
  821. ret = 1;
  822. }
  823. else
  824. {
  825. l=rec->length;
  826. bs=EVP_CIPHER_block_size(ds->cipher);
  827. if ((bs != 1) && send)
  828. {
  829. i=bs-((int)l%bs);
  830. /* Add weird padding of upto 256 bytes */
  831. /* we need to add 'i' padding bytes of value j */
  832. j=i-1;
  833. if (s->options & SSL_OP_TLS_BLOCK_PADDING_BUG)
  834. {
  835. if (s->s3->flags & TLS1_FLAGS_TLS_PADDING_BUG)
  836. j++;
  837. }
  838. for (k=(int)l; k<(int)(l+i); k++)
  839. rec->input[k]=j;
  840. l+=i;
  841. rec->length+=i;
  842. }
  843. #ifdef KSSL_DEBUG
  844. {
  845. unsigned long ui;
  846. printf("EVP_Cipher(ds=%p,rec->data=%p,rec->input=%p,l=%ld) ==>\n",
  847. ds,rec->data,rec->input,l);
  848. printf("\tEVP_CIPHER_CTX: %d buf_len, %d key_len [%d %d], %d iv_len\n",
  849. ds->buf_len, ds->cipher->key_len,
  850. DES_KEY_SZ, DES_SCHEDULE_SZ,
  851. ds->cipher->iv_len);
  852. printf("\t\tIV: ");
  853. for (i=0; i<ds->cipher->iv_len; i++) printf("%02X", ds->iv[i]);
  854. printf("\n");
  855. printf("\trec->input=");
  856. for (ui=0; ui<l; ui++) printf(" %02x", rec->input[ui]);
  857. printf("\n");
  858. }
  859. #endif /* KSSL_DEBUG */
  860. if (!send)
  861. {
  862. if (l == 0 || l%bs != 0)
  863. return 0;
  864. }
  865. i = EVP_Cipher(ds,rec->data,rec->input,l);
  866. if ((EVP_CIPHER_flags(ds->cipher)&EVP_CIPH_FLAG_CUSTOM_CIPHER)
  867. ?(i<0)
  868. :(i==0))
  869. return -1; /* AEAD can fail to verify MAC */
  870. if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE && !send)
  871. {
  872. rec->data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  873. rec->input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
  874. rec->length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
  875. }
  876. #ifdef KSSL_DEBUG
  877. {
  878. unsigned long i;
  879. printf("\trec->data=");
  880. for (i=0; i<l; i++)
  881. printf(" %02x", rec->data[i]); printf("\n");
  882. }
  883. #endif /* KSSL_DEBUG */
  884. ret = 1;
  885. if (EVP_MD_CTX_md(s->read_hash) != NULL)
  886. mac_size = EVP_MD_CTX_size(s->read_hash);
  887. if ((bs != 1) && !send)
  888. ret = tls1_cbc_remove_padding(s, rec, bs, mac_size);
  889. if (pad && !send)
  890. rec->length -= pad;
  891. }
  892. return ret;
  893. }
  894. int tls1_cert_verify_mac(SSL *s, int md_nid, unsigned char *out)
  895. {
  896. unsigned int ret;
  897. EVP_MD_CTX ctx, *d=NULL;
  898. int i;
  899. if (s->s3->handshake_buffer)
  900. if (!ssl3_digest_cached_records(s))
  901. return 0;
  902. for (i=0;i<SSL_MAX_DIGEST;i++)
  903. {
  904. if (s->s3->handshake_dgst[i]&&EVP_MD_CTX_type(s->s3->handshake_dgst[i])==md_nid)
  905. {
  906. d=s->s3->handshake_dgst[i];
  907. break;
  908. }
  909. }
  910. if (!d) {
  911. OPENSSL_PUT_ERROR(SSL, tls1_cert_verify_mac, SSL_R_NO_REQUIRED_DIGEST);
  912. return 0;
  913. }
  914. EVP_MD_CTX_init(&ctx);
  915. EVP_MD_CTX_copy_ex(&ctx,d);
  916. EVP_DigestFinal_ex(&ctx,out,&ret);
  917. EVP_MD_CTX_cleanup(&ctx);
  918. return((int)ret);
  919. }
  920. /* tls1_handshake_digest calculates the current handshake hash and writes it to
  921. * |out|, which has space for |out_len| bytes. It returns the number of bytes
  922. * written or -1 in the event of an error. This function works on a copy of the
  923. * underlying digests so can be called multiple times and prior to the final
  924. * update etc. */
  925. int tls1_handshake_digest(SSL *s, unsigned char *out, size_t out_len)
  926. {
  927. const EVP_MD *md;
  928. EVP_MD_CTX ctx;
  929. int i, err = 0, len = 0;
  930. long mask;
  931. EVP_MD_CTX_init(&ctx);
  932. for (i = 0; ssl_get_handshake_digest(i, &mask, &md); i++)
  933. {
  934. int hash_size;
  935. unsigned int digest_len;
  936. EVP_MD_CTX *hdgst = s->s3->handshake_dgst[i];
  937. if ((mask & ssl_get_algorithm2(s)) == 0)
  938. continue;
  939. hash_size = EVP_MD_size(md);
  940. if (!hdgst || hash_size < 0 || (size_t)hash_size > out_len)
  941. {
  942. err = 1;
  943. break;
  944. }
  945. if (!EVP_MD_CTX_copy_ex(&ctx, hdgst) ||
  946. !EVP_DigestFinal_ex(&ctx, out, &digest_len) ||
  947. digest_len != (unsigned int)hash_size) /* internal error */
  948. {
  949. err = 1;
  950. break;
  951. }
  952. out += digest_len;
  953. out_len -= digest_len;
  954. len += digest_len;
  955. }
  956. EVP_MD_CTX_cleanup(&ctx);
  957. if (err != 0)
  958. return -1;
  959. return len;
  960. }
  961. int tls1_final_finish_mac(SSL *s,
  962. const char *str, int slen, unsigned char *out)
  963. {
  964. unsigned char buf[2*EVP_MAX_MD_SIZE];
  965. unsigned char buf2[12];
  966. int err=0;
  967. int digests_len;
  968. if (s->s3->handshake_buffer)
  969. if (!ssl3_digest_cached_records(s))
  970. return 0;
  971. digests_len = tls1_handshake_digest(s, buf, sizeof(buf));
  972. if (digests_len < 0)
  973. {
  974. err = 1;
  975. digests_len = 0;
  976. }
  977. if (!tls1_PRF(ssl_get_algorithm2(s),
  978. str,slen, buf, digests_len, NULL,0, NULL,0, NULL,0,
  979. s->session->master_key,s->session->master_key_length,
  980. out,buf2,sizeof buf2))
  981. err = 1;
  982. if (err)
  983. return 0;
  984. else
  985. return sizeof buf2;
  986. }
  987. int tls1_mac(SSL *ssl, unsigned char *md, int send)
  988. {
  989. SSL3_RECORD *rec;
  990. unsigned char *seq;
  991. EVP_MD_CTX *hash;
  992. size_t md_size, orig_len;
  993. int i;
  994. EVP_MD_CTX hmac, *mac_ctx;
  995. unsigned char header[13];
  996. int t;
  997. if (send)
  998. {
  999. rec= &(ssl->s3->wrec);
  1000. seq= &(ssl->s3->write_sequence[0]);
  1001. hash=ssl->write_hash;
  1002. }
  1003. else
  1004. {
  1005. rec= &(ssl->s3->rrec);
  1006. seq= &(ssl->s3->read_sequence[0]);
  1007. hash=ssl->read_hash;
  1008. }
  1009. t=EVP_MD_CTX_size(hash);
  1010. assert(t >= 0);
  1011. md_size=t;
  1012. if (!EVP_MD_CTX_copy(&hmac,hash))
  1013. return -1;
  1014. mac_ctx = &hmac;
  1015. if (SSL_IS_DTLS(ssl))
  1016. {
  1017. unsigned char dtlsseq[8],*p=dtlsseq;
  1018. s2n(send?ssl->d1->w_epoch:ssl->d1->r_epoch, p);
  1019. memcpy (p,&seq[2],6);
  1020. memcpy(header, dtlsseq, 8);
  1021. }
  1022. else
  1023. memcpy(header, seq, 8);
  1024. /* kludge: tls1_cbc_remove_padding passes padding length in rec->type */
  1025. orig_len = rec->length+md_size+((unsigned int)rec->type>>8);
  1026. rec->type &= 0xff;
  1027. header[8]=rec->type;
  1028. header[9]=(unsigned char)(ssl->version>>8);
  1029. header[10]=(unsigned char)(ssl->version);
  1030. header[11]=(rec->length)>>8;
  1031. header[12]=(rec->length)&0xff;
  1032. if (!send &&
  1033. EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
  1034. ssl3_cbc_record_digest_supported(mac_ctx))
  1035. {
  1036. /* This is a CBC-encrypted record. We must avoid leaking any
  1037. * timing-side channel information about how many blocks of
  1038. * data we are hashing because that gives an attacker a
  1039. * timing-oracle. */
  1040. ssl3_cbc_digest_record(
  1041. mac_ctx,
  1042. md, &md_size,
  1043. header, rec->input,
  1044. rec->length + md_size, orig_len,
  1045. ssl->s3->read_mac_secret,
  1046. ssl->s3->read_mac_secret_size,
  1047. 0 /* not SSLv3 */);
  1048. }
  1049. else
  1050. {
  1051. EVP_DigestSignUpdate(mac_ctx,header,sizeof(header));
  1052. EVP_DigestSignUpdate(mac_ctx,rec->input,rec->length);
  1053. t=EVP_DigestSignFinal(mac_ctx,md,&md_size);
  1054. assert(t > 0);
  1055. }
  1056. EVP_MD_CTX_cleanup(&hmac);
  1057. if (!SSL_IS_DTLS(ssl))
  1058. {
  1059. for (i=7; i>=0; i--)
  1060. {
  1061. ++seq[i];
  1062. if (seq[i] != 0) break;
  1063. }
  1064. }
  1065. return(md_size);
  1066. }
  1067. int tls1_generate_master_secret(SSL *s, unsigned char *out, unsigned char *p,
  1068. int len)
  1069. {
  1070. unsigned char buff[SSL_MAX_MASTER_KEY_LENGTH];
  1071. const void *co = NULL, *so = NULL;
  1072. int col = 0, sol = 0;
  1073. #ifdef KSSL_DEBUG
  1074. printf ("tls1_generate_master_secret(%p,%p, %p, %d)\n", s,out, p,len);
  1075. #endif /* KSSL_DEBUG */
  1076. tls1_PRF(ssl_get_algorithm2(s),
  1077. TLS_MD_MASTER_SECRET_CONST,TLS_MD_MASTER_SECRET_CONST_SIZE,
  1078. s->s3->client_random,SSL3_RANDOM_SIZE,
  1079. co, col,
  1080. s->s3->server_random,SSL3_RANDOM_SIZE,
  1081. so, sol,
  1082. p,len,
  1083. s->session->master_key,buff,sizeof buff);
  1084. #ifdef SSL_DEBUG
  1085. fprintf(stderr, "Premaster Secret:\n");
  1086. BIO_dump_fp(stderr, (char *)p, len);
  1087. fprintf(stderr, "Client Random:\n");
  1088. BIO_dump_fp(stderr, (char *)s->s3->client_random, SSL3_RANDOM_SIZE);
  1089. fprintf(stderr, "Server Random:\n");
  1090. BIO_dump_fp(stderr, (char *)s->s3->server_random, SSL3_RANDOM_SIZE);
  1091. fprintf(stderr, "Master Secret:\n");
  1092. BIO_dump_fp(stderr, (char *)s->session->master_key, SSL3_MASTER_SECRET_SIZE);
  1093. #endif
  1094. #ifdef OPENSSL_SSL_TRACE_CRYPTO
  1095. if (s->msg_callback)
  1096. {
  1097. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_PREMASTER,
  1098. p, len, s, s->msg_callback_arg);
  1099. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_CLIENT_RANDOM,
  1100. s->s3->client_random, SSL3_RANDOM_SIZE,
  1101. s, s->msg_callback_arg);
  1102. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_SERVER_RANDOM,
  1103. s->s3->server_random, SSL3_RANDOM_SIZE,
  1104. s, s->msg_callback_arg);
  1105. s->msg_callback(2, s->version, TLS1_RT_CRYPTO_MASTER,
  1106. s->session->master_key,
  1107. SSL3_MASTER_SECRET_SIZE,
  1108. s, s->msg_callback_arg);
  1109. }
  1110. #endif
  1111. #ifdef KSSL_DEBUG
  1112. printf ("tls1_generate_master_secret() complete\n");
  1113. #endif /* KSSL_DEBUG */
  1114. return(SSL3_MASTER_SECRET_SIZE);
  1115. }
  1116. int tls1_export_keying_material(SSL *s, unsigned char *out, size_t olen,
  1117. const char *label, size_t llen, const unsigned char *context,
  1118. size_t contextlen, int use_context)
  1119. {
  1120. unsigned char *buff;
  1121. unsigned char *val = NULL;
  1122. size_t vallen, currentvalpos;
  1123. int rv;
  1124. #ifdef KSSL_DEBUG
  1125. printf ("tls1_export_keying_material(%p,%p,%d,%s,%d,%p,%d)\n", s, out, olen, label, llen, p, plen);
  1126. #endif /* KSSL_DEBUG */
  1127. buff = OPENSSL_malloc(olen);
  1128. if (buff == NULL) goto err2;
  1129. /* construct PRF arguments
  1130. * we construct the PRF argument ourself rather than passing separate
  1131. * values into the TLS PRF to ensure that the concatenation of values
  1132. * does not create a prohibited label.
  1133. */
  1134. vallen = llen + SSL3_RANDOM_SIZE * 2;
  1135. if (use_context)
  1136. {
  1137. vallen += 2 + contextlen;
  1138. }
  1139. val = OPENSSL_malloc(vallen);
  1140. if (val == NULL) goto err2;
  1141. currentvalpos = 0;
  1142. memcpy(val + currentvalpos, (unsigned char *) label, llen);
  1143. currentvalpos += llen;
  1144. memcpy(val + currentvalpos, s->s3->client_random, SSL3_RANDOM_SIZE);
  1145. currentvalpos += SSL3_RANDOM_SIZE;
  1146. memcpy(val + currentvalpos, s->s3->server_random, SSL3_RANDOM_SIZE);
  1147. currentvalpos += SSL3_RANDOM_SIZE;
  1148. if (use_context)
  1149. {
  1150. val[currentvalpos] = (contextlen >> 8) & 0xff;
  1151. currentvalpos++;
  1152. val[currentvalpos] = contextlen & 0xff;
  1153. currentvalpos++;
  1154. if ((contextlen > 0) || (context != NULL))
  1155. {
  1156. memcpy(val + currentvalpos, context, contextlen);
  1157. }
  1158. }
  1159. /* disallow prohibited labels
  1160. * note that SSL3_RANDOM_SIZE > max(prohibited label len) =
  1161. * 15, so size of val > max(prohibited label len) = 15 and the
  1162. * comparisons won't have buffer overflow
  1163. */
  1164. if (memcmp(val, TLS_MD_CLIENT_FINISH_CONST,
  1165. TLS_MD_CLIENT_FINISH_CONST_SIZE) == 0) goto err1;
  1166. if (memcmp(val, TLS_MD_SERVER_FINISH_CONST,
  1167. TLS_MD_SERVER_FINISH_CONST_SIZE) == 0) goto err1;
  1168. if (memcmp(val, TLS_MD_MASTER_SECRET_CONST,
  1169. TLS_MD_MASTER_SECRET_CONST_SIZE) == 0) goto err1;
  1170. if (memcmp(val, TLS_MD_KEY_EXPANSION_CONST,
  1171. TLS_MD_KEY_EXPANSION_CONST_SIZE) == 0) goto err1;
  1172. rv = tls1_PRF(ssl_get_algorithm2(s),
  1173. val, vallen,
  1174. NULL, 0,
  1175. NULL, 0,
  1176. NULL, 0,
  1177. NULL, 0,
  1178. s->session->master_key,s->session->master_key_length,
  1179. out,buff,olen);
  1180. #ifdef KSSL_DEBUG
  1181. printf ("tls1_export_keying_material() complete\n");
  1182. #endif /* KSSL_DEBUG */
  1183. goto ret;
  1184. err1:
  1185. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
  1186. rv = 0;
  1187. goto ret;
  1188. err2:
  1189. OPENSSL_PUT_ERROR(SSL, tls1_export_keying_material, ERR_R_MALLOC_FAILURE);
  1190. rv = 0;
  1191. ret:
  1192. if (buff != NULL) OPENSSL_free(buff);
  1193. if (val != NULL) OPENSSL_free(val);
  1194. return(rv);
  1195. }
  1196. int tls1_alert_code(int code)
  1197. {
  1198. switch (code)
  1199. {
  1200. case SSL_AD_CLOSE_NOTIFY: return(SSL3_AD_CLOSE_NOTIFY);
  1201. case SSL_AD_UNEXPECTED_MESSAGE: return(SSL3_AD_UNEXPECTED_MESSAGE);
  1202. case SSL_AD_BAD_RECORD_MAC: return(SSL3_AD_BAD_RECORD_MAC);
  1203. case SSL_AD_DECRYPTION_FAILED: return(TLS1_AD_DECRYPTION_FAILED);
  1204. case SSL_AD_RECORD_OVERFLOW: return(TLS1_AD_RECORD_OVERFLOW);
  1205. case SSL_AD_DECOMPRESSION_FAILURE:return(SSL3_AD_DECOMPRESSION_FAILURE);
  1206. case SSL_AD_HANDSHAKE_FAILURE: return(SSL3_AD_HANDSHAKE_FAILURE);
  1207. case SSL_AD_NO_CERTIFICATE: return(-1);
  1208. case SSL_AD_BAD_CERTIFICATE: return(SSL3_AD_BAD_CERTIFICATE);
  1209. case SSL_AD_UNSUPPORTED_CERTIFICATE:return(SSL3_AD_UNSUPPORTED_CERTIFICATE);
  1210. case SSL_AD_CERTIFICATE_REVOKED:return(SSL3_AD_CERTIFICATE_REVOKED);
  1211. case SSL_AD_CERTIFICATE_EXPIRED:return(SSL3_AD_CERTIFICATE_EXPIRED);
  1212. case SSL_AD_CERTIFICATE_UNKNOWN:return(SSL3_AD_CERTIFICATE_UNKNOWN);
  1213. case SSL_AD_ILLEGAL_PARAMETER: return(SSL3_AD_ILLEGAL_PARAMETER);
  1214. case SSL_AD_UNKNOWN_CA: return(TLS1_AD_UNKNOWN_CA);
  1215. case SSL_AD_ACCESS_DENIED: return(TLS1_AD_ACCESS_DENIED);
  1216. case SSL_AD_DECODE_ERROR: return(TLS1_AD_DECODE_ERROR);
  1217. case SSL_AD_DECRYPT_ERROR: return(TLS1_AD_DECRYPT_ERROR);
  1218. case SSL_AD_EXPORT_RESTRICTION: return(TLS1_AD_EXPORT_RESTRICTION);
  1219. case SSL_AD_PROTOCOL_VERSION: return(TLS1_AD_PROTOCOL_VERSION);
  1220. case SSL_AD_INSUFFICIENT_SECURITY:return(TLS1_AD_INSUFFICIENT_SECURITY);
  1221. case SSL_AD_INTERNAL_ERROR: return(TLS1_AD_INTERNAL_ERROR);
  1222. case SSL_AD_USER_CANCELLED: return(TLS1_AD_USER_CANCELLED);
  1223. case SSL_AD_NO_RENEGOTIATION: return(TLS1_AD_NO_RENEGOTIATION);
  1224. case SSL_AD_UNSUPPORTED_EXTENSION: return(TLS1_AD_UNSUPPORTED_EXTENSION);
  1225. case SSL_AD_CERTIFICATE_UNOBTAINABLE: return(TLS1_AD_CERTIFICATE_UNOBTAINABLE);
  1226. case SSL_AD_UNRECOGNIZED_NAME: return(TLS1_AD_UNRECOGNIZED_NAME);
  1227. case SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE: return(TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE);
  1228. case SSL_AD_BAD_CERTIFICATE_HASH_VALUE: return(TLS1_AD_BAD_CERTIFICATE_HASH_VALUE);
  1229. case SSL_AD_UNKNOWN_PSK_IDENTITY:return(TLS1_AD_UNKNOWN_PSK_IDENTITY);
  1230. case SSL_AD_INAPPROPRIATE_FALLBACK:return(SSL3_AD_INAPPROPRIATE_FALLBACK);
  1231. #if 0 /* not appropriate for TLS, not used for DTLS */
  1232. case DTLS1_AD_MISSING_HANDSHAKE_MESSAGE: return
  1233. (DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
  1234. #endif
  1235. default: return(-1);
  1236. }
  1237. }